From b63ada6816f607fb295dc75e30b478f1afbf5dfc Mon Sep 17 00:00:00 2001 From: Zhen Tang Date: Sun, 23 Jun 2013 08:37:12 -0700 Subject: [PATCH 001/196] Initial commit --- README.md | 4 ++++ 1 file changed, 4 insertions(+) create mode 100644 README.md diff --git a/README.md b/README.md new file mode 100644 index 00000000..329db5d3 --- /dev/null +++ b/README.md @@ -0,0 +1,4 @@ +Bench4Q-Agent +============= + +Agent node of Bench4Q From 7e2015843721e87e952bbcc88d687f4882a4491c Mon Sep 17 00:00:00 2001 From: Zhen Tang Date: Sun, 23 Jun 2013 23:47:08 +0800 Subject: [PATCH 002/196] Use jetty as http server. A simple service added. --- README.md | 2 +- pom.xml | 44 ++++++++++++ .../java/org/bench4q/agent/AgentServer.java | 67 +++++++++++++++++++ src/main/java/org/bench4q/agent/Main.java | 9 +++ .../org/bench4q/agent/api/HomeController.java | 16 +++++ src/main/resources/application-context.xml | 10 +++ 6 files changed, 147 insertions(+), 1 deletion(-) create mode 100644 pom.xml create mode 100644 src/main/java/org/bench4q/agent/AgentServer.java create mode 100644 src/main/java/org/bench4q/agent/Main.java create mode 100644 src/main/java/org/bench4q/agent/api/HomeController.java create mode 100644 src/main/resources/application-context.xml diff --git a/README.md b/README.md index 329db5d3..5f85d5cd 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,4 @@ Bench4Q-Agent ============= -Agent node of Bench4Q +Agent Node of Bench4Q diff --git a/pom.xml b/pom.xml new file mode 100644 index 00000000..8d41cc37 --- /dev/null +++ b/pom.xml @@ -0,0 +1,44 @@ + + 4.0.0 + org.bench4q + bench4q-agent + jar + 0.0.1-SNAPSHOT + Bench4Q Agent + Bench4Q Agent + + TCSE, ISCAS + + + + junit + junit + 4.11 + test + + + org.eclipse.jetty + jetty-server + 8.1.11.v20130520 + + + org.eclipse.jetty + jetty-servlet + 8.1.11.v20130520 + + + org.springframework + spring-webmvc + 3.2.3.RELEASE + + + org.codehaus.jackson + jackson-mapper-asl + 1.9.12 + + + + bench4q-agent + + \ No newline at end of file diff --git a/src/main/java/org/bench4q/agent/AgentServer.java b/src/main/java/org/bench4q/agent/AgentServer.java new file mode 100644 index 00000000..f3a4023b --- /dev/null +++ b/src/main/java/org/bench4q/agent/AgentServer.java @@ -0,0 +1,67 @@ +package org.bench4q.agent; + +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.web.servlet.DispatcherServlet; + +public class AgentServer { + private Server server; + private int port; + + private Server getServer() { + return server; + } + + private void setServer(Server server) { + this.server = server; + } + + private int getPort() { + return port; + } + + private void setPort(int port) { + this.port = port; + } + + public AgentServer(int port) { + this.setPort(port); + } + + 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*:/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); + } + } +} diff --git a/src/main/java/org/bench4q/agent/Main.java b/src/main/java/org/bench4q/agent/Main.java new file mode 100644 index 00000000..4ce89fc6 --- /dev/null +++ b/src/main/java/org/bench4q/agent/Main.java @@ -0,0 +1,9 @@ +package org.bench4q.agent; + +public class Main { + + public static void main(String[] args) { + AgentServer agentServer = new AgentServer(6565); + agentServer.start(); + } +} diff --git a/src/main/java/org/bench4q/agent/api/HomeController.java b/src/main/java/org/bench4q/agent/api/HomeController.java new file mode 100644 index 00000000..6203417b --- /dev/null +++ b/src/main/java/org/bench4q/agent/api/HomeController.java @@ -0,0 +1,16 @@ +package org.bench4q.agent.api; + +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 { + @RequestMapping(value = { "/" }, method = RequestMethod.GET) + @ResponseBody + public String index() { + return "It works!"; + } +} \ No newline at end of file diff --git a/src/main/resources/application-context.xml b/src/main/resources/application-context.xml new file mode 100644 index 00000000..6c72d7ff --- /dev/null +++ b/src/main/resources/application-context.xml @@ -0,0 +1,10 @@ + + + + + From ee57a36ba20db30f9bf18df9fff6c8793b2b9912 Mon Sep 17 00:00:00 2001 From: Zhen Tang Date: Wed, 26 Jun 2013 00:06:05 +0800 Subject: [PATCH 003/196] Plugin annotations and abstract classes added. --- .../agent/plugin/AbstractControlFunction.java | 5 +++++ .../bench4q/agent/plugin/AbstractFunction.java | 5 +++++ .../org/bench4q/agent/plugin/AbstractPlugin.java | 5 +++++ .../agent/plugin/AbstractSampleFunction.java | 5 +++++ .../agent/plugin/AbstractTestFunction.java | 5 +++++ .../agent/plugin/AbstractTimerFunction.java | 5 +++++ .../agent/plugin/annotation/Function.java | 16 ++++++++++++++++ .../agent/plugin/annotation/FunctionType.java | 5 +++++ .../agent/plugin/annotation/Parameter.java | 7 +++++++ .../bench4q/agent/plugin/annotation/Plugin.java | 11 +++++++++++ 10 files changed, 69 insertions(+) create mode 100644 src/main/java/org/bench4q/agent/plugin/AbstractControlFunction.java create mode 100644 src/main/java/org/bench4q/agent/plugin/AbstractFunction.java create mode 100644 src/main/java/org/bench4q/agent/plugin/AbstractPlugin.java create mode 100644 src/main/java/org/bench4q/agent/plugin/AbstractSampleFunction.java create mode 100644 src/main/java/org/bench4q/agent/plugin/AbstractTestFunction.java create mode 100644 src/main/java/org/bench4q/agent/plugin/AbstractTimerFunction.java create mode 100644 src/main/java/org/bench4q/agent/plugin/annotation/Function.java create mode 100644 src/main/java/org/bench4q/agent/plugin/annotation/FunctionType.java create mode 100644 src/main/java/org/bench4q/agent/plugin/annotation/Parameter.java create mode 100644 src/main/java/org/bench4q/agent/plugin/annotation/Plugin.java diff --git a/src/main/java/org/bench4q/agent/plugin/AbstractControlFunction.java b/src/main/java/org/bench4q/agent/plugin/AbstractControlFunction.java new file mode 100644 index 00000000..c6f2905a --- /dev/null +++ b/src/main/java/org/bench4q/agent/plugin/AbstractControlFunction.java @@ -0,0 +1,5 @@ +package org.bench4q.agent.plugin; + +public abstract class AbstractControlFunction extends AbstractFunction { + +} diff --git a/src/main/java/org/bench4q/agent/plugin/AbstractFunction.java b/src/main/java/org/bench4q/agent/plugin/AbstractFunction.java new file mode 100644 index 00000000..ee495bf7 --- /dev/null +++ b/src/main/java/org/bench4q/agent/plugin/AbstractFunction.java @@ -0,0 +1,5 @@ +package org.bench4q.agent.plugin; + +public abstract class AbstractFunction { + +} diff --git a/src/main/java/org/bench4q/agent/plugin/AbstractPlugin.java b/src/main/java/org/bench4q/agent/plugin/AbstractPlugin.java new file mode 100644 index 00000000..7eb211a7 --- /dev/null +++ b/src/main/java/org/bench4q/agent/plugin/AbstractPlugin.java @@ -0,0 +1,5 @@ +package org.bench4q.agent.plugin; + +public abstract class AbstractPlugin { + +} diff --git a/src/main/java/org/bench4q/agent/plugin/AbstractSampleFunction.java b/src/main/java/org/bench4q/agent/plugin/AbstractSampleFunction.java new file mode 100644 index 00000000..11f31483 --- /dev/null +++ b/src/main/java/org/bench4q/agent/plugin/AbstractSampleFunction.java @@ -0,0 +1,5 @@ +package org.bench4q.agent.plugin; + +public abstract class AbstractSampleFunction extends AbstractFunction { + +} diff --git a/src/main/java/org/bench4q/agent/plugin/AbstractTestFunction.java b/src/main/java/org/bench4q/agent/plugin/AbstractTestFunction.java new file mode 100644 index 00000000..391f8167 --- /dev/null +++ b/src/main/java/org/bench4q/agent/plugin/AbstractTestFunction.java @@ -0,0 +1,5 @@ +package org.bench4q.agent.plugin; + +public abstract class AbstractTestFunction extends AbstractFunction { + +} diff --git a/src/main/java/org/bench4q/agent/plugin/AbstractTimerFunction.java b/src/main/java/org/bench4q/agent/plugin/AbstractTimerFunction.java new file mode 100644 index 00000000..0a7b4a88 --- /dev/null +++ b/src/main/java/org/bench4q/agent/plugin/AbstractTimerFunction.java @@ -0,0 +1,5 @@ +package org.bench4q.agent.plugin; + +public abstract class AbstractTimerFunction extends AbstractFunction { + +} diff --git a/src/main/java/org/bench4q/agent/plugin/annotation/Function.java b/src/main/java/org/bench4q/agent/plugin/annotation/Function.java new file mode 100644 index 00000000..e5c38e17 --- /dev/null +++ b/src/main/java/org/bench4q/agent/plugin/annotation/Function.java @@ -0,0 +1,16 @@ +package org.bench4q.agent.plugin.annotation; + +public @interface Function { + + String name(); + + Class plugin(); + + int number(); + + FunctionType functionType(); + + Parameter[] parameters(); + + String help(); +} \ No newline at end of file diff --git a/src/main/java/org/bench4q/agent/plugin/annotation/FunctionType.java b/src/main/java/org/bench4q/agent/plugin/annotation/FunctionType.java new file mode 100644 index 00000000..0aaa9413 --- /dev/null +++ b/src/main/java/org/bench4q/agent/plugin/annotation/FunctionType.java @@ -0,0 +1,5 @@ +package org.bench4q.agent.plugin.annotation; + +public enum FunctionType { + Sample, Test, Timer, Control +} diff --git a/src/main/java/org/bench4q/agent/plugin/annotation/Parameter.java b/src/main/java/org/bench4q/agent/plugin/annotation/Parameter.java new file mode 100644 index 00000000..7dc3d69c --- /dev/null +++ b/src/main/java/org/bench4q/agent/plugin/annotation/Parameter.java @@ -0,0 +1,7 @@ +package org.bench4q.agent.plugin.annotation; + +public @interface Parameter { + String name(); + + String type(); +} diff --git a/src/main/java/org/bench4q/agent/plugin/annotation/Plugin.java b/src/main/java/org/bench4q/agent/plugin/annotation/Plugin.java new file mode 100644 index 00000000..a0cdb5e5 --- /dev/null +++ b/src/main/java/org/bench4q/agent/plugin/annotation/Plugin.java @@ -0,0 +1,11 @@ +package org.bench4q.agent.plugin.annotation; + +public @interface Plugin { + String id(); + + String name(); + + Parameter[] parameters(); + + String help(); +} From c999aba8afba82663c801c231940ec831216f55e Mon Sep 17 00:00:00 2001 From: Zhen Tang Date: Wed, 26 Jun 2013 00:23:58 +0800 Subject: [PATCH 004/196] Plugin support updated. --- .../java/org/bench4q/agent/plugin/AbstractFunction.java | 6 ++++-- src/main/java/org/bench4q/agent/plugin/AbstractPlugin.java | 4 +++- .../org/bench4q/agent/plugin/ControlFunctionResult.java | 5 +++++ src/main/java/org/bench4q/agent/plugin/FunctionResult.java | 5 +++++ .../java/org/bench4q/agent/plugin/SampleFunctionResult.java | 5 +++++ .../java/org/bench4q/agent/plugin/TestFunctionResult.java | 5 +++++ .../java/org/bench4q/agent/plugin/TimerFunctionResult.java | 5 +++++ .../java/org/bench4q/agent/plugin/annotation/Function.java | 2 -- .../org/bench4q/agent/plugin/annotation/FunctionType.java | 5 ----- 9 files changed, 32 insertions(+), 10 deletions(-) create mode 100644 src/main/java/org/bench4q/agent/plugin/ControlFunctionResult.java create mode 100644 src/main/java/org/bench4q/agent/plugin/FunctionResult.java create mode 100644 src/main/java/org/bench4q/agent/plugin/SampleFunctionResult.java create mode 100644 src/main/java/org/bench4q/agent/plugin/TestFunctionResult.java create mode 100644 src/main/java/org/bench4q/agent/plugin/TimerFunctionResult.java delete mode 100644 src/main/java/org/bench4q/agent/plugin/annotation/FunctionType.java diff --git a/src/main/java/org/bench4q/agent/plugin/AbstractFunction.java b/src/main/java/org/bench4q/agent/plugin/AbstractFunction.java index ee495bf7..18840e03 100644 --- a/src/main/java/org/bench4q/agent/plugin/AbstractFunction.java +++ b/src/main/java/org/bench4q/agent/plugin/AbstractFunction.java @@ -1,5 +1,7 @@ package org.bench4q.agent.plugin; -public abstract class AbstractFunction { +import java.util.Map; -} +public abstract class AbstractFunction { + public abstract FunctionResult execute(Map parameters); +} \ No newline at end of file diff --git a/src/main/java/org/bench4q/agent/plugin/AbstractPlugin.java b/src/main/java/org/bench4q/agent/plugin/AbstractPlugin.java index 7eb211a7..4d41dcb2 100644 --- a/src/main/java/org/bench4q/agent/plugin/AbstractPlugin.java +++ b/src/main/java/org/bench4q/agent/plugin/AbstractPlugin.java @@ -1,5 +1,7 @@ package org.bench4q.agent.plugin; -public abstract class AbstractPlugin { +import java.util.Map; +public abstract class AbstractPlugin { + public abstract void init(Map parameters); } diff --git a/src/main/java/org/bench4q/agent/plugin/ControlFunctionResult.java b/src/main/java/org/bench4q/agent/plugin/ControlFunctionResult.java new file mode 100644 index 00000000..5e01e720 --- /dev/null +++ b/src/main/java/org/bench4q/agent/plugin/ControlFunctionResult.java @@ -0,0 +1,5 @@ +package org.bench4q.agent.plugin; + +public class ControlFunctionResult extends FunctionResult { + +} diff --git a/src/main/java/org/bench4q/agent/plugin/FunctionResult.java b/src/main/java/org/bench4q/agent/plugin/FunctionResult.java new file mode 100644 index 00000000..89a4de86 --- /dev/null +++ b/src/main/java/org/bench4q/agent/plugin/FunctionResult.java @@ -0,0 +1,5 @@ +package org.bench4q.agent.plugin; + +public abstract class FunctionResult { + +} diff --git a/src/main/java/org/bench4q/agent/plugin/SampleFunctionResult.java b/src/main/java/org/bench4q/agent/plugin/SampleFunctionResult.java new file mode 100644 index 00000000..150c9e22 --- /dev/null +++ b/src/main/java/org/bench4q/agent/plugin/SampleFunctionResult.java @@ -0,0 +1,5 @@ +package org.bench4q.agent.plugin; + +public class SampleFunctionResult extends FunctionResult { + +} diff --git a/src/main/java/org/bench4q/agent/plugin/TestFunctionResult.java b/src/main/java/org/bench4q/agent/plugin/TestFunctionResult.java new file mode 100644 index 00000000..3ee4c674 --- /dev/null +++ b/src/main/java/org/bench4q/agent/plugin/TestFunctionResult.java @@ -0,0 +1,5 @@ +package org.bench4q.agent.plugin; + +public class TestFunctionResult extends FunctionResult { + +} diff --git a/src/main/java/org/bench4q/agent/plugin/TimerFunctionResult.java b/src/main/java/org/bench4q/agent/plugin/TimerFunctionResult.java new file mode 100644 index 00000000..33490d63 --- /dev/null +++ b/src/main/java/org/bench4q/agent/plugin/TimerFunctionResult.java @@ -0,0 +1,5 @@ +package org.bench4q.agent.plugin; + +public class TimerFunctionResult extends FunctionResult { + +} diff --git a/src/main/java/org/bench4q/agent/plugin/annotation/Function.java b/src/main/java/org/bench4q/agent/plugin/annotation/Function.java index e5c38e17..09b32893 100644 --- a/src/main/java/org/bench4q/agent/plugin/annotation/Function.java +++ b/src/main/java/org/bench4q/agent/plugin/annotation/Function.java @@ -8,8 +8,6 @@ public @interface Function { int number(); - FunctionType functionType(); - Parameter[] parameters(); String help(); diff --git a/src/main/java/org/bench4q/agent/plugin/annotation/FunctionType.java b/src/main/java/org/bench4q/agent/plugin/annotation/FunctionType.java deleted file mode 100644 index 0aaa9413..00000000 --- a/src/main/java/org/bench4q/agent/plugin/annotation/FunctionType.java +++ /dev/null @@ -1,5 +0,0 @@ -package org.bench4q.agent.plugin.annotation; - -public enum FunctionType { - Sample, Test, Timer, Control -} From 57a22f98b601497584f56d91298f60631a897e11 Mon Sep 17 00:00:00 2001 From: Zhen Tang Date: Wed, 26 Jun 2013 00:39:13 +0800 Subject: [PATCH 005/196] CommandLine injector added. --- .../agent/plugin/annotation/Function.java | 2 - .../agent/plugin/annotation/Plugin.java | 2 +- .../plugin/commandline/CommandLinePlugin.java | 16 +++ .../plugin/commandline/ExecuteFunction.java | 103 ++++++++++++++++++ 4 files changed, 120 insertions(+), 3 deletions(-) create mode 100644 src/main/java/org/bench4q/agent/plugin/commandline/CommandLinePlugin.java create mode 100644 src/main/java/org/bench4q/agent/plugin/commandline/ExecuteFunction.java diff --git a/src/main/java/org/bench4q/agent/plugin/annotation/Function.java b/src/main/java/org/bench4q/agent/plugin/annotation/Function.java index 09b32893..eb032bce 100644 --- a/src/main/java/org/bench4q/agent/plugin/annotation/Function.java +++ b/src/main/java/org/bench4q/agent/plugin/annotation/Function.java @@ -6,8 +6,6 @@ public @interface Function { Class plugin(); - int number(); - Parameter[] parameters(); String help(); diff --git a/src/main/java/org/bench4q/agent/plugin/annotation/Plugin.java b/src/main/java/org/bench4q/agent/plugin/annotation/Plugin.java index a0cdb5e5..536c2230 100644 --- a/src/main/java/org/bench4q/agent/plugin/annotation/Plugin.java +++ b/src/main/java/org/bench4q/agent/plugin/annotation/Plugin.java @@ -1,7 +1,7 @@ package org.bench4q.agent.plugin.annotation; public @interface Plugin { - String id(); + String uuid(); String name(); diff --git a/src/main/java/org/bench4q/agent/plugin/commandline/CommandLinePlugin.java b/src/main/java/org/bench4q/agent/plugin/commandline/CommandLinePlugin.java new file mode 100644 index 00000000..faeebe47 --- /dev/null +++ b/src/main/java/org/bench4q/agent/plugin/commandline/CommandLinePlugin.java @@ -0,0 +1,16 @@ +package org.bench4q.agent.plugin.commandline; + +import java.util.Map; + +import org.bench4q.agent.plugin.AbstractPlugin; +import org.bench4q.agent.plugin.annotation.Plugin; + +@Plugin(help = "This plug-in supports execution of command lines", uuid = "13b46059-559d-c483-93c1-bd008d92fab8", name = "Command Line Injector", parameters = {}) +public class CommandLinePlugin extends AbstractPlugin { + + @Override + public void init(Map parameters) { + + } + +} diff --git a/src/main/java/org/bench4q/agent/plugin/commandline/ExecuteFunction.java b/src/main/java/org/bench4q/agent/plugin/commandline/ExecuteFunction.java new file mode 100644 index 00000000..7d586bd8 --- /dev/null +++ b/src/main/java/org/bench4q/agent/plugin/commandline/ExecuteFunction.java @@ -0,0 +1,103 @@ +package org.bench4q.agent.plugin.commandline; + +import java.io.BufferedReader; +import java.io.InputStreamReader; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import org.bench4q.agent.plugin.AbstractSampleFunction; +import org.bench4q.agent.plugin.FunctionResult; +import org.bench4q.agent.plugin.annotation.Function; +import org.bench4q.agent.plugin.annotation.Parameter; + +@Function(help = "Executes the provided command line.", name = "Execute", parameters = { + @Parameter(name = "command", type = "String"), + @Parameter(name = "comment", type = "String"), + @Parameter(name = "iteration", type = "String") }, plugin = CommandLinePlugin.class) +public class ExecuteFunction extends AbstractSampleFunction { + private String stderr; + private String stdout; + + @Override + public FunctionResult execute(Map parameters) { + try { + List commandLine = new ArrayList(); + final String commandLineStr = parameters.get("command"); + Runtime runtime = Runtime.getRuntime(); + if (System.getProperty("os.name").equalsIgnoreCase("linux")) { + commandLine.add("/bin/sh"); + commandLine.add("-c"); + commandLine.add(commandLineStr); + } else if (System.getProperty("os.name").toLowerCase() + .startsWith("windows")) { + commandLine.add("cmd.exe"); + commandLine.add("/c"); + commandLine.add("\"" + commandLineStr + "\""); + } else { + } + // report.setDate(System.currentTimeMillis()); + final Process process = runtime.exec(commandLine + .toArray(new String[commandLine.size()])); + + // standard output reading + new Thread() { + public void run() { + try { + BufferedReader reader = new BufferedReader( + new InputStreamReader(process.getInputStream())); + String streamline = ""; + try { + stdout = ""; + while ((streamline = reader.readLine()) != null) + stdout += streamline + + System.getProperty("line.separator"); + } finally { + reader.close(); + } + } catch (Exception e) { + e.printStackTrace(); + } + } + }.start(); + // standard error output reading + new Thread() { + public void run() { + try { + BufferedReader reader = new BufferedReader( + new InputStreamReader(process.getErrorStream())); + String streamline = ""; + try { + stderr = ""; + while ((streamline = reader.readLine()) != null) + stderr += streamline + + System.getProperty("line.separator"); + } finally { + reader.close(); + } + } catch (Exception e) { + e.printStackTrace(); + } + } + }.start(); + // wait until the end of command execution + process.waitFor(); + // get return code of command execution + int result = process.exitValue(); + // retcode = String.valueOf(result); + // fill sample report + // report.duration = (int) (System.currentTimeMillis() - + // report.getDate()); + // report.type = "COMMAND LINE"; + // report.comment = (String)params.get(SAMPLE_EXECUTE_COMMENT); + // report.iteration = + // Long.parseLong((String)params.get(SAMPLE_EXECUTE_ITERATION)); + // report.result = retcode; + // report.successful = (result == 0); + return null; + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } +} From 7a111adffe7e8169a4cffeccce0fa6a080ac7404 Mon Sep 17 00:00:00 2001 From: Zhen Tang Date: Wed, 26 Jun 2013 14:22:23 +0800 Subject: [PATCH 006/196] Plugin support updated. --- pom.xml | 91 ++++++------ .../java/org/bench4q/agent/AgentServer.java | 134 +++++++++--------- .../org/bench4q/agent/api/HomeController.java | 53 +++++-- .../agent/plugin/AbstractControlFunction.java | 5 - .../agent/plugin/AbstractFunction.java | 7 - .../bench4q/agent/plugin/AbstractPlugin.java | 7 - .../agent/plugin/AbstractSampleFunction.java | 5 - .../agent/plugin/AbstractTestFunction.java | 5 - .../agent/plugin/AbstractTimerFunction.java | 5 - .../org/bench4q/agent/plugin/Behavior.java | 12 ++ .../org/bench4q/agent/plugin/ClassHelper.java | 124 ++++++++++++++++ .../agent/plugin/ControlFunctionResult.java | 5 - .../bench4q/agent/plugin/FunctionResult.java | 5 - .../java/org/bench4q/agent/plugin/Plugin.java | 12 ++ .../bench4q/agent/plugin/PluginManager.java | 95 +++++++++++++ .../agent/plugin/SampleFunctionResult.java | 5 - .../agent/plugin/TestFunctionResult.java | 5 - .../agent/plugin/TimerFunctionResult.java | 5 - .../bench4q/agent/plugin/TypeConverter.java | 44 ++++++ .../agent/plugin/annotation/Function.java | 12 -- .../agent/plugin/annotation/Parameter.java | 7 - .../agent/plugin/annotation/Plugin.java | 11 -- .../plugin/commandline/CommandLinePlugin.java | 16 --- .../plugin/commandline/ExecuteFunction.java | 103 -------------- .../bench4q/agent/plugin/http/HttpPlugin.java | 18 +++ 25 files changed, 458 insertions(+), 333 deletions(-) delete mode 100644 src/main/java/org/bench4q/agent/plugin/AbstractControlFunction.java delete mode 100644 src/main/java/org/bench4q/agent/plugin/AbstractFunction.java delete mode 100644 src/main/java/org/bench4q/agent/plugin/AbstractPlugin.java delete mode 100644 src/main/java/org/bench4q/agent/plugin/AbstractSampleFunction.java delete mode 100644 src/main/java/org/bench4q/agent/plugin/AbstractTestFunction.java delete mode 100644 src/main/java/org/bench4q/agent/plugin/AbstractTimerFunction.java create mode 100644 src/main/java/org/bench4q/agent/plugin/Behavior.java create mode 100644 src/main/java/org/bench4q/agent/plugin/ClassHelper.java delete mode 100644 src/main/java/org/bench4q/agent/plugin/ControlFunctionResult.java delete mode 100644 src/main/java/org/bench4q/agent/plugin/FunctionResult.java create mode 100644 src/main/java/org/bench4q/agent/plugin/Plugin.java create mode 100644 src/main/java/org/bench4q/agent/plugin/PluginManager.java delete mode 100644 src/main/java/org/bench4q/agent/plugin/SampleFunctionResult.java delete mode 100644 src/main/java/org/bench4q/agent/plugin/TestFunctionResult.java delete mode 100644 src/main/java/org/bench4q/agent/plugin/TimerFunctionResult.java create mode 100644 src/main/java/org/bench4q/agent/plugin/TypeConverter.java delete mode 100644 src/main/java/org/bench4q/agent/plugin/annotation/Function.java delete mode 100644 src/main/java/org/bench4q/agent/plugin/annotation/Parameter.java delete mode 100644 src/main/java/org/bench4q/agent/plugin/annotation/Plugin.java delete mode 100644 src/main/java/org/bench4q/agent/plugin/commandline/CommandLinePlugin.java delete mode 100644 src/main/java/org/bench4q/agent/plugin/commandline/ExecuteFunction.java create mode 100644 src/main/java/org/bench4q/agent/plugin/http/HttpPlugin.java diff --git a/pom.xml b/pom.xml index 8d41cc37..3b566634 100644 --- a/pom.xml +++ b/pom.xml @@ -1,44 +1,49 @@ - - 4.0.0 - org.bench4q - bench4q-agent - jar - 0.0.1-SNAPSHOT - Bench4Q Agent - Bench4Q Agent - - TCSE, ISCAS - - - - junit - junit - 4.11 - test - - - org.eclipse.jetty - jetty-server - 8.1.11.v20130520 - - - org.eclipse.jetty - jetty-servlet - 8.1.11.v20130520 - - - org.springframework - spring-webmvc - 3.2.3.RELEASE - - - org.codehaus.jackson - jackson-mapper-asl - 1.9.12 - - - - bench4q-agent - + + 4.0.0 + org.bench4q + bench4q-agent + jar + 0.0.1-SNAPSHOT + Bench4Q Agent + Bench4Q Agent + + TCSE, ISCAS + + + + junit + junit + 4.11 + test + + + org.eclipse.jetty + jetty-server + 8.1.11.v20130520 + + + org.eclipse.jetty + jetty-servlet + 8.1.11.v20130520 + + + org.springframework + spring-webmvc + 3.2.3.RELEASE + + + org.codehaus.jackson + jackson-mapper-asl + 1.9.12 + + + org.javassist + javassist + 3.18.0-GA + + + + bench4q-agent + \ No newline at end of file diff --git a/src/main/java/org/bench4q/agent/AgentServer.java b/src/main/java/org/bench4q/agent/AgentServer.java index f3a4023b..f1940cd1 100644 --- a/src/main/java/org/bench4q/agent/AgentServer.java +++ b/src/main/java/org/bench4q/agent/AgentServer.java @@ -1,67 +1,67 @@ -package org.bench4q.agent; - -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.web.servlet.DispatcherServlet; - -public class AgentServer { - private Server server; - private int port; - - private Server getServer() { - return server; - } - - private void setServer(Server server) { - this.server = server; - } - - private int getPort() { - return port; - } - - private void setPort(int port) { - this.port = port; - } - - public AgentServer(int port) { - this.setPort(port); - } - - 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*:/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); - } - } -} +package org.bench4q.agent; + +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.web.servlet.DispatcherServlet; + +public class AgentServer { + private Server server; + private int port; + + private Server getServer() { + return server; + } + + private void setServer(Server server) { + this.server = server; + } + + private int getPort() { + return port; + } + + private void setPort(int port) { + this.port = port; + } + + public AgentServer(int port) { + this.setPort(port); + } + + 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*:/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); + } + } +} diff --git a/src/main/java/org/bench4q/agent/api/HomeController.java b/src/main/java/org/bench4q/agent/api/HomeController.java index 6203417b..c044a3d5 100644 --- a/src/main/java/org/bench4q/agent/api/HomeController.java +++ b/src/main/java/org/bench4q/agent/api/HomeController.java @@ -1,16 +1,39 @@ -package org.bench4q.agent.api; - -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 { - @RequestMapping(value = { "/" }, method = RequestMethod.GET) - @ResponseBody - public String index() { - return "It works!"; - } +package org.bench4q.agent.api; + +import java.util.HashMap; +import java.util.Map; + +import org.bench4q.agent.plugin.PluginManager; +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.ResponseBody; + +@Controller +@RequestMapping("/") +public class HomeController { + private PluginManager pluginManager; + + private PluginManager getPluginManager() { + return pluginManager; + } + + @Autowired + private void setPluginManager(PluginManager pluginManager) { + this.pluginManager = pluginManager; + } + + @RequestMapping(value = { "/" }, method = RequestMethod.GET) + @ResponseBody + public String index() { + Class plugin = this.getPluginManager().getPlugin("Http"); + Map parameters = new HashMap(); + parameters.put("abc", "123"); + parameters.put("def", "Test DEF"); + parameters.put("ghi", "23.4"); + Object object = this.getPluginManager().initializePlugin(plugin, + parameters); + return object.toString(); + } } \ No newline at end of file diff --git a/src/main/java/org/bench4q/agent/plugin/AbstractControlFunction.java b/src/main/java/org/bench4q/agent/plugin/AbstractControlFunction.java deleted file mode 100644 index c6f2905a..00000000 --- a/src/main/java/org/bench4q/agent/plugin/AbstractControlFunction.java +++ /dev/null @@ -1,5 +0,0 @@ -package org.bench4q.agent.plugin; - -public abstract class AbstractControlFunction extends AbstractFunction { - -} diff --git a/src/main/java/org/bench4q/agent/plugin/AbstractFunction.java b/src/main/java/org/bench4q/agent/plugin/AbstractFunction.java deleted file mode 100644 index 18840e03..00000000 --- a/src/main/java/org/bench4q/agent/plugin/AbstractFunction.java +++ /dev/null @@ -1,7 +0,0 @@ -package org.bench4q.agent.plugin; - -import java.util.Map; - -public abstract class AbstractFunction { - public abstract FunctionResult execute(Map parameters); -} \ No newline at end of file diff --git a/src/main/java/org/bench4q/agent/plugin/AbstractPlugin.java b/src/main/java/org/bench4q/agent/plugin/AbstractPlugin.java deleted file mode 100644 index 4d41dcb2..00000000 --- a/src/main/java/org/bench4q/agent/plugin/AbstractPlugin.java +++ /dev/null @@ -1,7 +0,0 @@ -package org.bench4q.agent.plugin; - -import java.util.Map; - -public abstract class AbstractPlugin { - public abstract void init(Map parameters); -} diff --git a/src/main/java/org/bench4q/agent/plugin/AbstractSampleFunction.java b/src/main/java/org/bench4q/agent/plugin/AbstractSampleFunction.java deleted file mode 100644 index 11f31483..00000000 --- a/src/main/java/org/bench4q/agent/plugin/AbstractSampleFunction.java +++ /dev/null @@ -1,5 +0,0 @@ -package org.bench4q.agent.plugin; - -public abstract class AbstractSampleFunction extends AbstractFunction { - -} diff --git a/src/main/java/org/bench4q/agent/plugin/AbstractTestFunction.java b/src/main/java/org/bench4q/agent/plugin/AbstractTestFunction.java deleted file mode 100644 index 391f8167..00000000 --- a/src/main/java/org/bench4q/agent/plugin/AbstractTestFunction.java +++ /dev/null @@ -1,5 +0,0 @@ -package org.bench4q.agent.plugin; - -public abstract class AbstractTestFunction extends AbstractFunction { - -} diff --git a/src/main/java/org/bench4q/agent/plugin/AbstractTimerFunction.java b/src/main/java/org/bench4q/agent/plugin/AbstractTimerFunction.java deleted file mode 100644 index 0a7b4a88..00000000 --- a/src/main/java/org/bench4q/agent/plugin/AbstractTimerFunction.java +++ /dev/null @@ -1,5 +0,0 @@ -package org.bench4q.agent.plugin; - -public abstract class AbstractTimerFunction extends AbstractFunction { - -} diff --git a/src/main/java/org/bench4q/agent/plugin/Behavior.java b/src/main/java/org/bench4q/agent/plugin/Behavior.java new file mode 100644 index 00000000..3fab5f99 --- /dev/null +++ b/src/main/java/org/bench4q/agent/plugin/Behavior.java @@ -0,0 +1,12 @@ +package org.bench4q.agent.plugin; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Target(ElementType.METHOD) +@Retention(RetentionPolicy.RUNTIME) +public @interface Behavior { + String value(); +} \ No newline at end of file diff --git a/src/main/java/org/bench4q/agent/plugin/ClassHelper.java b/src/main/java/org/bench4q/agent/plugin/ClassHelper.java new file mode 100644 index 00000000..cf5edc7f --- /dev/null +++ b/src/main/java/org/bench4q/agent/plugin/ClassHelper.java @@ -0,0 +1,124 @@ +package org.bench4q.agent.plugin; + +import java.io.File; +import java.io.IOException; +import java.net.URL; +import java.net.URLClassLoader; +import java.util.ArrayList; +import java.util.Enumeration; +import java.util.List; +import java.util.jar.JarEntry; +import java.util.jar.JarFile; + +import org.springframework.stereotype.Component; + +@Component +public class ClassHelper { + + public List getClassNames(String packageName, + boolean searchInChildPackage) { + try { + List classNames = new ArrayList(); + URLClassLoader classLoader = (URLClassLoader) Thread + .currentThread().getContextClassLoader(); + URL[] urls = classLoader.getURLs(); + for (URL url : urls) { + if (url.getProtocol().equals("file")) { + File file = new File(url.getFile()); + String root = file.getPath().replace("\\", "/"); + if (file.isDirectory()) { + classNames.addAll(this.getClassNamesFromDirectory(root, + packageName, searchInChildPackage, file, true)); + } else if (file.getName().endsWith(".jar")) { + classNames.addAll(this.getClassNameFromJar(packageName, + searchInChildPackage, file)); + } + } + } + return classNames; + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } + + private List getClassNamesFromDirectory(String root, + String packageName, boolean searchInChildPackage, File directory, + boolean continueSearch) { + List classNames = new ArrayList(); + File[] files = directory.listFiles(); + for (File file : files) { + String filePath = file.getPath().replace("\\", "/"); + if (file.isDirectory()) { + if (searchInChildPackage || continueSearch) { + boolean needToContinue = continueSearch; + if (filePath.endsWith(packageName.replace(".", "/"))) { + needToContinue = needToContinue & false; + } + classNames.addAll(this.getClassNamesFromDirectory(root, + packageName, searchInChildPackage, file, + needToContinue)); + } + } else { + if (filePath.endsWith(".class")) { + String classFileName = filePath.replace(root + "/", ""); + if (classFileName.startsWith(packageName.replace(".", "/"))) { + String className = classFileName.substring(0, + classFileName.length() - ".class".length()) + .replace("/", "."); + classNames.add(className); + } + } + } + } + return classNames; + } + + private List getClassNameFromJar(String packageName, + boolean searchInChildPackage, File file) { + List classNames = new ArrayList(); + JarFile jarFile = null; + try { + jarFile = new JarFile(file); + Enumeration jarEntries = jarFile.entries(); + while (jarEntries.hasMoreElements()) { + JarEntry jarEntry = jarEntries.nextElement(); + String entryName = jarEntry.getName(); + if (entryName.endsWith(".class")) { + String packagePath = packageName.replace(".", "/"); + if (searchInChildPackage) { + if (entryName.startsWith(packagePath)) { + entryName = entryName.replace("/", ".").substring( + 0, entryName.lastIndexOf(".")); + classNames.add(entryName); + } + } else { + int index = entryName.lastIndexOf("/"); + String entryPath; + if (index != -1) { + entryPath = entryName.substring(0, index); + } else { + entryPath = entryName; + } + if (entryPath.equals(packagePath)) { + entryName = entryName.replace("/", ".").substring( + 0, entryName.lastIndexOf(".")); + classNames.add(entryName); + } + } + } + } + } catch (IOException e) { + e.printStackTrace(); + } finally { + if (jarFile != null) { + try { + jarFile.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + return classNames; + } +} diff --git a/src/main/java/org/bench4q/agent/plugin/ControlFunctionResult.java b/src/main/java/org/bench4q/agent/plugin/ControlFunctionResult.java deleted file mode 100644 index 5e01e720..00000000 --- a/src/main/java/org/bench4q/agent/plugin/ControlFunctionResult.java +++ /dev/null @@ -1,5 +0,0 @@ -package org.bench4q.agent.plugin; - -public class ControlFunctionResult extends FunctionResult { - -} diff --git a/src/main/java/org/bench4q/agent/plugin/FunctionResult.java b/src/main/java/org/bench4q/agent/plugin/FunctionResult.java deleted file mode 100644 index 89a4de86..00000000 --- a/src/main/java/org/bench4q/agent/plugin/FunctionResult.java +++ /dev/null @@ -1,5 +0,0 @@ -package org.bench4q.agent.plugin; - -public abstract class FunctionResult { - -} diff --git a/src/main/java/org/bench4q/agent/plugin/Plugin.java b/src/main/java/org/bench4q/agent/plugin/Plugin.java new file mode 100644 index 00000000..7841b547 --- /dev/null +++ b/src/main/java/org/bench4q/agent/plugin/Plugin.java @@ -0,0 +1,12 @@ +package org.bench4q.agent.plugin; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Target(ElementType.TYPE) +@Retention(RetentionPolicy.RUNTIME) +public @interface Plugin { + String value(); +} diff --git a/src/main/java/org/bench4q/agent/plugin/PluginManager.java b/src/main/java/org/bench4q/agent/plugin/PluginManager.java new file mode 100644 index 00000000..d1ae86a0 --- /dev/null +++ b/src/main/java/org/bench4q/agent/plugin/PluginManager.java @@ -0,0 +1,95 @@ +package org.bench4q.agent.plugin; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javassist.ClassPool; +import javassist.CtClass; +import javassist.CtConstructor; +import javassist.Modifier; +import javassist.bytecode.CodeAttribute; +import javassist.bytecode.LocalVariableAttribute; +import javassist.bytecode.MethodInfo; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +@Component +public class PluginManager { + private ClassHelper classHelper; + private TypeConverter typeConverter; + + private ClassHelper getClassHelper() { + return classHelper; + } + + @Autowired + private void setClassHelper(ClassHelper classHelper) { + this.classHelper = classHelper; + } + + private TypeConverter getTypeConverter() { + return typeConverter; + } + + @Autowired + private void setTypeConverter(TypeConverter typeConverter) { + this.typeConverter = typeConverter; + } + + private Map> findPlugins(String packageName) { + try { + List classNames = this.getClassHelper().getClassNames( + packageName, true); + Map> ret = new HashMap>(); + for (String className : classNames) { + Class plugin = Class.forName(className); + if (plugin.isAnnotationPresent(Plugin.class)) { + ret.put(plugin.getAnnotation(Plugin.class).value(), plugin); + } + } + return ret; + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } + + public Class getPlugin(String name) { + return this.findPlugins("org.bench4q.agent.plugin").get(name); + } + + public Object initializePlugin(Class plugin, + Map parameters) { + try { + ClassPool classPool = ClassPool.getDefault(); + CtClass ctClass = classPool.get(plugin.getCanonicalName()); + CtConstructor[] ctConstructors = ctClass.getConstructors(); + if (ctConstructors.length != 1) { + return null; + } + CtConstructor constructor = ctConstructors[0]; + MethodInfo methodInfo = constructor.getMethodInfo(); + CodeAttribute codeAttribute = methodInfo.getCodeAttribute(); + LocalVariableAttribute localVariableAttribute = (LocalVariableAttribute) codeAttribute + .getAttribute(LocalVariableAttribute.tag); + int parameterCount = constructor.getParameterTypes().length; + String parameterNames[] = new String[parameterCount]; + Object values[] = new Object[parameterCount]; + int i; + int pos = Modifier.isStatic(constructor.getModifiers()) ? 0 : 1; + for (i = 0; i < parameterCount; i++) { + parameterNames[i] = localVariableAttribute + .variableName(i + pos); + values[i] = this.getTypeConverter().convert( + parameters.get(parameterNames[i]), + constructor.getParameterTypes()[i].getName()); + } + return plugin.getConstructors()[0].newInstance(values); + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } +} diff --git a/src/main/java/org/bench4q/agent/plugin/SampleFunctionResult.java b/src/main/java/org/bench4q/agent/plugin/SampleFunctionResult.java deleted file mode 100644 index 150c9e22..00000000 --- a/src/main/java/org/bench4q/agent/plugin/SampleFunctionResult.java +++ /dev/null @@ -1,5 +0,0 @@ -package org.bench4q.agent.plugin; - -public class SampleFunctionResult extends FunctionResult { - -} diff --git a/src/main/java/org/bench4q/agent/plugin/TestFunctionResult.java b/src/main/java/org/bench4q/agent/plugin/TestFunctionResult.java deleted file mode 100644 index 3ee4c674..00000000 --- a/src/main/java/org/bench4q/agent/plugin/TestFunctionResult.java +++ /dev/null @@ -1,5 +0,0 @@ -package org.bench4q.agent.plugin; - -public class TestFunctionResult extends FunctionResult { - -} diff --git a/src/main/java/org/bench4q/agent/plugin/TimerFunctionResult.java b/src/main/java/org/bench4q/agent/plugin/TimerFunctionResult.java deleted file mode 100644 index 33490d63..00000000 --- a/src/main/java/org/bench4q/agent/plugin/TimerFunctionResult.java +++ /dev/null @@ -1,5 +0,0 @@ -package org.bench4q.agent.plugin; - -public class TimerFunctionResult extends FunctionResult { - -} diff --git a/src/main/java/org/bench4q/agent/plugin/TypeConverter.java b/src/main/java/org/bench4q/agent/plugin/TypeConverter.java new file mode 100644 index 00000000..de1216e3 --- /dev/null +++ b/src/main/java/org/bench4q/agent/plugin/TypeConverter.java @@ -0,0 +1,44 @@ +package org.bench4q.agent.plugin; + +import org.springframework.stereotype.Component; + +@Component +public class TypeConverter { + public Object convert(Object source, String targetClassName) { + if (targetClassName.equals("boolean")) { + return Boolean.parseBoolean(source.toString()); + } + if (targetClassName.equals("char")) { + return source.toString().toCharArray()[0]; + } + if (targetClassName.equals("byte")) { + return Byte.parseByte(source.toString()); + } + if (targetClassName.equals("short")) { + return Short.parseShort(source.toString()); + } + if (targetClassName.equals("int")) { + return Integer.parseInt(source.toString()); + } + if (targetClassName.equals("long")) { + return Long.parseLong(source.toString()); + } + if (targetClassName.equals("float")) { + return Float.parseFloat(source.toString()); + } + if (targetClassName.equals("double")) { + return Double.parseDouble(source.toString()); + } + + try { + Class targetClass = Class.forName(targetClassName); + if (targetClass.isAssignableFrom(String.class)) { + return source.toString(); + } + return targetClass.cast(source); + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } +} diff --git a/src/main/java/org/bench4q/agent/plugin/annotation/Function.java b/src/main/java/org/bench4q/agent/plugin/annotation/Function.java deleted file mode 100644 index eb032bce..00000000 --- a/src/main/java/org/bench4q/agent/plugin/annotation/Function.java +++ /dev/null @@ -1,12 +0,0 @@ -package org.bench4q.agent.plugin.annotation; - -public @interface Function { - - String name(); - - Class plugin(); - - Parameter[] parameters(); - - String help(); -} \ No newline at end of file diff --git a/src/main/java/org/bench4q/agent/plugin/annotation/Parameter.java b/src/main/java/org/bench4q/agent/plugin/annotation/Parameter.java deleted file mode 100644 index 7dc3d69c..00000000 --- a/src/main/java/org/bench4q/agent/plugin/annotation/Parameter.java +++ /dev/null @@ -1,7 +0,0 @@ -package org.bench4q.agent.plugin.annotation; - -public @interface Parameter { - String name(); - - String type(); -} diff --git a/src/main/java/org/bench4q/agent/plugin/annotation/Plugin.java b/src/main/java/org/bench4q/agent/plugin/annotation/Plugin.java deleted file mode 100644 index 536c2230..00000000 --- a/src/main/java/org/bench4q/agent/plugin/annotation/Plugin.java +++ /dev/null @@ -1,11 +0,0 @@ -package org.bench4q.agent.plugin.annotation; - -public @interface Plugin { - String uuid(); - - String name(); - - Parameter[] parameters(); - - String help(); -} diff --git a/src/main/java/org/bench4q/agent/plugin/commandline/CommandLinePlugin.java b/src/main/java/org/bench4q/agent/plugin/commandline/CommandLinePlugin.java deleted file mode 100644 index faeebe47..00000000 --- a/src/main/java/org/bench4q/agent/plugin/commandline/CommandLinePlugin.java +++ /dev/null @@ -1,16 +0,0 @@ -package org.bench4q.agent.plugin.commandline; - -import java.util.Map; - -import org.bench4q.agent.plugin.AbstractPlugin; -import org.bench4q.agent.plugin.annotation.Plugin; - -@Plugin(help = "This plug-in supports execution of command lines", uuid = "13b46059-559d-c483-93c1-bd008d92fab8", name = "Command Line Injector", parameters = {}) -public class CommandLinePlugin extends AbstractPlugin { - - @Override - public void init(Map parameters) { - - } - -} diff --git a/src/main/java/org/bench4q/agent/plugin/commandline/ExecuteFunction.java b/src/main/java/org/bench4q/agent/plugin/commandline/ExecuteFunction.java deleted file mode 100644 index 7d586bd8..00000000 --- a/src/main/java/org/bench4q/agent/plugin/commandline/ExecuteFunction.java +++ /dev/null @@ -1,103 +0,0 @@ -package org.bench4q.agent.plugin.commandline; - -import java.io.BufferedReader; -import java.io.InputStreamReader; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -import org.bench4q.agent.plugin.AbstractSampleFunction; -import org.bench4q.agent.plugin.FunctionResult; -import org.bench4q.agent.plugin.annotation.Function; -import org.bench4q.agent.plugin.annotation.Parameter; - -@Function(help = "Executes the provided command line.", name = "Execute", parameters = { - @Parameter(name = "command", type = "String"), - @Parameter(name = "comment", type = "String"), - @Parameter(name = "iteration", type = "String") }, plugin = CommandLinePlugin.class) -public class ExecuteFunction extends AbstractSampleFunction { - private String stderr; - private String stdout; - - @Override - public FunctionResult execute(Map parameters) { - try { - List commandLine = new ArrayList(); - final String commandLineStr = parameters.get("command"); - Runtime runtime = Runtime.getRuntime(); - if (System.getProperty("os.name").equalsIgnoreCase("linux")) { - commandLine.add("/bin/sh"); - commandLine.add("-c"); - commandLine.add(commandLineStr); - } else if (System.getProperty("os.name").toLowerCase() - .startsWith("windows")) { - commandLine.add("cmd.exe"); - commandLine.add("/c"); - commandLine.add("\"" + commandLineStr + "\""); - } else { - } - // report.setDate(System.currentTimeMillis()); - final Process process = runtime.exec(commandLine - .toArray(new String[commandLine.size()])); - - // standard output reading - new Thread() { - public void run() { - try { - BufferedReader reader = new BufferedReader( - new InputStreamReader(process.getInputStream())); - String streamline = ""; - try { - stdout = ""; - while ((streamline = reader.readLine()) != null) - stdout += streamline - + System.getProperty("line.separator"); - } finally { - reader.close(); - } - } catch (Exception e) { - e.printStackTrace(); - } - } - }.start(); - // standard error output reading - new Thread() { - public void run() { - try { - BufferedReader reader = new BufferedReader( - new InputStreamReader(process.getErrorStream())); - String streamline = ""; - try { - stderr = ""; - while ((streamline = reader.readLine()) != null) - stderr += streamline - + System.getProperty("line.separator"); - } finally { - reader.close(); - } - } catch (Exception e) { - e.printStackTrace(); - } - } - }.start(); - // wait until the end of command execution - process.waitFor(); - // get return code of command execution - int result = process.exitValue(); - // retcode = String.valueOf(result); - // fill sample report - // report.duration = (int) (System.currentTimeMillis() - - // report.getDate()); - // report.type = "COMMAND LINE"; - // report.comment = (String)params.get(SAMPLE_EXECUTE_COMMENT); - // report.iteration = - // Long.parseLong((String)params.get(SAMPLE_EXECUTE_ITERATION)); - // report.result = retcode; - // report.successful = (result == 0); - return null; - } catch (Exception e) { - e.printStackTrace(); - return null; - } - } -} diff --git a/src/main/java/org/bench4q/agent/plugin/http/HttpPlugin.java b/src/main/java/org/bench4q/agent/plugin/http/HttpPlugin.java new file mode 100644 index 00000000..469b1140 --- /dev/null +++ b/src/main/java/org/bench4q/agent/plugin/http/HttpPlugin.java @@ -0,0 +1,18 @@ +package org.bench4q.agent.plugin.http; + +import org.bench4q.agent.plugin.Behavior; +import org.bench4q.agent.plugin.Plugin; + +@Plugin("Http") +public class HttpPlugin { + public HttpPlugin(int abc, String def, double ghi) { + System.out.println(abc); + System.out.println(def); + System.out.println(ghi); + } + + @Behavior("Get") + public void doGet(String url) { + System.out.println("Get " + url); + } +} From 3d958fe8c56660ffa53395ffabf7e898a7de2efa Mon Sep 17 00:00:00 2001 From: Zhen Tang Date: Wed, 26 Jun 2013 15:11:24 +0800 Subject: [PATCH 007/196] Scenario added. --- .../org/bench4q/agent/scenario/Parameter.java | 29 +++++++++++++ .../org/bench4q/agent/scenario/Scenario.java | 32 +++++++++++++++ .../org/bench4q/agent/scenario/UsePlugin.java | 41 +++++++++++++++++++ .../bench4q/agent/scenario/UserBehavior.java | 40 ++++++++++++++++++ 4 files changed, 142 insertions(+) create mode 100644 src/main/java/org/bench4q/agent/scenario/Parameter.java create mode 100644 src/main/java/org/bench4q/agent/scenario/Scenario.java create mode 100644 src/main/java/org/bench4q/agent/scenario/UsePlugin.java create mode 100644 src/main/java/org/bench4q/agent/scenario/UserBehavior.java diff --git a/src/main/java/org/bench4q/agent/scenario/Parameter.java b/src/main/java/org/bench4q/agent/scenario/Parameter.java new file mode 100644 index 00000000..0947b4d9 --- /dev/null +++ b/src/main/java/org/bench4q/agent/scenario/Parameter.java @@ -0,0 +1,29 @@ +package org.bench4q.agent.scenario; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; + +@XmlRootElement(name = "parameter") +public class Parameter { + 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; + } + +} diff --git a/src/main/java/org/bench4q/agent/scenario/Scenario.java b/src/main/java/org/bench4q/agent/scenario/Scenario.java new file mode 100644 index 00000000..4853c8d5 --- /dev/null +++ b/src/main/java/org/bench4q/agent/scenario/Scenario.java @@ -0,0 +1,32 @@ +package org.bench4q.agent.scenario; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlElementWrapper; +import javax.xml.bind.annotation.XmlRootElement; + +@XmlRootElement(name = "scenario") +public class Scenario { + private UsePlugin[] usePlugins; + private UserBehavior[] userBehaviors; + + @XmlElementWrapper(name = "plugins") + @XmlElement(name = "plugin") + public UsePlugin[] getUsePlugins() { + return usePlugins; + } + + public void setUsePlugins(UsePlugin[] usePlugins) { + this.usePlugins = usePlugins; + } + + @XmlElementWrapper(name = "userBehaviors") + @XmlElement(name = "userBehavior") + public UserBehavior[] getUserBehaviors() { + return userBehaviors; + } + + public void setUserBehaviors(UserBehavior[] userBehaviors) { + this.userBehaviors = userBehaviors; + } + +} diff --git a/src/main/java/org/bench4q/agent/scenario/UsePlugin.java b/src/main/java/org/bench4q/agent/scenario/UsePlugin.java new file mode 100644 index 00000000..44a85143 --- /dev/null +++ b/src/main/java/org/bench4q/agent/scenario/UsePlugin.java @@ -0,0 +1,41 @@ +package org.bench4q.agent.scenario; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlElementWrapper; +import javax.xml.bind.annotation.XmlRootElement; + +@XmlRootElement(name = "usePlugin") +public class UsePlugin { + private String id; + private String name; + private Parameter[] 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 Parameter[] getParameters() { + return parameters; + } + + public void setParameters(Parameter[] parameters) { + this.parameters = parameters; + } + +} diff --git a/src/main/java/org/bench4q/agent/scenario/UserBehavior.java b/src/main/java/org/bench4q/agent/scenario/UserBehavior.java new file mode 100644 index 00000000..976800fd --- /dev/null +++ b/src/main/java/org/bench4q/agent/scenario/UserBehavior.java @@ -0,0 +1,40 @@ +package org.bench4q.agent.scenario; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlElementWrapper; +import javax.xml.bind.annotation.XmlRootElement; + +@XmlRootElement(name = "userBehavior") +public class UserBehavior { + private String use; + private String name; + private Parameter[] 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 Parameter[] getParameters() { + return parameters; + } + + public void setParameters(Parameter[] parameters) { + this.parameters = parameters; + } +} From ad99f1aaa3ec9d233084a816975f12d380493c4f Mon Sep 17 00:00:00 2001 From: Zhen Tang Date: Wed, 26 Jun 2013 16:14:17 +0800 Subject: [PATCH 008/196] Scenario Engine added. --- .../bench4q/agent/api/AgentController.java | 5 ++ .../org/bench4q/agent/api/HomeController.java | 81 +++++++++++++++---- .../bench4q/agent/plugin/PluginManager.java | 81 +++++++++++++++---- .../bench4q/agent/plugin/http/HttpPlugin.java | 16 ++-- .../plugin/timer/ConstantTimerPlugin.java | 16 ++++ .../agent/scenario/ScenarioContext.java | 16 ++++ .../agent/scenario/ScenarioEngine.java | 51 ++++++++++++ 7 files changed, 227 insertions(+), 39 deletions(-) create mode 100644 src/main/java/org/bench4q/agent/api/AgentController.java create mode 100644 src/main/java/org/bench4q/agent/plugin/timer/ConstantTimerPlugin.java create mode 100644 src/main/java/org/bench4q/agent/scenario/ScenarioContext.java create mode 100644 src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java diff --git a/src/main/java/org/bench4q/agent/api/AgentController.java b/src/main/java/org/bench4q/agent/api/AgentController.java new file mode 100644 index 00000000..d76de836 --- /dev/null +++ b/src/main/java/org/bench4q/agent/api/AgentController.java @@ -0,0 +1,5 @@ +package org.bench4q.agent.api; + +public class AgentController { + +} diff --git a/src/main/java/org/bench4q/agent/api/HomeController.java b/src/main/java/org/bench4q/agent/api/HomeController.java index c044a3d5..2ef18060 100644 --- a/src/main/java/org/bench4q/agent/api/HomeController.java +++ b/src/main/java/org/bench4q/agent/api/HomeController.java @@ -1,9 +1,10 @@ package org.bench4q.agent.api; -import java.util.HashMap; -import java.util.Map; - -import org.bench4q.agent.plugin.PluginManager; +import org.bench4q.agent.scenario.Parameter; +import org.bench4q.agent.scenario.Scenario; +import org.bench4q.agent.scenario.ScenarioEngine; +import org.bench4q.agent.scenario.UsePlugin; +import org.bench4q.agent.scenario.UserBehavior; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @@ -13,27 +14,73 @@ import org.springframework.web.bind.annotation.ResponseBody; @Controller @RequestMapping("/") public class HomeController { - private PluginManager pluginManager; + private ScenarioEngine scenarioEngine; - private PluginManager getPluginManager() { - return pluginManager; + private ScenarioEngine getScenarioEngine() { + return scenarioEngine; } @Autowired - private void setPluginManager(PluginManager pluginManager) { - this.pluginManager = pluginManager; + private void setScenarioEngine(ScenarioEngine scenarioEngine) { + this.scenarioEngine = scenarioEngine; } @RequestMapping(value = { "/" }, method = RequestMethod.GET) @ResponseBody public String index() { - Class plugin = this.getPluginManager().getPlugin("Http"); - Map parameters = new HashMap(); - parameters.put("abc", "123"); - parameters.put("def", "Test DEF"); - parameters.put("ghi", "23.4"); - Object object = this.getPluginManager().initializePlugin(plugin, - parameters); - return object.toString(); + Scenario scenario = new Scenario(); + + scenario.setUsePlugins(new UsePlugin[2]); + scenario.getUsePlugins()[0] = new UsePlugin(); + scenario.getUsePlugins()[0].setId("http"); + scenario.getUsePlugins()[0].setName("Http"); + scenario.getUsePlugins()[0].setParameters(new Parameter[0]); + + scenario.getUsePlugins()[1] = new UsePlugin(); + scenario.getUsePlugins()[1].setId("timer"); + scenario.getUsePlugins()[1].setName("ConstantTimer"); + scenario.getUsePlugins()[1].setParameters(new Parameter[1]); + scenario.getUsePlugins()[1].getParameters()[0] = new Parameter(); + scenario.getUsePlugins()[1].getParameters()[0].setKey("time"); + scenario.getUsePlugins()[1].getParameters()[0].setValue("100"); + + scenario.setUserBehaviors(new UserBehavior[3]); + scenario.getUserBehaviors()[0] = new UserBehavior(); + scenario.getUserBehaviors()[0].setUse("http"); + scenario.getUserBehaviors()[0].setName("Get"); + scenario.getUserBehaviors()[0].setParameters(new Parameter[2]); + scenario.getUserBehaviors()[0].getParameters()[0] = new Parameter(); + scenario.getUserBehaviors()[0].getParameters()[0].setKey("url"); + scenario.getUserBehaviors()[0].getParameters()[0].setValue("localhost"); + scenario.getUserBehaviors()[0].getParameters()[1] = new Parameter(); + scenario.getUserBehaviors()[0].getParameters()[1].setKey("content"); + scenario.getUserBehaviors()[0].getParameters()[1] + .setValue("Hello,world!"); + + scenario.getUserBehaviors()[1] = new UserBehavior(); + scenario.getUserBehaviors()[1].setUse("http"); + scenario.getUserBehaviors()[1].setName("Post"); + scenario.getUserBehaviors()[1].setParameters(new Parameter[3]); + scenario.getUserBehaviors()[1].getParameters()[0] = new Parameter(); + scenario.getUserBehaviors()[1].getParameters()[0].setKey("url"); + scenario.getUserBehaviors()[1].getParameters()[0].setValue("localhost"); + scenario.getUserBehaviors()[1].getParameters()[1] = new Parameter(); + scenario.getUserBehaviors()[1].getParameters()[1].setKey("content"); + scenario.getUserBehaviors()[1].getParameters()[1] + .setValue("Hello,world!"); + scenario.getUserBehaviors()[1].getParameters()[2] = new Parameter(); + scenario.getUserBehaviors()[1].getParameters()[2].setKey("code"); + scenario.getUserBehaviors()[1].getParameters()[2].setValue("404"); + + scenario.getUserBehaviors()[2] = new UserBehavior(); + scenario.getUserBehaviors()[2].setUse("timer"); + scenario.getUserBehaviors()[2].setName("Sleep"); + scenario.getUserBehaviors()[2].setParameters(new Parameter[1]); + scenario.getUserBehaviors()[2].getParameters()[0] = new Parameter(); + scenario.getUserBehaviors()[2].getParameters()[0].setKey("time"); + scenario.getUserBehaviors()[2].getParameters()[0].setValue("1000"); + + this.getScenarioEngine().runScenario(scenario); + return "It works!"; } } \ No newline at end of file diff --git a/src/main/java/org/bench4q/agent/plugin/PluginManager.java b/src/main/java/org/bench4q/agent/plugin/PluginManager.java index d1ae86a0..4fdd1cc6 100644 --- a/src/main/java/org/bench4q/agent/plugin/PluginManager.java +++ b/src/main/java/org/bench4q/agent/plugin/PluginManager.java @@ -1,13 +1,17 @@ package org.bench4q.agent.plugin; +import java.lang.reflect.Method; import java.util.HashMap; import java.util.List; import java.util.Map; import javassist.ClassPool; +import javassist.CtBehavior; import javassist.CtClass; import javassist.CtConstructor; +import javassist.CtMethod; import javassist.Modifier; +import javassist.NotFoundException; import javassist.bytecode.CodeAttribute; import javassist.bytecode.LocalVariableAttribute; import javassist.bytecode.MethodInfo; @@ -70,23 +74,68 @@ public class PluginManager { return null; } CtConstructor constructor = ctConstructors[0]; - MethodInfo methodInfo = constructor.getMethodInfo(); - CodeAttribute codeAttribute = methodInfo.getCodeAttribute(); - LocalVariableAttribute localVariableAttribute = (LocalVariableAttribute) codeAttribute - .getAttribute(LocalVariableAttribute.tag); - int parameterCount = constructor.getParameterTypes().length; - String parameterNames[] = new String[parameterCount]; - Object values[] = new Object[parameterCount]; - int i; - int pos = Modifier.isStatic(constructor.getModifiers()) ? 0 : 1; - for (i = 0; i < parameterCount; i++) { - parameterNames[i] = localVariableAttribute - .variableName(i + pos); - values[i] = this.getTypeConverter().convert( - parameters.get(parameterNames[i]), - constructor.getParameterTypes()[i].getName()); + Object[] params = prepareParameters(constructor, parameters); + return plugin.getConstructors()[0].newInstance(params); + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } + + private Object[] prepareParameters(CtBehavior constructor, + Map parameters) throws NotFoundException { + MethodInfo methodInfo = constructor.getMethodInfo(); + CodeAttribute codeAttribute = methodInfo.getCodeAttribute(); + LocalVariableAttribute localVariableAttribute = (LocalVariableAttribute) codeAttribute + .getAttribute(LocalVariableAttribute.tag); + int parameterCount = constructor.getParameterTypes().length; + String parameterNames[] = new String[parameterCount]; + Object values[] = new Object[parameterCount]; + int i; + int pos = Modifier.isStatic(constructor.getModifiers()) ? 0 : 1; + for (i = 0; i < parameterCount; i++) { + parameterNames[i] = localVariableAttribute.variableName(i + pos); + values[i] = this.getTypeConverter().convert( + parameters.get(parameterNames[i]), + constructor.getParameterTypes()[i].getName()); + } + return values; + } + + public Object doBehavior(Object plugin, String behaviorName, + Map parameters) { + try { + ClassPool classPool = ClassPool.getDefault(); + CtClass ctClass = classPool.get(plugin.getClass() + .getCanonicalName()); + CtMethod[] ctMethods = ctClass.getMethods(); + CtMethod ctMethod = null; + + int i = 0; + for (i = 0; i < ctMethods.length; i++) { + if (ctMethods[i].hasAnnotation(Behavior.class)) { + if (((Behavior) ctMethods[i].getAnnotation(Behavior.class)) + .value().equals(behaviorName)) { + ctMethod = ctMethods[i]; + break; + } + } } - return plugin.getConstructors()[0].newInstance(values); + if (ctMethod == null) { + return null; + } + Method[] methods = plugin.getClass().getMethods(); + Method method = null; + for (i = 0; i < methods.length; i++) { + if (methods[i].getName().equals(ctMethod.getName())) { + method = methods[i]; + } + } + if (method == null) { + return null; + } + Object[] params = prepareParameters(ctMethod, parameters); + return method.invoke(plugin, params); } catch (Exception e) { e.printStackTrace(); return null; diff --git a/src/main/java/org/bench4q/agent/plugin/http/HttpPlugin.java b/src/main/java/org/bench4q/agent/plugin/http/HttpPlugin.java index 469b1140..aff35df4 100644 --- a/src/main/java/org/bench4q/agent/plugin/http/HttpPlugin.java +++ b/src/main/java/org/bench4q/agent/plugin/http/HttpPlugin.java @@ -5,14 +5,18 @@ import org.bench4q.agent.plugin.Plugin; @Plugin("Http") public class HttpPlugin { - public HttpPlugin(int abc, String def, double ghi) { - System.out.println(abc); - System.out.println(def); - System.out.println(ghi); + public HttpPlugin() { + System.out.println("Http Plugin init..."); } @Behavior("Get") - public void doGet(String url) { - System.out.println("Get " + url); + public void get(String url, String content) { + System.out.println("HTTP GET, url=" + url + ", content=" + content); + } + + @Behavior("Post") + public void post(String url, String content, int code) { + System.out.println("HTTP POST, url=" + url + ", content=" + content + + ", code=" + code); } } diff --git a/src/main/java/org/bench4q/agent/plugin/timer/ConstantTimerPlugin.java b/src/main/java/org/bench4q/agent/plugin/timer/ConstantTimerPlugin.java new file mode 100644 index 00000000..5fe3a951 --- /dev/null +++ b/src/main/java/org/bench4q/agent/plugin/timer/ConstantTimerPlugin.java @@ -0,0 +1,16 @@ +package org.bench4q.agent.plugin.timer; + +import org.bench4q.agent.plugin.Behavior; +import org.bench4q.agent.plugin.Plugin; + +@Plugin("ConstantTimer") +public class ConstantTimerPlugin { + public ConstantTimerPlugin(int time) { + System.out.println("Constant Plugin init... time=" + time); + } + + @Behavior("Sleep") + public void sleep(int time) { + System.out.println("Sleeping for " + time + "..."); + } +} diff --git a/src/main/java/org/bench4q/agent/scenario/ScenarioContext.java b/src/main/java/org/bench4q/agent/scenario/ScenarioContext.java new file mode 100644 index 00000000..ebfab4b2 --- /dev/null +++ b/src/main/java/org/bench4q/agent/scenario/ScenarioContext.java @@ -0,0 +1,16 @@ +package org.bench4q.agent.scenario; + +import java.util.Map; + +public class ScenarioContext { + private Map plugins; + + public Map getPlugins() { + return plugins; + } + + public void setPlugins(Map plugins) { + this.plugins = plugins; + } + +} diff --git a/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java b/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java new file mode 100644 index 00000000..6f344d49 --- /dev/null +++ b/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java @@ -0,0 +1,51 @@ +package org.bench4q.agent.scenario; + +import java.util.HashMap; +import java.util.Map; + +import org.bench4q.agent.plugin.PluginManager; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +@Component +public class ScenarioEngine { + private PluginManager pluginManager; + + private PluginManager getPluginManager() { + return pluginManager; + } + + @Autowired + private void setPluginManager(PluginManager pluginManager) { + this.pluginManager = pluginManager; + } + + public void runScenario(Scenario scenario) { + ScenarioContext scenarioContext = new ScenarioContext(); + scenarioContext.setPlugins(new HashMap()); + for (UsePlugin usePlugin : scenario.getUsePlugins()) { + String pluginId = usePlugin.getId(); + Class pluginClass = this.getPluginManager().getPlugin( + usePlugin.getName()); + Map initParameters = new HashMap(); + for (Parameter parameter : usePlugin.getParameters()) { + initParameters.put(parameter.getKey(), parameter.getValue()); + } + Object plugin = this.getPluginManager().initializePlugin( + pluginClass, initParameters); + scenarioContext.getPlugins().put(pluginId, plugin); + } + for (UserBehavior userBehavior : scenario.getUserBehaviors()) { + Object plugin = scenarioContext.getPlugins().get( + userBehavior.getUse()); + String behaviorName = userBehavior.getName(); + Map behaviorParameters = new HashMap(); + for (Parameter parameter : userBehavior.getParameters()) { + behaviorParameters + .put(parameter.getKey(), parameter.getValue()); + } + this.getPluginManager().doBehavior(plugin, behaviorName, + behaviorParameters); + } + } +} From 147c40166d13366d7d7a579ae4b9b8ef3799f364 Mon Sep 17 00:00:00 2001 From: Zhen Tang Date: Wed, 26 Jun 2013 17:08:00 +0800 Subject: [PATCH 009/196] Thread pool added. --- .../org/bench4q/agent/api/HomeController.java | 2 +- .../bench4q/agent/plugin/http/HttpPlugin.java | 7 +++--- .../plugin/timer/ConstantTimerPlugin.java | 4 ++-- .../agent/scenario/ScenarioEngine.java | 24 +++++++++++++++++++ 4 files changed, 30 insertions(+), 7 deletions(-) diff --git a/src/main/java/org/bench4q/agent/api/HomeController.java b/src/main/java/org/bench4q/agent/api/HomeController.java index 2ef18060..cb4fedb0 100644 --- a/src/main/java/org/bench4q/agent/api/HomeController.java +++ b/src/main/java/org/bench4q/agent/api/HomeController.java @@ -80,7 +80,7 @@ public class HomeController { scenario.getUserBehaviors()[2].getParameters()[0].setKey("time"); scenario.getUserBehaviors()[2].getParameters()[0].setValue("1000"); - this.getScenarioEngine().runScenario(scenario); + this.getScenarioEngine().runScenario(scenario, 1000); return "It works!"; } } \ No newline at end of file diff --git a/src/main/java/org/bench4q/agent/plugin/http/HttpPlugin.java b/src/main/java/org/bench4q/agent/plugin/http/HttpPlugin.java index aff35df4..27467cb4 100644 --- a/src/main/java/org/bench4q/agent/plugin/http/HttpPlugin.java +++ b/src/main/java/org/bench4q/agent/plugin/http/HttpPlugin.java @@ -6,17 +6,16 @@ import org.bench4q.agent.plugin.Plugin; @Plugin("Http") public class HttpPlugin { public HttpPlugin() { - System.out.println("Http Plugin init..."); + } @Behavior("Get") public void get(String url, String content) { - System.out.println("HTTP GET, url=" + url + ", content=" + content); + } @Behavior("Post") public void post(String url, String content, int code) { - System.out.println("HTTP POST, url=" + url + ", content=" + content - + ", code=" + code); + } } diff --git a/src/main/java/org/bench4q/agent/plugin/timer/ConstantTimerPlugin.java b/src/main/java/org/bench4q/agent/plugin/timer/ConstantTimerPlugin.java index 5fe3a951..010b021c 100644 --- a/src/main/java/org/bench4q/agent/plugin/timer/ConstantTimerPlugin.java +++ b/src/main/java/org/bench4q/agent/plugin/timer/ConstantTimerPlugin.java @@ -6,11 +6,11 @@ import org.bench4q.agent.plugin.Plugin; @Plugin("ConstantTimer") public class ConstantTimerPlugin { public ConstantTimerPlugin(int time) { - System.out.println("Constant Plugin init... time=" + time); + } @Behavior("Sleep") public void sleep(int time) { - System.out.println("Sleeping for " + time + "..."); + } } diff --git a/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java b/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java index 6f344d49..f6b51eb2 100644 --- a/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java +++ b/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java @@ -1,7 +1,10 @@ package org.bench4q.agent.scenario; +import java.util.Date; import java.util.HashMap; import java.util.Map; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; import org.bench4q.agent.plugin.PluginManager; import org.springframework.beans.factory.annotation.Autowired; @@ -20,7 +23,28 @@ public class ScenarioEngine { this.pluginManager = pluginManager; } + public void runScenario(final Scenario scenario, int threadCount) { + System.out.println("Start at:" + new Date(System.currentTimeMillis())); + ExecutorService executorService = Executors + .newFixedThreadPool(threadCount); + int i; + Runnable runnable = new Runnable() { + public void run() { + doRunScenario(scenario); + } + }; + for (i = 0; i < threadCount; i++) { + executorService.execute(runnable); + } + executorService.shutdown(); + System.out.println("End at:" + new Date(System.currentTimeMillis())); + } + public void runScenario(Scenario scenario) { + this.doRunScenario(scenario); + } + + private void doRunScenario(Scenario scenario) { ScenarioContext scenarioContext = new ScenarioContext(); scenarioContext.setPlugins(new HashMap()); for (UsePlugin usePlugin : scenario.getUsePlugins()) { From 33c09a2de66fef3f05606d3747c971b7462a7bd4 Mon Sep 17 00:00:00 2001 From: Zhen Tang Date: Thu, 27 Jun 2013 00:07:49 +0800 Subject: [PATCH 010/196] Plugin manager updated. --- .../org/bench4q/agent/api/HomeController.java | 2 +- .../bench4q/agent/plugin/BehaviorInfo.java | 23 ++++ .../org/bench4q/agent/plugin/PluginInfo.java | 32 +++++ .../bench4q/agent/plugin/PluginManager.java | 109 ++++++++++++++---- .../bench4q/agent/plugin/http/HttpPlugin.java | 11 +- .../plugin/timer/ConstantTimerPlugin.java | 4 +- .../agent/scenario/ScenarioEngine.java | 4 +- 7 files changed, 157 insertions(+), 28 deletions(-) create mode 100644 src/main/java/org/bench4q/agent/plugin/BehaviorInfo.java create mode 100644 src/main/java/org/bench4q/agent/plugin/PluginInfo.java diff --git a/src/main/java/org/bench4q/agent/api/HomeController.java b/src/main/java/org/bench4q/agent/api/HomeController.java index cb4fedb0..2ef18060 100644 --- a/src/main/java/org/bench4q/agent/api/HomeController.java +++ b/src/main/java/org/bench4q/agent/api/HomeController.java @@ -80,7 +80,7 @@ public class HomeController { scenario.getUserBehaviors()[2].getParameters()[0].setKey("time"); scenario.getUserBehaviors()[2].getParameters()[0].setValue("1000"); - this.getScenarioEngine().runScenario(scenario, 1000); + this.getScenarioEngine().runScenario(scenario); return "It works!"; } } \ No newline at end of file diff --git a/src/main/java/org/bench4q/agent/plugin/BehaviorInfo.java b/src/main/java/org/bench4q/agent/plugin/BehaviorInfo.java new file mode 100644 index 00000000..96317ac3 --- /dev/null +++ b/src/main/java/org/bench4q/agent/plugin/BehaviorInfo.java @@ -0,0 +1,23 @@ +package org.bench4q.agent.plugin; + +public class BehaviorInfo { + private String name; + private String[] parameters; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String[] getParameters() { + return parameters; + } + + public void setParameters(String[] parameters) { + this.parameters = parameters; + } + +} diff --git a/src/main/java/org/bench4q/agent/plugin/PluginInfo.java b/src/main/java/org/bench4q/agent/plugin/PluginInfo.java new file mode 100644 index 00000000..d3c8aa39 --- /dev/null +++ b/src/main/java/org/bench4q/agent/plugin/PluginInfo.java @@ -0,0 +1,32 @@ +package org.bench4q.agent.plugin; + +public class PluginInfo { + private String name; + private String parameters[]; + private BehaviorInfo[] behaviors; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String[] getParameters() { + return parameters; + } + + public void setParameters(String[] parameters) { + this.parameters = parameters; + } + + public BehaviorInfo[] getBehaviors() { + return behaviors; + } + + public void setBehaviors(BehaviorInfo[] behaviors) { + this.behaviors = behaviors; + } + +} diff --git a/src/main/java/org/bench4q/agent/plugin/PluginManager.java b/src/main/java/org/bench4q/agent/plugin/PluginManager.java index 4fdd1cc6..8a9f758d 100644 --- a/src/main/java/org/bench4q/agent/plugin/PluginManager.java +++ b/src/main/java/org/bench4q/agent/plugin/PluginManager.java @@ -1,6 +1,7 @@ package org.bench4q.agent.plugin; import java.lang.reflect.Method; +import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -11,7 +12,6 @@ import javassist.CtClass; import javassist.CtConstructor; import javassist.CtMethod; import javassist.Modifier; -import javassist.NotFoundException; import javassist.bytecode.CodeAttribute; import javassist.bytecode.LocalVariableAttribute; import javassist.bytecode.MethodInfo; @@ -60,8 +60,79 @@ public class PluginManager { } } - public Class getPlugin(String name) { - return this.findPlugins("org.bench4q.agent.plugin").get(name); + public Map> getPlugins() { + return this.findPlugins("org.bench4q.agent.plugin"); + } + + public List getPluginInfo() { + try { + Map> plugins = this.getPlugins(); + List ret = new ArrayList(); + for (Class plugin : plugins.values()) { + PluginInfo pluginInfo = new PluginInfo(); + ClassPool classPool = ClassPool.getDefault(); + CtClass ctClass = classPool.get(plugin.getCanonicalName()); + pluginInfo.setName(((Plugin) ctClass + .getAnnotation(Plugin.class)).value()); + pluginInfo.setParameters(this.getParameterNames(ctClass + .getConstructors()[0])); + CtMethod[] behaviors = this.getBehaviors(ctClass); + pluginInfo.setBehaviors(new BehaviorInfo[behaviors.length]); + int i = 0; + for (i = 0; i < behaviors.length; i++) { + BehaviorInfo behaviorInfo = new BehaviorInfo(); + CtMethod behaviorMethod = behaviors[i]; + behaviorInfo.setName(((Behavior) behaviorMethod + .getAnnotation(Behavior.class)).value()); + behaviorInfo.setParameters(this + .getParameterNames(behaviorMethod)); + pluginInfo.getBehaviors()[i] = behaviorInfo; + } + ret.add(pluginInfo); + } + return ret; + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } + + private String[] getParameterNames(CtBehavior behavior) { + try { + MethodInfo methodInfo = behavior.getMethodInfo(); + CodeAttribute codeAttribute = methodInfo.getCodeAttribute(); + LocalVariableAttribute localVariableAttribute = (LocalVariableAttribute) codeAttribute + .getAttribute(LocalVariableAttribute.tag); + int parameterCount = behavior.getParameterTypes().length; + String parameterNames[] = new String[parameterCount]; + int i; + int pos = Modifier.isStatic(behavior.getModifiers()) ? 0 : 1; + for (i = 0; i < parameterCount; i++) { + parameterNames[i] = localVariableAttribute + .variableName(i + pos); + } + return parameterNames; + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } + + private CtMethod[] getBehaviors(CtClass plugin) { + try { + CtMethod[] ctMethods = plugin.getMethods(); + List ret = new ArrayList(); + int i = 0; + for (i = 0; i < ctMethods.length; i++) { + if (ctMethods[i].hasAnnotation(Behavior.class)) { + ret.add(ctMethods[i]); + } + } + return ret.toArray(new CtMethod[0]); + } catch (Exception e) { + e.printStackTrace(); + return null; + } } public Object initializePlugin(Class plugin, @@ -82,24 +153,22 @@ public class PluginManager { } } - private Object[] prepareParameters(CtBehavior constructor, - Map parameters) throws NotFoundException { - MethodInfo methodInfo = constructor.getMethodInfo(); - CodeAttribute codeAttribute = methodInfo.getCodeAttribute(); - LocalVariableAttribute localVariableAttribute = (LocalVariableAttribute) codeAttribute - .getAttribute(LocalVariableAttribute.tag); - int parameterCount = constructor.getParameterTypes().length; - String parameterNames[] = new String[parameterCount]; - Object values[] = new Object[parameterCount]; - int i; - int pos = Modifier.isStatic(constructor.getModifiers()) ? 0 : 1; - for (i = 0; i < parameterCount; i++) { - parameterNames[i] = localVariableAttribute.variableName(i + pos); - values[i] = this.getTypeConverter().convert( - parameters.get(parameterNames[i]), - constructor.getParameterTypes()[i].getName()); + private Object[] prepareParameters(CtBehavior behavior, + Map parameters) { + try { + String[] parameterNames = this.getParameterNames(behavior); + Object values[] = new Object[parameterNames.length]; + int i = 0; + for (i = 0; i < parameterNames.length; i++) { + values[i] = this.getTypeConverter().convert( + parameters.get(parameterNames[i]), + behavior.getParameterTypes()[i].getName()); + } + return values; + } catch (Exception e) { + e.printStackTrace(); + return null; } - return values; } public Object doBehavior(Object plugin, String behaviorName, diff --git a/src/main/java/org/bench4q/agent/plugin/http/HttpPlugin.java b/src/main/java/org/bench4q/agent/plugin/http/HttpPlugin.java index 27467cb4..7703736b 100644 --- a/src/main/java/org/bench4q/agent/plugin/http/HttpPlugin.java +++ b/src/main/java/org/bench4q/agent/plugin/http/HttpPlugin.java @@ -6,16 +6,21 @@ import org.bench4q.agent.plugin.Plugin; @Plugin("Http") public class HttpPlugin { public HttpPlugin() { - + System.out.println("init http plugin"); } @Behavior("Get") public void get(String url, String content) { - + System.out.println("get"); + System.out.println("url:" + url); + System.out.println("content:" + content); } @Behavior("Post") public void post(String url, String content, int code) { - + System.out.println("get"); + System.out.println("url:" + url); + System.out.println("content:" + content); + System.out.println("code:" + code); } } diff --git a/src/main/java/org/bench4q/agent/plugin/timer/ConstantTimerPlugin.java b/src/main/java/org/bench4q/agent/plugin/timer/ConstantTimerPlugin.java index 010b021c..0ef601fc 100644 --- a/src/main/java/org/bench4q/agent/plugin/timer/ConstantTimerPlugin.java +++ b/src/main/java/org/bench4q/agent/plugin/timer/ConstantTimerPlugin.java @@ -6,11 +6,11 @@ import org.bench4q.agent.plugin.Plugin; @Plugin("ConstantTimer") public class ConstantTimerPlugin { public ConstantTimerPlugin(int time) { - + System.out.println("init timer plugin: " + time); } @Behavior("Sleep") public void sleep(int time) { - + System.out.println("sleep:" + time); } } diff --git a/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java b/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java index f6b51eb2..a1062483 100644 --- a/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java +++ b/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java @@ -49,8 +49,8 @@ public class ScenarioEngine { scenarioContext.setPlugins(new HashMap()); for (UsePlugin usePlugin : scenario.getUsePlugins()) { String pluginId = usePlugin.getId(); - Class pluginClass = this.getPluginManager().getPlugin( - usePlugin.getName()); + Class pluginClass = this.getPluginManager().getPlugins() + .get(usePlugin.getName()); Map initParameters = new HashMap(); for (Parameter parameter : usePlugin.getParameters()) { initParameters.put(parameter.getKey(), parameter.getValue()); From 0d545811b8eb72862015edbe520d34f121eea169 Mon Sep 17 00:00:00 2001 From: Zhen Tang Date: Thu, 27 Jun 2013 15:34:41 +0800 Subject: [PATCH 011/196] plugins are only loaded while starting. --- .../org/bench4q/agent/api/HomeController.java | 2 +- .../bench4q/agent/plugin/PluginManager.java | 22 ++++++++++++++----- .../plugin/timer/ConstantTimerPlugin.java | 2 +- .../agent/scenario/ScenarioEngine.java | 9 ++++---- 4 files changed, 22 insertions(+), 13 deletions(-) diff --git a/src/main/java/org/bench4q/agent/api/HomeController.java b/src/main/java/org/bench4q/agent/api/HomeController.java index cb4fedb0..69fdd854 100644 --- a/src/main/java/org/bench4q/agent/api/HomeController.java +++ b/src/main/java/org/bench4q/agent/api/HomeController.java @@ -80,7 +80,7 @@ public class HomeController { scenario.getUserBehaviors()[2].getParameters()[0].setKey("time"); scenario.getUserBehaviors()[2].getParameters()[0].setValue("1000"); - this.getScenarioEngine().runScenario(scenario, 1000); + this.getScenarioEngine().runScenario(scenario, 100); return "It works!"; } } \ No newline at end of file diff --git a/src/main/java/org/bench4q/agent/plugin/PluginManager.java b/src/main/java/org/bench4q/agent/plugin/PluginManager.java index 4fdd1cc6..a39dc8db 100644 --- a/src/main/java/org/bench4q/agent/plugin/PluginManager.java +++ b/src/main/java/org/bench4q/agent/plugin/PluginManager.java @@ -23,12 +23,19 @@ import org.springframework.stereotype.Component; public class PluginManager { private ClassHelper classHelper; private TypeConverter typeConverter; + private Map> plugins; + + @Autowired + public PluginManager(ClassHelper classHelper, TypeConverter typeConverter) { + this.setClassHelper(classHelper); + this.setTypeConverter(typeConverter); + this.setPlugins(this.findPlugins("org.bench4q.agent.plugin")); + } private ClassHelper getClassHelper() { return classHelper; } - @Autowired private void setClassHelper(ClassHelper classHelper) { this.classHelper = classHelper; } @@ -37,11 +44,18 @@ public class PluginManager { return typeConverter; } - @Autowired private void setTypeConverter(TypeConverter typeConverter) { this.typeConverter = typeConverter; } + public Map> getPlugins() { + return plugins; + } + + private void setPlugins(Map> plugins) { + this.plugins = plugins; + } + private Map> findPlugins(String packageName) { try { List classNames = this.getClassHelper().getClassNames( @@ -60,10 +74,6 @@ public class PluginManager { } } - public Class getPlugin(String name) { - return this.findPlugins("org.bench4q.agent.plugin").get(name); - } - public Object initializePlugin(Class plugin, Map parameters) { try { diff --git a/src/main/java/org/bench4q/agent/plugin/timer/ConstantTimerPlugin.java b/src/main/java/org/bench4q/agent/plugin/timer/ConstantTimerPlugin.java index 010b021c..f78d857f 100644 --- a/src/main/java/org/bench4q/agent/plugin/timer/ConstantTimerPlugin.java +++ b/src/main/java/org/bench4q/agent/plugin/timer/ConstantTimerPlugin.java @@ -5,7 +5,7 @@ import org.bench4q.agent.plugin.Plugin; @Plugin("ConstantTimer") public class ConstantTimerPlugin { - public ConstantTimerPlugin(int time) { + public ConstantTimerPlugin() { } diff --git a/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java b/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java index f6b51eb2..51a849d8 100644 --- a/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java +++ b/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java @@ -1,6 +1,5 @@ package org.bench4q.agent.scenario; -import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ExecutorService; @@ -24,7 +23,6 @@ public class ScenarioEngine { } public void runScenario(final Scenario scenario, int threadCount) { - System.out.println("Start at:" + new Date(System.currentTimeMillis())); ExecutorService executorService = Executors .newFixedThreadPool(threadCount); int i; @@ -37,7 +35,6 @@ public class ScenarioEngine { executorService.execute(runnable); } executorService.shutdown(); - System.out.println("End at:" + new Date(System.currentTimeMillis())); } public void runScenario(Scenario scenario) { @@ -45,12 +42,13 @@ public class ScenarioEngine { } private void doRunScenario(Scenario scenario) { + System.out.println("Running"); ScenarioContext scenarioContext = new ScenarioContext(); scenarioContext.setPlugins(new HashMap()); for (UsePlugin usePlugin : scenario.getUsePlugins()) { String pluginId = usePlugin.getId(); - Class pluginClass = this.getPluginManager().getPlugin( - usePlugin.getName()); + Class pluginClass = this.getPluginManager().getPlugins() + .get(usePlugin.getName()); Map initParameters = new HashMap(); for (Parameter parameter : usePlugin.getParameters()) { initParameters.put(parameter.getKey(), parameter.getValue()); @@ -71,5 +69,6 @@ public class ScenarioEngine { this.getPluginManager().doBehavior(plugin, behaviorName, behaviorParameters); } + System.out.println("Finished"); } } From 7344b4e3e1bcc84ee7bf3503ca858b1683ff3ffe Mon Sep 17 00:00:00 2001 From: Zhen Tang Date: Thu, 27 Jun 2013 16:10:04 +0800 Subject: [PATCH 012/196] plugin info api added. --- .../org/bench4q/agent/api/HomeController.java | 12 ++-- .../bench4q/agent/api/PluginController.java | 60 +++++++++++++++++++ .../agent/api/model/BehaviorInfoModel.java | 32 ++++++++++ .../agent/api/model/PluginInfoListModel.java | 23 +++++++ .../agent/api/model/PluginInfoModel.java | 43 +++++++++++++ 5 files changed, 163 insertions(+), 7 deletions(-) create mode 100644 src/main/java/org/bench4q/agent/api/PluginController.java create mode 100644 src/main/java/org/bench4q/agent/api/model/BehaviorInfoModel.java create mode 100644 src/main/java/org/bench4q/agent/api/model/PluginInfoListModel.java create mode 100644 src/main/java/org/bench4q/agent/api/model/PluginInfoModel.java diff --git a/src/main/java/org/bench4q/agent/api/HomeController.java b/src/main/java/org/bench4q/agent/api/HomeController.java index 999c1306..93f30550 100644 --- a/src/main/java/org/bench4q/agent/api/HomeController.java +++ b/src/main/java/org/bench4q/agent/api/HomeController.java @@ -28,6 +28,7 @@ public class HomeController { @RequestMapping(value = { "/" }, method = RequestMethod.GET) @ResponseBody public String index() { + Scenario scenario = new Scenario(); scenario.setUsePlugins(new UsePlugin[2]); @@ -39,10 +40,7 @@ public class HomeController { scenario.getUsePlugins()[1] = new UsePlugin(); scenario.getUsePlugins()[1].setId("timer"); scenario.getUsePlugins()[1].setName("ConstantTimer"); - scenario.getUsePlugins()[1].setParameters(new Parameter[1]); - scenario.getUsePlugins()[1].getParameters()[0] = new Parameter(); - scenario.getUsePlugins()[1].getParameters()[0].setKey("time"); - scenario.getUsePlugins()[1].getParameters()[0].setValue("100"); + scenario.getUsePlugins()[1].setParameters(new Parameter[0]); scenario.setUserBehaviors(new UserBehavior[3]); scenario.getUserBehaviors()[0] = new UserBehavior(); @@ -79,8 +77,8 @@ public class HomeController { scenario.getUserBehaviors()[2].getParameters()[0] = new Parameter(); scenario.getUserBehaviors()[2].getParameters()[0].setKey("time"); scenario.getUserBehaviors()[2].getParameters()[0].setValue("1000"); - - this.getScenarioEngine().runScenario(scenario, 100); + + this.getScenarioEngine().runScenario(scenario, 100); return "It works!"; } -} +} diff --git a/src/main/java/org/bench4q/agent/api/PluginController.java b/src/main/java/org/bench4q/agent/api/PluginController.java new file mode 100644 index 00000000..a701b443 --- /dev/null +++ b/src/main/java/org/bench4q/agent/api/PluginController.java @@ -0,0 +1,60 @@ +package org.bench4q.agent.api; + +import java.util.ArrayList; +import java.util.List; + +import org.bench4q.agent.api.model.BehaviorInfoModel; +import org.bench4q.agent.api.model.PluginInfoListModel; +import org.bench4q.agent.api.model.PluginInfoModel; +import org.bench4q.agent.plugin.BehaviorInfo; +import org.bench4q.agent.plugin.PluginInfo; +import org.bench4q.agent.plugin.PluginManager; +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.ResponseBody; + +@Controller +@RequestMapping("/plugin") +public class PluginController { + private PluginManager pluginManager; + + public PluginManager getPluginManager() { + return pluginManager; + } + + @Autowired + public void setPluginManager(PluginManager pluginManager) { + this.pluginManager = pluginManager; + } + + @RequestMapping(method = RequestMethod.GET) + @ResponseBody + public PluginInfoListModel list() { + List pluginInfos = this.getPluginManager().getPluginInfo(); + PluginInfoListModel pluginInfoListModel = new PluginInfoListModel(); + pluginInfoListModel.setPlugins(new ArrayList()); + for (PluginInfo pluginInfo : pluginInfos) { + PluginInfoModel pluginInfoModel = new PluginInfoModel(); + pluginInfoModel.setName(pluginInfo.getName()); + pluginInfoModel.setParameters(new ArrayList()); + for (String param : pluginInfo.getParameters()) { + pluginInfoModel.getParameters().add(param); + } + pluginInfoModel.setBehaviors(new ArrayList()); + for (BehaviorInfo behaviorInfo : pluginInfo.getBehaviors()) { + BehaviorInfoModel behaviorInfoModel = new BehaviorInfoModel(); + behaviorInfoModel.setName(behaviorInfo.getName()); + behaviorInfoModel.setParameters(new ArrayList()); + for (String param : behaviorInfo.getParameters()) { + behaviorInfoModel.getParameters().add(param); + } + pluginInfoModel.getBehaviors().add(behaviorInfoModel); + } + pluginInfoListModel.getPlugins().add(pluginInfoModel); + } + return pluginInfoListModel; + } + +} diff --git a/src/main/java/org/bench4q/agent/api/model/BehaviorInfoModel.java b/src/main/java/org/bench4q/agent/api/model/BehaviorInfoModel.java new file mode 100644 index 00000000..3b5de043 --- /dev/null +++ b/src/main/java/org/bench4q/agent/api/model/BehaviorInfoModel.java @@ -0,0 +1,32 @@ +package org.bench4q.agent.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 = "behaviorInfo") +public class BehaviorInfoModel { + private String name; + private List parameters; + + @XmlElement + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + @XmlElementWrapper(name = "parameters") + @XmlElement(name = "parameter") + public List getParameters() { + return parameters; + } + + public void setParameters(List parameters) { + this.parameters = parameters; + } +} diff --git a/src/main/java/org/bench4q/agent/api/model/PluginInfoListModel.java b/src/main/java/org/bench4q/agent/api/model/PluginInfoListModel.java new file mode 100644 index 00000000..e927d439 --- /dev/null +++ b/src/main/java/org/bench4q/agent/api/model/PluginInfoListModel.java @@ -0,0 +1,23 @@ +package org.bench4q.agent.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 = "pluginList") +public class PluginInfoListModel { + private List plugins; + + @XmlElementWrapper(name = "plugins") + @XmlElement(name = "plugin") + public List getPlugins() { + return plugins; + } + + public void setPlugins(List plugins) { + this.plugins = plugins; + } + +} diff --git a/src/main/java/org/bench4q/agent/api/model/PluginInfoModel.java b/src/main/java/org/bench4q/agent/api/model/PluginInfoModel.java new file mode 100644 index 00000000..a04bf6d6 --- /dev/null +++ b/src/main/java/org/bench4q/agent/api/model/PluginInfoModel.java @@ -0,0 +1,43 @@ +package org.bench4q.agent.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 = "pluginInfoItem") +public class PluginInfoModel { + private String name; + private List parameters; + private List behaviors; + + @XmlElement + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + @XmlElementWrapper(name = "parameters") + @XmlElement(name = "parameter") + public List getParameters() { + return parameters; + } + + public void setParameters(List parameters) { + this.parameters = parameters; + } + + @XmlElementWrapper(name = "behaviors") + @XmlElement(name = "behavior") + public List getBehaviors() { + return behaviors; + } + + public void setBehaviors(List behaviors) { + this.behaviors = behaviors; + } +} From d41cb8d32aaac5a910216dc57049a4e57ea4f510 Mon Sep 17 00:00:00 2001 From: Zhen Tang Date: Thu, 27 Jun 2013 17:43:04 +0800 Subject: [PATCH 013/196] test service added. --- .../org/bench4q/agent/api/HomeController.java | 68 +-------------- .../bench4q/agent/api/PluginController.java | 4 +- .../org/bench4q/agent/api/TestController.java | 87 +++++++++++++++++++ .../bench4q/agent/plugin/BehaviorResult.java | 34 ++++++++ .../bench4q/agent/plugin/PluginManager.java | 8 +- .../plugin/{ => annotation}/Behavior.java | 2 +- .../agent/plugin/{ => annotation}/Plugin.java | 2 +- .../bench4q/agent/plugin/http/HttpPlugin.java | 33 +++++-- .../plugin/{ => metadata}/BehaviorInfo.java | 2 +- .../plugin/{ => metadata}/PluginInfo.java | 2 +- .../plugin/timer/ConstantTimerPlugin.java | 23 ++++- .../agent/scenario/ScenarioEngine.java | 50 +++++++---- 12 files changed, 211 insertions(+), 104 deletions(-) create mode 100644 src/main/java/org/bench4q/agent/api/TestController.java create mode 100644 src/main/java/org/bench4q/agent/plugin/BehaviorResult.java rename src/main/java/org/bench4q/agent/plugin/{ => annotation}/Behavior.java (82%) rename src/main/java/org/bench4q/agent/plugin/{ => annotation}/Plugin.java (82%) rename src/main/java/org/bench4q/agent/plugin/{ => metadata}/BehaviorInfo.java (83%) rename src/main/java/org/bench4q/agent/plugin/{ => metadata}/PluginInfo.java (87%) diff --git a/src/main/java/org/bench4q/agent/api/HomeController.java b/src/main/java/org/bench4q/agent/api/HomeController.java index 93f30550..8f5c131b 100644 --- a/src/main/java/org/bench4q/agent/api/HomeController.java +++ b/src/main/java/org/bench4q/agent/api/HomeController.java @@ -1,11 +1,5 @@ package org.bench4q.agent.api; -import org.bench4q.agent.scenario.Parameter; -import org.bench4q.agent.scenario.Scenario; -import org.bench4q.agent.scenario.ScenarioEngine; -import org.bench4q.agent.scenario.UsePlugin; -import org.bench4q.agent.scenario.UserBehavior; -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; @@ -14,71 +8,11 @@ import org.springframework.web.bind.annotation.ResponseBody; @Controller @RequestMapping("/") public class HomeController { - private ScenarioEngine scenarioEngine; - private ScenarioEngine getScenarioEngine() { - return scenarioEngine; - } - - @Autowired - private void setScenarioEngine(ScenarioEngine scenarioEngine) { - this.scenarioEngine = scenarioEngine; - } - - @RequestMapping(value = { "/" }, method = RequestMethod.GET) + @RequestMapping(method = RequestMethod.GET) @ResponseBody public String index() { - Scenario scenario = new Scenario(); - - scenario.setUsePlugins(new UsePlugin[2]); - scenario.getUsePlugins()[0] = new UsePlugin(); - scenario.getUsePlugins()[0].setId("http"); - scenario.getUsePlugins()[0].setName("Http"); - scenario.getUsePlugins()[0].setParameters(new Parameter[0]); - - scenario.getUsePlugins()[1] = new UsePlugin(); - scenario.getUsePlugins()[1].setId("timer"); - scenario.getUsePlugins()[1].setName("ConstantTimer"); - scenario.getUsePlugins()[1].setParameters(new Parameter[0]); - - scenario.setUserBehaviors(new UserBehavior[3]); - scenario.getUserBehaviors()[0] = new UserBehavior(); - scenario.getUserBehaviors()[0].setUse("http"); - scenario.getUserBehaviors()[0].setName("Get"); - scenario.getUserBehaviors()[0].setParameters(new Parameter[2]); - scenario.getUserBehaviors()[0].getParameters()[0] = new Parameter(); - scenario.getUserBehaviors()[0].getParameters()[0].setKey("url"); - scenario.getUserBehaviors()[0].getParameters()[0].setValue("localhost"); - scenario.getUserBehaviors()[0].getParameters()[1] = new Parameter(); - scenario.getUserBehaviors()[0].getParameters()[1].setKey("content"); - scenario.getUserBehaviors()[0].getParameters()[1] - .setValue("Hello,world!"); - - scenario.getUserBehaviors()[1] = new UserBehavior(); - scenario.getUserBehaviors()[1].setUse("http"); - scenario.getUserBehaviors()[1].setName("Post"); - scenario.getUserBehaviors()[1].setParameters(new Parameter[3]); - scenario.getUserBehaviors()[1].getParameters()[0] = new Parameter(); - scenario.getUserBehaviors()[1].getParameters()[0].setKey("url"); - scenario.getUserBehaviors()[1].getParameters()[0].setValue("localhost"); - scenario.getUserBehaviors()[1].getParameters()[1] = new Parameter(); - scenario.getUserBehaviors()[1].getParameters()[1].setKey("content"); - scenario.getUserBehaviors()[1].getParameters()[1] - .setValue("Hello,world!"); - scenario.getUserBehaviors()[1].getParameters()[2] = new Parameter(); - scenario.getUserBehaviors()[1].getParameters()[2].setKey("code"); - scenario.getUserBehaviors()[1].getParameters()[2].setValue("404"); - - scenario.getUserBehaviors()[2] = new UserBehavior(); - scenario.getUserBehaviors()[2].setUse("timer"); - scenario.getUserBehaviors()[2].setName("Sleep"); - scenario.getUserBehaviors()[2].setParameters(new Parameter[1]); - scenario.getUserBehaviors()[2].getParameters()[0] = new Parameter(); - scenario.getUserBehaviors()[2].getParameters()[0].setKey("time"); - scenario.getUserBehaviors()[2].getParameters()[0].setValue("1000"); - - this.getScenarioEngine().runScenario(scenario, 100); return "It works!"; } } diff --git a/src/main/java/org/bench4q/agent/api/PluginController.java b/src/main/java/org/bench4q/agent/api/PluginController.java index a701b443..620e1b1b 100644 --- a/src/main/java/org/bench4q/agent/api/PluginController.java +++ b/src/main/java/org/bench4q/agent/api/PluginController.java @@ -6,9 +6,9 @@ import java.util.List; import org.bench4q.agent.api.model.BehaviorInfoModel; import org.bench4q.agent.api.model.PluginInfoListModel; import org.bench4q.agent.api.model.PluginInfoModel; -import org.bench4q.agent.plugin.BehaviorInfo; -import org.bench4q.agent.plugin.PluginInfo; import org.bench4q.agent.plugin.PluginManager; +import org.bench4q.agent.plugin.metadata.BehaviorInfo; +import org.bench4q.agent.plugin.metadata.PluginInfo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; diff --git a/src/main/java/org/bench4q/agent/api/TestController.java b/src/main/java/org/bench4q/agent/api/TestController.java new file mode 100644 index 00000000..2ed43393 --- /dev/null +++ b/src/main/java/org/bench4q/agent/api/TestController.java @@ -0,0 +1,87 @@ +package org.bench4q.agent.api; + +import java.util.List; + +import org.bench4q.agent.plugin.BehaviorResult; +import org.bench4q.agent.scenario.Parameter; +import org.bench4q.agent.scenario.Scenario; +import org.bench4q.agent.scenario.ScenarioEngine; +import org.bench4q.agent.scenario.UsePlugin; +import org.bench4q.agent.scenario.UserBehavior; +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.ResponseBody; + +@Controller +@RequestMapping("/test") +public class TestController { + private ScenarioEngine scenarioEngine; + + private ScenarioEngine getScenarioEngine() { + return scenarioEngine; + } + + @Autowired + private void setScenarioEngine(ScenarioEngine scenarioEngine) { + this.scenarioEngine = scenarioEngine; + } + + @RequestMapping(method = RequestMethod.GET) + @ResponseBody + public String run() { + Scenario scenario = new Scenario(); + + scenario.setUsePlugins(new UsePlugin[2]); + scenario.getUsePlugins()[0] = new UsePlugin(); + scenario.getUsePlugins()[0].setId("http"); + scenario.getUsePlugins()[0].setName("Http"); + scenario.getUsePlugins()[0].setParameters(new Parameter[0]); + + scenario.getUsePlugins()[1] = new UsePlugin(); + scenario.getUsePlugins()[1].setId("timer"); + scenario.getUsePlugins()[1].setName("ConstantTimer"); + scenario.getUsePlugins()[1].setParameters(new Parameter[0]); + + scenario.setUserBehaviors(new UserBehavior[3]); + scenario.getUserBehaviors()[0] = new UserBehavior(); + scenario.getUserBehaviors()[0].setUse("http"); + scenario.getUserBehaviors()[0].setName("Get"); + scenario.getUserBehaviors()[0].setParameters(new Parameter[2]); + scenario.getUserBehaviors()[0].getParameters()[0] = new Parameter(); + scenario.getUserBehaviors()[0].getParameters()[0].setKey("url"); + scenario.getUserBehaviors()[0].getParameters()[0].setValue("localhost"); + scenario.getUserBehaviors()[0].getParameters()[1] = new Parameter(); + scenario.getUserBehaviors()[0].getParameters()[1].setKey("content"); + scenario.getUserBehaviors()[0].getParameters()[1] + .setValue("Hello,world!"); + + scenario.getUserBehaviors()[1] = new UserBehavior(); + scenario.getUserBehaviors()[1].setUse("http"); + scenario.getUserBehaviors()[1].setName("Post"); + scenario.getUserBehaviors()[1].setParameters(new Parameter[3]); + scenario.getUserBehaviors()[1].getParameters()[0] = new Parameter(); + scenario.getUserBehaviors()[1].getParameters()[0].setKey("url"); + scenario.getUserBehaviors()[1].getParameters()[0].setValue("localhost"); + scenario.getUserBehaviors()[1].getParameters()[1] = new Parameter(); + scenario.getUserBehaviors()[1].getParameters()[1].setKey("content"); + scenario.getUserBehaviors()[1].getParameters()[1] + .setValue("Hello,world!"); + scenario.getUserBehaviors()[1].getParameters()[2] = new Parameter(); + scenario.getUserBehaviors()[1].getParameters()[2].setKey("code"); + scenario.getUserBehaviors()[1].getParameters()[2].setValue("404"); + + scenario.getUserBehaviors()[2] = new UserBehavior(); + scenario.getUserBehaviors()[2].setUse("timer"); + scenario.getUserBehaviors()[2].setName("Sleep"); + scenario.getUserBehaviors()[2].setParameters(new Parameter[1]); + scenario.getUserBehaviors()[2].getParameters()[0] = new Parameter(); + scenario.getUserBehaviors()[2].getParameters()[0].setKey("time"); + scenario.getUserBehaviors()[2].getParameters()[0].setValue("1000"); + + List list = this.getScenarioEngine().runScenario( + scenario, 100); + return list.toString(); + } +} diff --git a/src/main/java/org/bench4q/agent/plugin/BehaviorResult.java b/src/main/java/org/bench4q/agent/plugin/BehaviorResult.java new file mode 100644 index 00000000..1376643e --- /dev/null +++ b/src/main/java/org/bench4q/agent/plugin/BehaviorResult.java @@ -0,0 +1,34 @@ +package org.bench4q.agent.plugin; + +import java.util.Date; + +public class BehaviorResult { + private Date startDate; + private Date endDate; + private boolean success; + + public Date getStartDate() { + return startDate; + } + + public void setStartDate(Date startDate) { + this.startDate = startDate; + } + + public Date getEndDate() { + return endDate; + } + + public void setEndDate(Date endDate) { + this.endDate = endDate; + } + + public boolean isSuccess() { + return success; + } + + public void setSuccess(boolean success) { + this.success = success; + } + +} diff --git a/src/main/java/org/bench4q/agent/plugin/PluginManager.java b/src/main/java/org/bench4q/agent/plugin/PluginManager.java index 3dcce486..28df9235 100644 --- a/src/main/java/org/bench4q/agent/plugin/PluginManager.java +++ b/src/main/java/org/bench4q/agent/plugin/PluginManager.java @@ -16,6 +16,10 @@ import javassist.bytecode.CodeAttribute; import javassist.bytecode.LocalVariableAttribute; import javassist.bytecode.MethodInfo; +import org.bench4q.agent.plugin.annotation.Behavior; +import org.bench4q.agent.plugin.annotation.Plugin; +import org.bench4q.agent.plugin.metadata.BehaviorInfo; +import org.bench4q.agent.plugin.metadata.PluginInfo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @@ -29,7 +33,7 @@ public class PluginManager { public PluginManager(ClassHelper classHelper, TypeConverter typeConverter) { this.setClassHelper(classHelper); this.setTypeConverter(typeConverter); - this.setPlugins(this.findPlugins("org.bench4q.agent.plugin")); + this.setPlugins(this.loadPlugins("org.bench4q.agent.plugin")); } private ClassHelper getClassHelper() { @@ -56,7 +60,7 @@ public class PluginManager { this.plugins = plugins; } - private Map> findPlugins(String packageName) { + public Map> loadPlugins(String packageName) { try { List classNames = this.getClassHelper().getClassNames( packageName, true); diff --git a/src/main/java/org/bench4q/agent/plugin/Behavior.java b/src/main/java/org/bench4q/agent/plugin/annotation/Behavior.java similarity index 82% rename from src/main/java/org/bench4q/agent/plugin/Behavior.java rename to src/main/java/org/bench4q/agent/plugin/annotation/Behavior.java index 3fab5f99..6e7d4e60 100644 --- a/src/main/java/org/bench4q/agent/plugin/Behavior.java +++ b/src/main/java/org/bench4q/agent/plugin/annotation/Behavior.java @@ -1,4 +1,4 @@ -package org.bench4q.agent.plugin; +package org.bench4q.agent.plugin.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; diff --git a/src/main/java/org/bench4q/agent/plugin/Plugin.java b/src/main/java/org/bench4q/agent/plugin/annotation/Plugin.java similarity index 82% rename from src/main/java/org/bench4q/agent/plugin/Plugin.java rename to src/main/java/org/bench4q/agent/plugin/annotation/Plugin.java index 7841b547..f35ca906 100644 --- a/src/main/java/org/bench4q/agent/plugin/Plugin.java +++ b/src/main/java/org/bench4q/agent/plugin/annotation/Plugin.java @@ -1,4 +1,4 @@ -package org.bench4q.agent.plugin; +package org.bench4q.agent.plugin.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; diff --git a/src/main/java/org/bench4q/agent/plugin/http/HttpPlugin.java b/src/main/java/org/bench4q/agent/plugin/http/HttpPlugin.java index 7703736b..96b00fe5 100644 --- a/src/main/java/org/bench4q/agent/plugin/http/HttpPlugin.java +++ b/src/main/java/org/bench4q/agent/plugin/http/HttpPlugin.java @@ -1,7 +1,10 @@ package org.bench4q.agent.plugin.http; -import org.bench4q.agent.plugin.Behavior; -import org.bench4q.agent.plugin.Plugin; +import java.util.Date; + +import org.bench4q.agent.plugin.BehaviorResult; +import org.bench4q.agent.plugin.annotation.Behavior; +import org.bench4q.agent.plugin.annotation.Plugin; @Plugin("Http") public class HttpPlugin { @@ -10,17 +13,33 @@ public class HttpPlugin { } @Behavior("Get") - public void get(String url, String content) { - System.out.println("get"); - System.out.println("url:" + url); - System.out.println("content:" + content); + public BehaviorResult get(String url, String content) { + BehaviorResult behaviorResult = new BehaviorResult(); + behaviorResult.setStartDate(new Date(System.currentTimeMillis())); + try { + System.out.println("get"); + System.out.println("url:" + url); + System.out.println("content:" + content); + behaviorResult.setEndDate(new Date(System.currentTimeMillis())); + behaviorResult.setSuccess(true); + } catch (Exception e) { + e.printStackTrace(); + behaviorResult.setEndDate(new Date(System.currentTimeMillis())); + behaviorResult.setSuccess(true); + } + return behaviorResult; } @Behavior("Post") - public void post(String url, String content, int code) { + public BehaviorResult post(String url, String content, int code) { + BehaviorResult behaviorResult = new BehaviorResult(); + behaviorResult.setStartDate(new Date(System.currentTimeMillis())); System.out.println("get"); System.out.println("url:" + url); System.out.println("content:" + content); System.out.println("code:" + code); + behaviorResult.setEndDate(new Date(System.currentTimeMillis())); + behaviorResult.setSuccess(true); + return behaviorResult; } } diff --git a/src/main/java/org/bench4q/agent/plugin/BehaviorInfo.java b/src/main/java/org/bench4q/agent/plugin/metadata/BehaviorInfo.java similarity index 83% rename from src/main/java/org/bench4q/agent/plugin/BehaviorInfo.java rename to src/main/java/org/bench4q/agent/plugin/metadata/BehaviorInfo.java index 96317ac3..547ff43f 100644 --- a/src/main/java/org/bench4q/agent/plugin/BehaviorInfo.java +++ b/src/main/java/org/bench4q/agent/plugin/metadata/BehaviorInfo.java @@ -1,4 +1,4 @@ -package org.bench4q.agent.plugin; +package org.bench4q.agent.plugin.metadata; public class BehaviorInfo { private String name; diff --git a/src/main/java/org/bench4q/agent/plugin/PluginInfo.java b/src/main/java/org/bench4q/agent/plugin/metadata/PluginInfo.java similarity index 87% rename from src/main/java/org/bench4q/agent/plugin/PluginInfo.java rename to src/main/java/org/bench4q/agent/plugin/metadata/PluginInfo.java index d3c8aa39..8742fb59 100644 --- a/src/main/java/org/bench4q/agent/plugin/PluginInfo.java +++ b/src/main/java/org/bench4q/agent/plugin/metadata/PluginInfo.java @@ -1,4 +1,4 @@ -package org.bench4q.agent.plugin; +package org.bench4q.agent.plugin.metadata; public class PluginInfo { private String name; diff --git a/src/main/java/org/bench4q/agent/plugin/timer/ConstantTimerPlugin.java b/src/main/java/org/bench4q/agent/plugin/timer/ConstantTimerPlugin.java index 222eafa5..095fa656 100644 --- a/src/main/java/org/bench4q/agent/plugin/timer/ConstantTimerPlugin.java +++ b/src/main/java/org/bench4q/agent/plugin/timer/ConstantTimerPlugin.java @@ -1,7 +1,10 @@ package org.bench4q.agent.plugin.timer; -import org.bench4q.agent.plugin.Behavior; -import org.bench4q.agent.plugin.Plugin; +import java.util.Date; + +import org.bench4q.agent.plugin.BehaviorResult; +import org.bench4q.agent.plugin.annotation.Behavior; +import org.bench4q.agent.plugin.annotation.Plugin; @Plugin("ConstantTimer") public class ConstantTimerPlugin { @@ -10,7 +13,19 @@ public class ConstantTimerPlugin { } @Behavior("Sleep") - public void sleep(int time) { - System.out.println("sleep:" + time); + public BehaviorResult sleep(int time) { + BehaviorResult behaviorResult = new BehaviorResult(); + behaviorResult.setStartDate(new Date(System.currentTimeMillis())); + try { + System.out.println("sleep:" + time); + Thread.sleep(time); + behaviorResult.setEndDate(new Date(System.currentTimeMillis())); + behaviorResult.setSuccess(true); + } catch (Exception e) { + e.printStackTrace(); + behaviorResult.setEndDate(new Date(System.currentTimeMillis())); + behaviorResult.setSuccess(false); + } + return behaviorResult; } } diff --git a/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java b/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java index 51a849d8..572891f4 100644 --- a/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java +++ b/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java @@ -1,10 +1,14 @@ package org.bench4q.agent.scenario; +import java.util.ArrayList; import java.util.HashMap; +import java.util.List; import java.util.Map; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; +import org.bench4q.agent.plugin.BehaviorResult; import org.bench4q.agent.plugin.PluginManager; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @@ -22,27 +26,35 @@ public class ScenarioEngine { this.pluginManager = pluginManager; } - public void runScenario(final Scenario scenario, int threadCount) { - ExecutorService executorService = Executors - .newFixedThreadPool(threadCount); - int i; - Runnable runnable = new Runnable() { - public void run() { - doRunScenario(scenario); + public List runScenario(final Scenario scenario, + int threadCount) { + try { + ExecutorService executorService = Executors + .newFixedThreadPool(threadCount); + int i; + final List ret = new ArrayList(); + Runnable runnable = new Runnable() { + public void run() { + ret.addAll(doRunScenario(scenario)); + } + }; + for (i = 0; i < threadCount; i++) { + executorService.execute(runnable); } - }; - for (i = 0; i < threadCount; i++) { - executorService.execute(runnable); + executorService.shutdown(); + executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.SECONDS); + return ret; + } catch (Exception e) { + e.printStackTrace(); + return null; } - executorService.shutdown(); } - public void runScenario(Scenario scenario) { - this.doRunScenario(scenario); + public List runScenario(Scenario scenario) { + return this.doRunScenario(scenario); } - private void doRunScenario(Scenario scenario) { - System.out.println("Running"); + private List doRunScenario(Scenario scenario) { ScenarioContext scenarioContext = new ScenarioContext(); scenarioContext.setPlugins(new HashMap()); for (UsePlugin usePlugin : scenario.getUsePlugins()) { @@ -57,6 +69,8 @@ public class ScenarioEngine { pluginClass, initParameters); scenarioContext.getPlugins().put(pluginId, plugin); } + + List ret = new ArrayList(); for (UserBehavior userBehavior : scenario.getUserBehaviors()) { Object plugin = scenarioContext.getPlugins().get( userBehavior.getUse()); @@ -66,9 +80,9 @@ public class ScenarioEngine { behaviorParameters .put(parameter.getKey(), parameter.getValue()); } - this.getPluginManager().doBehavior(plugin, behaviorName, - behaviorParameters); + ret.add((BehaviorResult) this.getPluginManager().doBehavior(plugin, + behaviorName, behaviorParameters)); } - System.out.println("Finished"); + return ret; } } From 96be2104c606e60df69ec1ad295cb9239e5e4924 Mon Sep 17 00:00:00 2001 From: Zhen Tang Date: Thu, 27 Jun 2013 18:05:31 +0800 Subject: [PATCH 014/196] test status monitoring added. --- .../org/bench4q/agent/api/TestController.java | 21 ++++++--- .../agent/scenario/ScenarioContext.java | 34 +++++++++++--- .../agent/scenario/ScenarioEngine.java | 46 ++++++++++++------- 3 files changed, 73 insertions(+), 28 deletions(-) diff --git a/src/main/java/org/bench4q/agent/api/TestController.java b/src/main/java/org/bench4q/agent/api/TestController.java index 2ed43393..ca46e761 100644 --- a/src/main/java/org/bench4q/agent/api/TestController.java +++ b/src/main/java/org/bench4q/agent/api/TestController.java @@ -1,10 +1,11 @@ package org.bench4q.agent.api; -import java.util.List; +import java.util.Map; +import java.util.UUID; -import org.bench4q.agent.plugin.BehaviorResult; import org.bench4q.agent.scenario.Parameter; import org.bench4q.agent.scenario.Scenario; +import org.bench4q.agent.scenario.ScenarioContext; import org.bench4q.agent.scenario.ScenarioEngine; import org.bench4q.agent.scenario.UsePlugin; import org.bench4q.agent.scenario.UserBehavior; @@ -28,7 +29,7 @@ public class TestController { this.scenarioEngine = scenarioEngine; } - @RequestMapping(method = RequestMethod.GET) + @RequestMapping(value = "/run", method = RequestMethod.GET) @ResponseBody public String run() { Scenario scenario = new Scenario(); @@ -80,8 +81,16 @@ public class TestController { scenario.getUserBehaviors()[2].getParameters()[0].setKey("time"); scenario.getUserBehaviors()[2].getParameters()[0].setValue("1000"); - List list = this.getScenarioEngine().runScenario( - scenario, 100); - return list.toString(); + this.getScenarioEngine().runScenario(UUID.randomUUID(), scenario, 100); + return "It works!"; + } + + @RequestMapping(value = "/status", method = RequestMethod.GET) + @ResponseBody + public String status() { + Map map = this.getScenarioEngine() + .getRunningTests(); + System.out.println(map.toString()); + return "It works!"; } } diff --git a/src/main/java/org/bench4q/agent/scenario/ScenarioContext.java b/src/main/java/org/bench4q/agent/scenario/ScenarioContext.java index ebfab4b2..bc3fb080 100644 --- a/src/main/java/org/bench4q/agent/scenario/ScenarioContext.java +++ b/src/main/java/org/bench4q/agent/scenario/ScenarioContext.java @@ -1,16 +1,38 @@ package org.bench4q.agent.scenario; -import java.util.Map; +import java.util.List; +import java.util.concurrent.ExecutorService; + +import org.bench4q.agent.plugin.BehaviorResult; public class ScenarioContext { - private Map plugins; + private ExecutorService executorService; + private Scenario scenario; + private List results; - public Map getPlugins() { - return plugins; + public ExecutorService getExecutorService() { + return executorService; } - public void setPlugins(Map plugins) { - this.plugins = plugins; + public void setExecutorService(ExecutorService executorService) { + this.executorService = executorService; } + public Scenario getScenario() { + return scenario; + } + + public void setScenario(Scenario scenario) { + this.scenario = scenario; + } + + public List getResults() { + return results; + } + + public void setResults(List results) { + this.results = results; + } + + } diff --git a/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java b/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java index 572891f4..e90b51d8 100644 --- a/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java +++ b/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java @@ -1,12 +1,13 @@ package org.bench4q.agent.scenario; import java.util.ArrayList; +import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.UUID; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; -import java.util.concurrent.TimeUnit; import org.bench4q.agent.plugin.BehaviorResult; import org.bench4q.agent.plugin.PluginManager; @@ -16,6 +17,11 @@ import org.springframework.stereotype.Component; @Component public class ScenarioEngine { private PluginManager pluginManager; + private Map runningTests; + + public ScenarioEngine() { + this.setRunningTests(new HashMap()); + } private PluginManager getPluginManager() { return pluginManager; @@ -26,13 +32,30 @@ public class ScenarioEngine { this.pluginManager = pluginManager; } - public List runScenario(final Scenario scenario, - int threadCount) { + public Map getRunningTests() { + return runningTests; + } + + private void setRunningTests(Map runningTests) { + this.runningTests = runningTests; + } + + public ScenarioContext getState(UUID uuid) { + return this.getRunningTests().get(uuid); + } + + public void runScenario(UUID uuid, final Scenario scenario, int threadCount) { try { + ScenarioContext scenarioContext = new ScenarioContext(); + scenarioContext.setScenario(scenario); ExecutorService executorService = Executors .newFixedThreadPool(threadCount); + scenarioContext.setExecutorService(executorService); int i; - final List ret = new ArrayList(); + final List ret = Collections + .synchronizedList(new ArrayList()); + scenarioContext.setResults(ret); + this.getRunningTests().put(uuid, scenarioContext); Runnable runnable = new Runnable() { public void run() { ret.addAll(doRunScenario(scenario)); @@ -42,21 +65,13 @@ public class ScenarioEngine { executorService.execute(runnable); } executorService.shutdown(); - executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.SECONDS); - return ret; } catch (Exception e) { e.printStackTrace(); - return null; } } - public List runScenario(Scenario scenario) { - return this.doRunScenario(scenario); - } - private List doRunScenario(Scenario scenario) { - ScenarioContext scenarioContext = new ScenarioContext(); - scenarioContext.setPlugins(new HashMap()); + Map plugins = new HashMap(); for (UsePlugin usePlugin : scenario.getUsePlugins()) { String pluginId = usePlugin.getId(); Class pluginClass = this.getPluginManager().getPlugins() @@ -67,13 +82,12 @@ public class ScenarioEngine { } Object plugin = this.getPluginManager().initializePlugin( pluginClass, initParameters); - scenarioContext.getPlugins().put(pluginId, plugin); + plugins.put(pluginId, plugin); } List ret = new ArrayList(); for (UserBehavior userBehavior : scenario.getUserBehaviors()) { - Object plugin = scenarioContext.getPlugins().get( - userBehavior.getUse()); + Object plugin = plugins.get(userBehavior.getUse()); String behaviorName = userBehavior.getName(); Map behaviorParameters = new HashMap(); for (Parameter parameter : userBehavior.getParameters()) { From d0a14e6ea4ae133af1f2e8c782ae0ac7dc4befe9 Mon Sep 17 00:00:00 2001 From: Zhen Tang Date: Fri, 28 Jun 2013 15:24:38 +0800 Subject: [PATCH 015/196] Constant timer and Http plugin added. --- .../org/bench4q/agent/api/HomeController.java | 2 +- .../bench4q/agent/api/PluginController.java | 4 +- .../org/bench4q/agent/api/TestController.java | 17 ++--- .../plugin/{annotation => }/Behavior.java | 2 +- .../plugin/{metadata => }/BehaviorInfo.java | 2 +- .../agent/plugin/{annotation => }/Plugin.java | 2 +- .../plugin/{metadata => }/PluginInfo.java | 2 +- .../bench4q/agent/plugin/PluginManager.java | 4 -- .../bench4q/agent/plugin/http/HttpPlugin.java | 71 ++++++++++++++----- .../plugin/timer/ConstantTimerPlugin.java | 9 ++- 10 files changed, 72 insertions(+), 43 deletions(-) rename src/main/java/org/bench4q/agent/plugin/{annotation => }/Behavior.java (82%) rename src/main/java/org/bench4q/agent/plugin/{metadata => }/BehaviorInfo.java (83%) rename src/main/java/org/bench4q/agent/plugin/{annotation => }/Plugin.java (82%) rename src/main/java/org/bench4q/agent/plugin/{metadata => }/PluginInfo.java (87%) diff --git a/src/main/java/org/bench4q/agent/api/HomeController.java b/src/main/java/org/bench4q/agent/api/HomeController.java index 8f5c131b..46a0f120 100644 --- a/src/main/java/org/bench4q/agent/api/HomeController.java +++ b/src/main/java/org/bench4q/agent/api/HomeController.java @@ -9,7 +9,7 @@ import org.springframework.web.bind.annotation.ResponseBody; @RequestMapping("/") public class HomeController { - @RequestMapping(method = RequestMethod.GET) + @RequestMapping(method = { RequestMethod.GET, RequestMethod.POST }) @ResponseBody public String index() { diff --git a/src/main/java/org/bench4q/agent/api/PluginController.java b/src/main/java/org/bench4q/agent/api/PluginController.java index 620e1b1b..a701b443 100644 --- a/src/main/java/org/bench4q/agent/api/PluginController.java +++ b/src/main/java/org/bench4q/agent/api/PluginController.java @@ -6,9 +6,9 @@ import java.util.List; import org.bench4q.agent.api.model.BehaviorInfoModel; import org.bench4q.agent.api.model.PluginInfoListModel; import org.bench4q.agent.api.model.PluginInfoModel; +import org.bench4q.agent.plugin.BehaviorInfo; +import org.bench4q.agent.plugin.PluginInfo; import org.bench4q.agent.plugin.PluginManager; -import org.bench4q.agent.plugin.metadata.BehaviorInfo; -import org.bench4q.agent.plugin.metadata.PluginInfo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; diff --git a/src/main/java/org/bench4q/agent/api/TestController.java b/src/main/java/org/bench4q/agent/api/TestController.java index ca46e761..1cb78ca2 100644 --- a/src/main/java/org/bench4q/agent/api/TestController.java +++ b/src/main/java/org/bench4q/agent/api/TestController.java @@ -49,29 +49,24 @@ public class TestController { scenario.getUserBehaviors()[0] = new UserBehavior(); scenario.getUserBehaviors()[0].setUse("http"); scenario.getUserBehaviors()[0].setName("Get"); - scenario.getUserBehaviors()[0].setParameters(new Parameter[2]); + scenario.getUserBehaviors()[0].setParameters(new Parameter[1]); scenario.getUserBehaviors()[0].getParameters()[0] = new Parameter(); scenario.getUserBehaviors()[0].getParameters()[0].setKey("url"); - scenario.getUserBehaviors()[0].getParameters()[0].setValue("localhost"); - scenario.getUserBehaviors()[0].getParameters()[1] = new Parameter(); - scenario.getUserBehaviors()[0].getParameters()[1].setKey("content"); - scenario.getUserBehaviors()[0].getParameters()[1] - .setValue("Hello,world!"); + scenario.getUserBehaviors()[0].getParameters()[0] + .setValue("http://www.baidu.com"); scenario.getUserBehaviors()[1] = new UserBehavior(); scenario.getUserBehaviors()[1].setUse("http"); scenario.getUserBehaviors()[1].setName("Post"); - scenario.getUserBehaviors()[1].setParameters(new Parameter[3]); + scenario.getUserBehaviors()[1].setParameters(new Parameter[2]); scenario.getUserBehaviors()[1].getParameters()[0] = new Parameter(); scenario.getUserBehaviors()[1].getParameters()[0].setKey("url"); - scenario.getUserBehaviors()[1].getParameters()[0].setValue("localhost"); + scenario.getUserBehaviors()[1].getParameters()[0] + .setValue("http://localhost:6565"); scenario.getUserBehaviors()[1].getParameters()[1] = new Parameter(); scenario.getUserBehaviors()[1].getParameters()[1].setKey("content"); scenario.getUserBehaviors()[1].getParameters()[1] .setValue("Hello,world!"); - scenario.getUserBehaviors()[1].getParameters()[2] = new Parameter(); - scenario.getUserBehaviors()[1].getParameters()[2].setKey("code"); - scenario.getUserBehaviors()[1].getParameters()[2].setValue("404"); scenario.getUserBehaviors()[2] = new UserBehavior(); scenario.getUserBehaviors()[2].setUse("timer"); diff --git a/src/main/java/org/bench4q/agent/plugin/annotation/Behavior.java b/src/main/java/org/bench4q/agent/plugin/Behavior.java similarity index 82% rename from src/main/java/org/bench4q/agent/plugin/annotation/Behavior.java rename to src/main/java/org/bench4q/agent/plugin/Behavior.java index 6e7d4e60..3fab5f99 100644 --- a/src/main/java/org/bench4q/agent/plugin/annotation/Behavior.java +++ b/src/main/java/org/bench4q/agent/plugin/Behavior.java @@ -1,4 +1,4 @@ -package org.bench4q.agent.plugin.annotation; +package org.bench4q.agent.plugin; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; diff --git a/src/main/java/org/bench4q/agent/plugin/metadata/BehaviorInfo.java b/src/main/java/org/bench4q/agent/plugin/BehaviorInfo.java similarity index 83% rename from src/main/java/org/bench4q/agent/plugin/metadata/BehaviorInfo.java rename to src/main/java/org/bench4q/agent/plugin/BehaviorInfo.java index 547ff43f..96317ac3 100644 --- a/src/main/java/org/bench4q/agent/plugin/metadata/BehaviorInfo.java +++ b/src/main/java/org/bench4q/agent/plugin/BehaviorInfo.java @@ -1,4 +1,4 @@ -package org.bench4q.agent.plugin.metadata; +package org.bench4q.agent.plugin; public class BehaviorInfo { private String name; diff --git a/src/main/java/org/bench4q/agent/plugin/annotation/Plugin.java b/src/main/java/org/bench4q/agent/plugin/Plugin.java similarity index 82% rename from src/main/java/org/bench4q/agent/plugin/annotation/Plugin.java rename to src/main/java/org/bench4q/agent/plugin/Plugin.java index f35ca906..7841b547 100644 --- a/src/main/java/org/bench4q/agent/plugin/annotation/Plugin.java +++ b/src/main/java/org/bench4q/agent/plugin/Plugin.java @@ -1,4 +1,4 @@ -package org.bench4q.agent.plugin.annotation; +package org.bench4q.agent.plugin; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; diff --git a/src/main/java/org/bench4q/agent/plugin/metadata/PluginInfo.java b/src/main/java/org/bench4q/agent/plugin/PluginInfo.java similarity index 87% rename from src/main/java/org/bench4q/agent/plugin/metadata/PluginInfo.java rename to src/main/java/org/bench4q/agent/plugin/PluginInfo.java index 8742fb59..d3c8aa39 100644 --- a/src/main/java/org/bench4q/agent/plugin/metadata/PluginInfo.java +++ b/src/main/java/org/bench4q/agent/plugin/PluginInfo.java @@ -1,4 +1,4 @@ -package org.bench4q.agent.plugin.metadata; +package org.bench4q.agent.plugin; public class PluginInfo { private String name; diff --git a/src/main/java/org/bench4q/agent/plugin/PluginManager.java b/src/main/java/org/bench4q/agent/plugin/PluginManager.java index 28df9235..ce71b093 100644 --- a/src/main/java/org/bench4q/agent/plugin/PluginManager.java +++ b/src/main/java/org/bench4q/agent/plugin/PluginManager.java @@ -16,10 +16,6 @@ import javassist.bytecode.CodeAttribute; import javassist.bytecode.LocalVariableAttribute; import javassist.bytecode.MethodInfo; -import org.bench4q.agent.plugin.annotation.Behavior; -import org.bench4q.agent.plugin.annotation.Plugin; -import org.bench4q.agent.plugin.metadata.BehaviorInfo; -import org.bench4q.agent.plugin.metadata.PluginInfo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; diff --git a/src/main/java/org/bench4q/agent/plugin/http/HttpPlugin.java b/src/main/java/org/bench4q/agent/plugin/http/HttpPlugin.java index 96b00fe5..6e10b93f 100644 --- a/src/main/java/org/bench4q/agent/plugin/http/HttpPlugin.java +++ b/src/main/java/org/bench4q/agent/plugin/http/HttpPlugin.java @@ -1,45 +1,84 @@ package org.bench4q.agent.plugin.http; +import java.io.BufferedReader; +import java.io.InputStreamReader; +import java.io.OutputStreamWriter; +import java.net.HttpURLConnection; +import java.net.URL; import java.util.Date; +import org.bench4q.agent.plugin.Behavior; import org.bench4q.agent.plugin.BehaviorResult; -import org.bench4q.agent.plugin.annotation.Behavior; -import org.bench4q.agent.plugin.annotation.Plugin; +import org.bench4q.agent.plugin.Plugin; @Plugin("Http") public class HttpPlugin { public HttpPlugin() { - System.out.println("init http plugin"); + } @Behavior("Get") - public BehaviorResult get(String url, String content) { + public BehaviorResult get(String url) { BehaviorResult behaviorResult = new BehaviorResult(); behaviorResult.setStartDate(new Date(System.currentTimeMillis())); try { - System.out.println("get"); - System.out.println("url:" + url); - System.out.println("content:" + content); - behaviorResult.setEndDate(new Date(System.currentTimeMillis())); + URL target = new URL(url); + HttpURLConnection httpURLConnection = (HttpURLConnection) target + .openConnection(); + httpURLConnection.setDoOutput(false); + httpURLConnection.setDoInput(true); + httpURLConnection.setUseCaches(false); + httpURLConnection.setRequestMethod("GET"); + BufferedReader bufferedReader = new BufferedReader( + new InputStreamReader(httpURLConnection.getInputStream())); + int temp = -1; + StringBuffer stringBuffer = new StringBuffer(); + while ((temp = bufferedReader.read()) != -1) { + stringBuffer.append((char) temp); + } + bufferedReader.close(); behaviorResult.setSuccess(true); } catch (Exception e) { e.printStackTrace(); + behaviorResult.setSuccess(false); + } finally { behaviorResult.setEndDate(new Date(System.currentTimeMillis())); - behaviorResult.setSuccess(true); } return behaviorResult; } @Behavior("Post") - public BehaviorResult post(String url, String content, int code) { + public BehaviorResult post(String url, String content) { BehaviorResult behaviorResult = new BehaviorResult(); behaviorResult.setStartDate(new Date(System.currentTimeMillis())); - System.out.println("get"); - System.out.println("url:" + url); - System.out.println("content:" + content); - System.out.println("code:" + code); - behaviorResult.setEndDate(new Date(System.currentTimeMillis())); - behaviorResult.setSuccess(true); + try { + URL target = new URL(url); + HttpURLConnection httpURLConnection = (HttpURLConnection) target + .openConnection(); + httpURLConnection.setDoOutput(true); + httpURLConnection.setDoInput(true); + httpURLConnection.setUseCaches(false); + httpURLConnection.setRequestMethod("POST"); + OutputStreamWriter outputStreamWriter = new OutputStreamWriter( + httpURLConnection.getOutputStream()); + outputStreamWriter.write(content); + outputStreamWriter.flush(); + outputStreamWriter.close(); + BufferedReader bufferedReader = new BufferedReader( + new InputStreamReader(httpURLConnection.getInputStream())); + int temp = -1; + StringBuffer stringBuffer = new StringBuffer(); + while ((temp = bufferedReader.read()) != -1) { + stringBuffer.append((char) temp); + } + bufferedReader.close(); + behaviorResult.setSuccess(true); + } catch (Exception e) { + e.printStackTrace(); + behaviorResult.setSuccess(false); + } finally { + behaviorResult.setEndDate(new Date(System.currentTimeMillis())); + } return behaviorResult; } } diff --git a/src/main/java/org/bench4q/agent/plugin/timer/ConstantTimerPlugin.java b/src/main/java/org/bench4q/agent/plugin/timer/ConstantTimerPlugin.java index 095fa656..989d39bb 100644 --- a/src/main/java/org/bench4q/agent/plugin/timer/ConstantTimerPlugin.java +++ b/src/main/java/org/bench4q/agent/plugin/timer/ConstantTimerPlugin.java @@ -2,9 +2,9 @@ package org.bench4q.agent.plugin.timer; import java.util.Date; +import org.bench4q.agent.plugin.Behavior; import org.bench4q.agent.plugin.BehaviorResult; -import org.bench4q.agent.plugin.annotation.Behavior; -import org.bench4q.agent.plugin.annotation.Plugin; +import org.bench4q.agent.plugin.Plugin; @Plugin("ConstantTimer") public class ConstantTimerPlugin { @@ -17,14 +17,13 @@ public class ConstantTimerPlugin { BehaviorResult behaviorResult = new BehaviorResult(); behaviorResult.setStartDate(new Date(System.currentTimeMillis())); try { - System.out.println("sleep:" + time); Thread.sleep(time); - behaviorResult.setEndDate(new Date(System.currentTimeMillis())); behaviorResult.setSuccess(true); } catch (Exception e) { e.printStackTrace(); - behaviorResult.setEndDate(new Date(System.currentTimeMillis())); behaviorResult.setSuccess(false); + } finally { + behaviorResult.setEndDate(new Date(System.currentTimeMillis())); } return behaviorResult; } From 92fb5fb76f914a9e9f2bffc1d47924a8bdc93e57 Mon Sep 17 00:00:00 2001 From: Zhen Tang Date: Fri, 28 Jun 2013 16:33:15 +0800 Subject: [PATCH 016/196] Test status service added. --- .../org/bench4q/agent/api/TestController.java | 119 +++++++++++++++--- .../agent/api/model/TestBriefStatusModel.java | 81 ++++++++++++ .../agent/api/model/TestDetailModel.java | 80 ++++++++++++ .../api/model/TestDetailStatusModel.java | 94 ++++++++++++++ .../bench4q/agent/plugin/BehaviorResult.java | 36 ++++++ .../bench4q/agent/plugin/http/HttpPlugin.java | 26 ++-- .../plugin/timer/ConstantTimerPlugin.java | 14 +-- .../agent/scenario/ScenarioContext.java | 22 +++- .../agent/scenario/ScenarioEngine.java | 26 +++- 9 files changed, 442 insertions(+), 56 deletions(-) create mode 100644 src/main/java/org/bench4q/agent/api/model/TestBriefStatusModel.java create mode 100644 src/main/java/org/bench4q/agent/api/model/TestDetailModel.java create mode 100644 src/main/java/org/bench4q/agent/api/model/TestDetailStatusModel.java diff --git a/src/main/java/org/bench4q/agent/api/TestController.java b/src/main/java/org/bench4q/agent/api/TestController.java index 1cb78ca2..b81ac049 100644 --- a/src/main/java/org/bench4q/agent/api/TestController.java +++ b/src/main/java/org/bench4q/agent/api/TestController.java @@ -1,8 +1,13 @@ package org.bench4q.agent.api; -import java.util.Map; +import java.util.ArrayList; +import java.util.List; import java.util.UUID; +import org.bench4q.agent.api.model.TestBriefStatusModel; +import org.bench4q.agent.api.model.TestDetailModel; +import org.bench4q.agent.api.model.TestDetailStatusModel; +import org.bench4q.agent.plugin.BehaviorResult; import org.bench4q.agent.scenario.Parameter; import org.bench4q.agent.scenario.Scenario; import org.bench4q.agent.scenario.ScenarioContext; @@ -11,6 +16,7 @@ import org.bench4q.agent.scenario.UsePlugin; import org.bench4q.agent.scenario.UserBehavior; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; @@ -31,7 +37,7 @@ public class TestController { @RequestMapping(value = "/run", method = RequestMethod.GET) @ResponseBody - public String run() { + public UUID run() { Scenario scenario = new Scenario(); scenario.setUsePlugins(new UsePlugin[2]); @@ -53,7 +59,15 @@ public class TestController { scenario.getUserBehaviors()[0].getParameters()[0] = new Parameter(); scenario.getUserBehaviors()[0].getParameters()[0].setKey("url"); scenario.getUserBehaviors()[0].getParameters()[0] - .setValue("http://www.baidu.com"); + .setValue("http://localhost:6565"); + + scenario.getUserBehaviors()[2] = new UserBehavior(); + scenario.getUserBehaviors()[2].setUse("timer"); + scenario.getUserBehaviors()[2].setName("Sleep"); + scenario.getUserBehaviors()[2].setParameters(new Parameter[1]); + scenario.getUserBehaviors()[2].getParameters()[0] = new Parameter(); + scenario.getUserBehaviors()[2].getParameters()[0].setKey("time"); + scenario.getUserBehaviors()[2].getParameters()[0].setValue("1000"); scenario.getUserBehaviors()[1] = new UserBehavior(); scenario.getUserBehaviors()[1].setUse("http"); @@ -68,24 +82,91 @@ public class TestController { scenario.getUserBehaviors()[1].getParameters()[1] .setValue("Hello,world!"); - scenario.getUserBehaviors()[2] = new UserBehavior(); - scenario.getUserBehaviors()[2].setUse("timer"); - scenario.getUserBehaviors()[2].setName("Sleep"); - scenario.getUserBehaviors()[2].setParameters(new Parameter[1]); - scenario.getUserBehaviors()[2].getParameters()[0] = new Parameter(); - scenario.getUserBehaviors()[2].getParameters()[0].setKey("time"); - scenario.getUserBehaviors()[2].getParameters()[0].setValue("1000"); - - this.getScenarioEngine().runScenario(UUID.randomUUID(), scenario, 100); - return "It works!"; + UUID uuid = UUID.randomUUID(); + this.getScenarioEngine().runScenario(uuid, scenario, 200); + return uuid; } - @RequestMapping(value = "/status", method = RequestMethod.GET) + @RequestMapping(value = "/detail/{uuid}", method = RequestMethod.GET) @ResponseBody - public String status() { - Map map = this.getScenarioEngine() - .getRunningTests(); - System.out.println(map.toString()); - return "It works!"; + public TestDetailStatusModel detail(@PathVariable UUID uuid) { + ScenarioContext scenarioContext = this.getScenarioEngine() + .getRunningTests().get(uuid); + TestDetailStatusModel testStatusModel = new TestDetailStatusModel(); + testStatusModel.setStartDate(scenarioContext.getStartDate()); + testStatusModel.setTestDetailModels(new ArrayList()); + int failCount = 0; + int successCount = 0; + List behaviorResults = scenarioContext.getResults(); + long maxDate = 0; + long totalResponseTime = 0; + for (BehaviorResult behaviorResult : behaviorResults) { + TestDetailModel testDetailModel = new TestDetailModel(); + testDetailModel.setBehaviorName(behaviorResult.getBehaviorName()); + testDetailModel.setEndDate(behaviorResult.getEndDate()); + testDetailModel.setPluginId(behaviorResult.getPluginId()); + testDetailModel.setPluginName(behaviorResult.getPluginName()); + testDetailModel.setResponseTime(behaviorResult.getResponseTime()); + testDetailModel.setStartDate(behaviorResult.getStartDate()); + testDetailModel.setSuccess(behaviorResult.isSuccess()); + testStatusModel.getTestDetailModels().add(testDetailModel); + if (testDetailModel.getEndDate().getTime() > maxDate) { + maxDate = testDetailModel.getEndDate().getTime(); + } + if (testDetailModel.isSuccess()) { + successCount++; + } else { + failCount++; + } + if (!behaviorResult.getPluginName().contains("Timer")) { + totalResponseTime += behaviorResult.getResponseTime(); + } + } + testStatusModel.setAverageResponseTime((totalResponseTime + 0.0) + / behaviorResults.size()); + testStatusModel.setElapsedTime(maxDate + - testStatusModel.getStartDate().getTime()); + testStatusModel.setFailCount(failCount); + testStatusModel.setSuccessCount(successCount); + testStatusModel.setFinishedCount(testStatusModel.getTestDetailModels() + .size()); + testStatusModel.setTotalCount(scenarioContext.getTotalCount()); + return testStatusModel; + } + + @RequestMapping(value = "/brief/{uuid}", method = RequestMethod.GET) + @ResponseBody + public TestBriefStatusModel brief(@PathVariable UUID uuid) { + ScenarioContext scenarioContext = this.getScenarioEngine() + .getRunningTests().get(uuid); + TestBriefStatusModel testBriefStatusModel = new TestBriefStatusModel(); + testBriefStatusModel.setStartDate(scenarioContext.getStartDate()); + int failCount = 0; + int successCount = 0; + long totalResponseTime = 0; + List behaviorResults = scenarioContext.getResults(); + long maxDate = 0; + for (BehaviorResult behaviorResult : behaviorResults) { + if (behaviorResult.getEndDate().getTime() > maxDate) { + maxDate = behaviorResult.getEndDate().getTime(); + } + if (behaviorResult.isSuccess()) { + successCount++; + } else { + failCount++; + } + if (!behaviorResult.getPluginName().contains("Timer")) { + totalResponseTime += behaviorResult.getResponseTime(); + } + } + testBriefStatusModel.setAverageResponseTime((totalResponseTime + 0.0) + / behaviorResults.size()); + testBriefStatusModel.setElapsedTime(maxDate + - testBriefStatusModel.getStartDate().getTime()); + testBriefStatusModel.setFailCount(failCount); + testBriefStatusModel.setSuccessCount(successCount); + testBriefStatusModel.setFinishedCount(behaviorResults.size()); + testBriefStatusModel.setTotalCount(scenarioContext.getTotalCount()); + return testBriefStatusModel; } } diff --git a/src/main/java/org/bench4q/agent/api/model/TestBriefStatusModel.java b/src/main/java/org/bench4q/agent/api/model/TestBriefStatusModel.java new file mode 100644 index 00000000..e6dd9467 --- /dev/null +++ b/src/main/java/org/bench4q/agent/api/model/TestBriefStatusModel.java @@ -0,0 +1,81 @@ +package org.bench4q.agent.api.model; + +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 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; + } + +} diff --git a/src/main/java/org/bench4q/agent/api/model/TestDetailModel.java b/src/main/java/org/bench4q/agent/api/model/TestDetailModel.java new file mode 100644 index 00000000..07efb0cc --- /dev/null +++ b/src/main/java/org/bench4q/agent/api/model/TestDetailModel.java @@ -0,0 +1,80 @@ +package org.bench4q.agent.api.model; + +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; + } +} diff --git a/src/main/java/org/bench4q/agent/api/model/TestDetailStatusModel.java b/src/main/java/org/bench4q/agent/api/model/TestDetailStatusModel.java new file mode 100644 index 00000000..a94f2225 --- /dev/null +++ b/src/main/java/org/bench4q/agent/api/model/TestDetailStatusModel.java @@ -0,0 +1,94 @@ +package org.bench4q.agent.api.model; + +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 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 getTestDetailModels() { + return testDetailModels; + } + + public void setTestDetailModels(List testDetailModels) { + this.testDetailModels = testDetailModels; + } + +} diff --git a/src/main/java/org/bench4q/agent/plugin/BehaviorResult.java b/src/main/java/org/bench4q/agent/plugin/BehaviorResult.java index 1376643e..9676d8c4 100644 --- a/src/main/java/org/bench4q/agent/plugin/BehaviorResult.java +++ b/src/main/java/org/bench4q/agent/plugin/BehaviorResult.java @@ -3,10 +3,38 @@ package org.bench4q.agent.plugin; import java.util.Date; public class BehaviorResult { + private String pluginId; + private String pluginName; + private String behaviorName; private Date startDate; private Date endDate; + private long responseTime; private boolean success; + public String getPluginId() { + return pluginId; + } + + public void setPluginId(String pluginId) { + this.pluginId = pluginId; + } + + public String getPluginName() { + return pluginName; + } + + public void setPluginName(String pluginName) { + this.pluginName = pluginName; + } + + public String getBehaviorName() { + return behaviorName; + } + + public void setBehaviorName(String behaviorName) { + this.behaviorName = behaviorName; + } + public Date getStartDate() { return startDate; } @@ -23,6 +51,14 @@ public class BehaviorResult { this.endDate = endDate; } + public long getResponseTime() { + return responseTime; + } + + public void setResponseTime(long responseTime) { + this.responseTime = responseTime; + } + public boolean isSuccess() { return success; } diff --git a/src/main/java/org/bench4q/agent/plugin/http/HttpPlugin.java b/src/main/java/org/bench4q/agent/plugin/http/HttpPlugin.java index 6e10b93f..f50c861d 100644 --- a/src/main/java/org/bench4q/agent/plugin/http/HttpPlugin.java +++ b/src/main/java/org/bench4q/agent/plugin/http/HttpPlugin.java @@ -5,22 +5,18 @@ import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.HttpURLConnection; import java.net.URL; -import java.util.Date; - import org.bench4q.agent.plugin.Behavior; -import org.bench4q.agent.plugin.BehaviorResult; import org.bench4q.agent.plugin.Plugin; @Plugin("Http") public class HttpPlugin { + public HttpPlugin() { } @Behavior("Get") - public BehaviorResult get(String url) { - BehaviorResult behaviorResult = new BehaviorResult(); - behaviorResult.setStartDate(new Date(System.currentTimeMillis())); + public boolean get(String url) { try { URL target = new URL(url); HttpURLConnection httpURLConnection = (HttpURLConnection) target @@ -37,20 +33,15 @@ public class HttpPlugin { stringBuffer.append((char) temp); } bufferedReader.close(); - behaviorResult.setSuccess(true); + return true; } catch (Exception e) { e.printStackTrace(); - behaviorResult.setSuccess(false); - } finally { - behaviorResult.setEndDate(new Date(System.currentTimeMillis())); + return false; } - return behaviorResult; } @Behavior("Post") - public BehaviorResult post(String url, String content) { - BehaviorResult behaviorResult = new BehaviorResult(); - behaviorResult.setStartDate(new Date(System.currentTimeMillis())); + public boolean post(String url, String content) { try { URL target = new URL(url); HttpURLConnection httpURLConnection = (HttpURLConnection) target @@ -72,13 +63,10 @@ public class HttpPlugin { stringBuffer.append((char) temp); } bufferedReader.close(); - behaviorResult.setSuccess(true); + return true; } catch (Exception e) { e.printStackTrace(); - behaviorResult.setSuccess(false); - } finally { - behaviorResult.setEndDate(new Date(System.currentTimeMillis())); + return false; } - return behaviorResult; } } diff --git a/src/main/java/org/bench4q/agent/plugin/timer/ConstantTimerPlugin.java b/src/main/java/org/bench4q/agent/plugin/timer/ConstantTimerPlugin.java index 989d39bb..f0cd8dfe 100644 --- a/src/main/java/org/bench4q/agent/plugin/timer/ConstantTimerPlugin.java +++ b/src/main/java/org/bench4q/agent/plugin/timer/ConstantTimerPlugin.java @@ -1,9 +1,6 @@ package org.bench4q.agent.plugin.timer; -import java.util.Date; - import org.bench4q.agent.plugin.Behavior; -import org.bench4q.agent.plugin.BehaviorResult; import org.bench4q.agent.plugin.Plugin; @Plugin("ConstantTimer") @@ -13,18 +10,13 @@ public class ConstantTimerPlugin { } @Behavior("Sleep") - public BehaviorResult sleep(int time) { - BehaviorResult behaviorResult = new BehaviorResult(); - behaviorResult.setStartDate(new Date(System.currentTimeMillis())); + public boolean sleep(int time) { try { Thread.sleep(time); - behaviorResult.setSuccess(true); + return true; } catch (Exception e) { e.printStackTrace(); - behaviorResult.setSuccess(false); - } finally { - behaviorResult.setEndDate(new Date(System.currentTimeMillis())); + return false; } - return behaviorResult; } } diff --git a/src/main/java/org/bench4q/agent/scenario/ScenarioContext.java b/src/main/java/org/bench4q/agent/scenario/ScenarioContext.java index bc3fb080..08ec51c9 100644 --- a/src/main/java/org/bench4q/agent/scenario/ScenarioContext.java +++ b/src/main/java/org/bench4q/agent/scenario/ScenarioContext.java @@ -1,15 +1,34 @@ package org.bench4q.agent.scenario; +import java.util.Date; import java.util.List; import java.util.concurrent.ExecutorService; import org.bench4q.agent.plugin.BehaviorResult; public class ScenarioContext { + private int totalCount; + private Date startDate; private ExecutorService executorService; private Scenario scenario; private List results; + public int getTotalCount() { + return totalCount; + } + + public void setTotalCount(int totalCount) { + this.totalCount = totalCount; + } + + public Date getStartDate() { + return startDate; + } + + public void setStartDate(Date startDate) { + this.startDate = startDate; + } + public ExecutorService getExecutorService() { return executorService; } @@ -33,6 +52,5 @@ public class ScenarioContext { public void setResults(List results) { this.results = results; } - - + } diff --git a/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java b/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java index e90b51d8..bac15e19 100644 --- a/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java +++ b/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java @@ -2,6 +2,7 @@ package org.bench4q.agent.scenario; import java.util.ArrayList; import java.util.Collections; +import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -10,6 +11,7 @@ import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import org.bench4q.agent.plugin.BehaviorResult; +import org.bench4q.agent.plugin.Plugin; import org.bench4q.agent.plugin.PluginManager; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @@ -44,12 +46,15 @@ public class ScenarioEngine { return this.getRunningTests().get(uuid); } - public void runScenario(UUID uuid, final Scenario scenario, int threadCount) { + public void runScenario(UUID uuid, final Scenario scenario, int totalCount) { try { ScenarioContext scenarioContext = new ScenarioContext(); scenarioContext.setScenario(scenario); + scenarioContext.setTotalCount(totalCount + * scenario.getUserBehaviors().length); + scenarioContext.setStartDate(new Date(System.currentTimeMillis())); ExecutorService executorService = Executors - .newFixedThreadPool(threadCount); + .newFixedThreadPool(totalCount); scenarioContext.setExecutorService(executorService); int i; final List ret = Collections @@ -61,7 +66,7 @@ public class ScenarioEngine { ret.addAll(doRunScenario(scenario)); } }; - for (i = 0; i < threadCount; i++) { + for (i = 0; i < totalCount; i++) { executorService.execute(runnable); } executorService.shutdown(); @@ -94,8 +99,19 @@ public class ScenarioEngine { behaviorParameters .put(parameter.getKey(), parameter.getValue()); } - ret.add((BehaviorResult) this.getPluginManager().doBehavior(plugin, - behaviorName, behaviorParameters)); + BehaviorResult result = new BehaviorResult(); + result.setStartDate(new Date(System.currentTimeMillis())); + boolean success = (Boolean) this.getPluginManager().doBehavior( + plugin, behaviorName, behaviorParameters); + result.setEndDate(new Date(System.currentTimeMillis())); + result.setSuccess(success); + result.setResponseTime(result.getEndDate().getTime() + - result.getStartDate().getTime()); + result.setBehaviorName(behaviorName); + result.setPluginId(userBehavior.getUse()); + result.setPluginName(plugin.getClass().getAnnotation(Plugin.class) + .value()); + ret.add(result); } return ret; } From cc8bc43f27208086d1c63395842ef5c9700bf460 Mon Sep 17 00:00:00 2001 From: Zhen Tang Date: Fri, 28 Jun 2013 17:59:38 +0800 Subject: [PATCH 017/196] Run scenario service added. --- .../org/bench4q/agent/api/TestController.java | 115 ++++++++++-------- .../agent/api/model/ParameterModel.java | 29 +++++ .../agent/api/model/RunScenarioModel.java | 43 +++++++ .../api/model/RunScenarioResultModel.java | 21 ++++ .../agent/api/model/UsePluginModel.java | 43 +++++++ .../agent/api/model/UserBehaviorModel.java | 42 +++++++ .../org/bench4q/agent/scenario/Parameter.java | 6 - .../org/bench4q/agent/scenario/Scenario.java | 9 -- .../agent/scenario/ScenarioEngine.java | 4 +- .../org/bench4q/agent/scenario/UsePlugin.java | 9 -- .../bench4q/agent/scenario/UserBehavior.java | 9 -- .../bench4q/agent/test/RunScenarioTest.java | 107 ++++++++++++++++ 12 files changed, 349 insertions(+), 88 deletions(-) create mode 100644 src/main/java/org/bench4q/agent/api/model/ParameterModel.java create mode 100644 src/main/java/org/bench4q/agent/api/model/RunScenarioModel.java create mode 100644 src/main/java/org/bench4q/agent/api/model/RunScenarioResultModel.java create mode 100644 src/main/java/org/bench4q/agent/api/model/UsePluginModel.java create mode 100644 src/main/java/org/bench4q/agent/api/model/UserBehaviorModel.java create mode 100644 src/test/java/org/bench4q/agent/test/RunScenarioTest.java diff --git a/src/main/java/org/bench4q/agent/api/TestController.java b/src/main/java/org/bench4q/agent/api/TestController.java index b81ac049..57a4d27a 100644 --- a/src/main/java/org/bench4q/agent/api/TestController.java +++ b/src/main/java/org/bench4q/agent/api/TestController.java @@ -4,9 +4,14 @@ import java.util.ArrayList; import java.util.List; import java.util.UUID; +import org.bench4q.agent.api.model.ParameterModel; +import org.bench4q.agent.api.model.RunScenarioModel; +import org.bench4q.agent.api.model.RunScenarioResultModel; import org.bench4q.agent.api.model.TestBriefStatusModel; import org.bench4q.agent.api.model.TestDetailModel; import org.bench4q.agent.api.model.TestDetailStatusModel; +import org.bench4q.agent.api.model.UsePluginModel; +import org.bench4q.agent.api.model.UserBehaviorModel; import org.bench4q.agent.plugin.BehaviorResult; import org.bench4q.agent.scenario.Parameter; import org.bench4q.agent.scenario.Scenario; @@ -17,6 +22,7 @@ import org.bench4q.agent.scenario.UserBehavior; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; @@ -35,63 +41,66 @@ public class TestController { this.scenarioEngine = scenarioEngine; } - @RequestMapping(value = "/run", method = RequestMethod.GET) + @RequestMapping(value = "/run", method = RequestMethod.POST) @ResponseBody - public UUID run() { + public RunScenarioResultModel run( + @RequestBody RunScenarioModel runScenarioModel) { Scenario scenario = new Scenario(); + scenario.setUsePlugins(new UsePlugin[runScenarioModel.getUsePlugins() + .size()]); + scenario.setUserBehaviors(new UserBehavior[runScenarioModel + .getUserBehaviors().size()]); + int i = 0; + int j = 0; + for (i = 0; i < runScenarioModel.getUsePlugins().size(); i++) { + UsePluginModel usePluginModel = runScenarioModel.getUsePlugins() + .get(i); + UsePlugin usePlugin = new UsePlugin(); + usePlugin.setId(usePluginModel.getId()); + usePlugin.setName(usePluginModel.getName()); + usePlugin.setParameters(new Parameter[usePluginModel + .getParameters().size()]); + scenario.getUsePlugins()[i] = usePlugin; + for (j = 0; j < usePluginModel.getParameters().size(); j++) { + ParameterModel parameterModel = usePluginModel.getParameters() + .get(j); + Parameter parameter = new Parameter(); + parameter.setKey(parameterModel.getKey()); + parameter.setValue(parameterModel.getValue()); + scenario.getUsePlugins()[i].getParameters()[j] = parameter; + } + } + for (i = 0; i < runScenarioModel.getUserBehaviors().size(); i++) { + UserBehaviorModel userBehaviorModel = runScenarioModel + .getUserBehaviors().get(i); + UserBehavior userBehavior = new UserBehavior(); + userBehavior.setName(userBehaviorModel.getName()); + userBehavior.setUse(userBehaviorModel.getUse()); + userBehavior.setParameters(new Parameter[userBehaviorModel + .getParameters().size()]); + scenario.getUserBehaviors()[i] = userBehavior; + for (j = 0; j < userBehaviorModel.getParameters().size(); j++) { + ParameterModel parameterModel = userBehaviorModel + .getParameters().get(j); + Parameter parameter = new Parameter(); + parameter.setKey(parameterModel.getKey()); + parameter.setValue(parameterModel.getValue()); + scenario.getUserBehaviors()[i].getParameters()[j] = parameter; + } + } - scenario.setUsePlugins(new UsePlugin[2]); - scenario.getUsePlugins()[0] = new UsePlugin(); - scenario.getUsePlugins()[0].setId("http"); - scenario.getUsePlugins()[0].setName("Http"); - scenario.getUsePlugins()[0].setParameters(new Parameter[0]); - - scenario.getUsePlugins()[1] = new UsePlugin(); - scenario.getUsePlugins()[1].setId("timer"); - scenario.getUsePlugins()[1].setName("ConstantTimer"); - scenario.getUsePlugins()[1].setParameters(new Parameter[0]); - - scenario.setUserBehaviors(new UserBehavior[3]); - scenario.getUserBehaviors()[0] = new UserBehavior(); - scenario.getUserBehaviors()[0].setUse("http"); - scenario.getUserBehaviors()[0].setName("Get"); - scenario.getUserBehaviors()[0].setParameters(new Parameter[1]); - scenario.getUserBehaviors()[0].getParameters()[0] = new Parameter(); - scenario.getUserBehaviors()[0].getParameters()[0].setKey("url"); - scenario.getUserBehaviors()[0].getParameters()[0] - .setValue("http://localhost:6565"); - - scenario.getUserBehaviors()[2] = new UserBehavior(); - scenario.getUserBehaviors()[2].setUse("timer"); - scenario.getUserBehaviors()[2].setName("Sleep"); - scenario.getUserBehaviors()[2].setParameters(new Parameter[1]); - scenario.getUserBehaviors()[2].getParameters()[0] = new Parameter(); - scenario.getUserBehaviors()[2].getParameters()[0].setKey("time"); - scenario.getUserBehaviors()[2].getParameters()[0].setValue("1000"); - - scenario.getUserBehaviors()[1] = new UserBehavior(); - scenario.getUserBehaviors()[1].setUse("http"); - scenario.getUserBehaviors()[1].setName("Post"); - scenario.getUserBehaviors()[1].setParameters(new Parameter[2]); - scenario.getUserBehaviors()[1].getParameters()[0] = new Parameter(); - scenario.getUserBehaviors()[1].getParameters()[0].setKey("url"); - scenario.getUserBehaviors()[1].getParameters()[0] - .setValue("http://localhost:6565"); - scenario.getUserBehaviors()[1].getParameters()[1] = new Parameter(); - scenario.getUserBehaviors()[1].getParameters()[1].setKey("content"); - scenario.getUserBehaviors()[1].getParameters()[1] - .setValue("Hello,world!"); - - UUID uuid = UUID.randomUUID(); - this.getScenarioEngine().runScenario(uuid, scenario, 200); - return uuid; + RunScenarioResultModel runScenarioResultModel = new RunScenarioResultModel(); + runScenarioResultModel.setRunId(UUID.randomUUID()); + this.getScenarioEngine().runScenario(runScenarioResultModel.getRunId(), + scenario, runScenarioModel.getTotalCount()); + return runScenarioResultModel; } - @RequestMapping(value = "/detail/{uuid}", method = RequestMethod.GET) + @RequestMapping(value = "/detail/{runId}", method = RequestMethod.GET) @ResponseBody - public TestDetailStatusModel detail(@PathVariable UUID uuid) { + public TestDetailStatusModel detail(@PathVariable UUID runId) { ScenarioContext scenarioContext = this.getScenarioEngine() - .getRunningTests().get(uuid); + .getRunningTests().get(runId); TestDetailStatusModel testStatusModel = new TestDetailStatusModel(); testStatusModel.setStartDate(scenarioContext.getStartDate()); testStatusModel.setTestDetailModels(new ArrayList()); @@ -134,11 +143,11 @@ public class TestController { return testStatusModel; } - @RequestMapping(value = "/brief/{uuid}", method = RequestMethod.GET) + @RequestMapping(value = "/brief/{runId}", method = RequestMethod.GET) @ResponseBody - public TestBriefStatusModel brief(@PathVariable UUID uuid) { + public TestBriefStatusModel brief(@PathVariable UUID runId) { ScenarioContext scenarioContext = this.getScenarioEngine() - .getRunningTests().get(uuid); + .getRunningTests().get(runId); TestBriefStatusModel testBriefStatusModel = new TestBriefStatusModel(); testBriefStatusModel.setStartDate(scenarioContext.getStartDate()); int failCount = 0; diff --git a/src/main/java/org/bench4q/agent/api/model/ParameterModel.java b/src/main/java/org/bench4q/agent/api/model/ParameterModel.java new file mode 100644 index 00000000..130f7abb --- /dev/null +++ b/src/main/java/org/bench4q/agent/api/model/ParameterModel.java @@ -0,0 +1,29 @@ +package org.bench4q.agent.api.model; + +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; + } + +} diff --git a/src/main/java/org/bench4q/agent/api/model/RunScenarioModel.java b/src/main/java/org/bench4q/agent/api/model/RunScenarioModel.java new file mode 100644 index 00000000..2bcc4aca --- /dev/null +++ b/src/main/java/org/bench4q/agent/api/model/RunScenarioModel.java @@ -0,0 +1,43 @@ +package org.bench4q.agent.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 = "runScenario") +public class RunScenarioModel { + private int totalCount; + private List usePlugins; + private List userBehaviors; + + @XmlElement + public int getTotalCount() { + return totalCount; + } + + public void setTotalCount(int totalCount) { + this.totalCount = totalCount; + } + + @XmlElementWrapper(name = "usePlugins") + @XmlElement(name = "usePlugin") + public List getUsePlugins() { + return usePlugins; + } + + public void setUsePlugins(List usePlugins) { + this.usePlugins = usePlugins; + } + + @XmlElementWrapper(name = "userBehaviors") + @XmlElement(name = "userBehavior") + public List getUserBehaviors() { + return userBehaviors; + } + + public void setUserBehaviors(List userBehaviors) { + this.userBehaviors = userBehaviors; + } +} diff --git a/src/main/java/org/bench4q/agent/api/model/RunScenarioResultModel.java b/src/main/java/org/bench4q/agent/api/model/RunScenarioResultModel.java new file mode 100644 index 00000000..4f0c177a --- /dev/null +++ b/src/main/java/org/bench4q/agent/api/model/RunScenarioResultModel.java @@ -0,0 +1,21 @@ +package org.bench4q.agent.api.model; + +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; + } + +} diff --git a/src/main/java/org/bench4q/agent/api/model/UsePluginModel.java b/src/main/java/org/bench4q/agent/api/model/UsePluginModel.java new file mode 100644 index 00000000..f5c61d51 --- /dev/null +++ b/src/main/java/org/bench4q/agent/api/model/UsePluginModel.java @@ -0,0 +1,43 @@ +package org.bench4q.agent.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 = "usePlugin") +public class UsePluginModel { + private String id; + private String name; + private List 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 getParameters() { + return parameters; + } + + public void setParameters(List parameters) { + this.parameters = parameters; + } + +} diff --git a/src/main/java/org/bench4q/agent/api/model/UserBehaviorModel.java b/src/main/java/org/bench4q/agent/api/model/UserBehaviorModel.java new file mode 100644 index 00000000..c1c3f74f --- /dev/null +++ b/src/main/java/org/bench4q/agent/api/model/UserBehaviorModel.java @@ -0,0 +1,42 @@ +package org.bench4q.agent.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 = "userBehavior") +public class UserBehaviorModel { + private String use; + private String name; + private List 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 getParameters() { + return parameters; + } + + public void setParameters(List parameters) { + this.parameters = parameters; + } +} diff --git a/src/main/java/org/bench4q/agent/scenario/Parameter.java b/src/main/java/org/bench4q/agent/scenario/Parameter.java index 0947b4d9..325733d8 100644 --- a/src/main/java/org/bench4q/agent/scenario/Parameter.java +++ b/src/main/java/org/bench4q/agent/scenario/Parameter.java @@ -1,14 +1,9 @@ package org.bench4q.agent.scenario; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; - -@XmlRootElement(name = "parameter") public class Parameter { private String key; private String value; - @XmlElement public String getKey() { return key; } @@ -17,7 +12,6 @@ public class Parameter { this.key = key; } - @XmlElement public String getValue() { return value; } diff --git a/src/main/java/org/bench4q/agent/scenario/Scenario.java b/src/main/java/org/bench4q/agent/scenario/Scenario.java index 4853c8d5..938ee17b 100644 --- a/src/main/java/org/bench4q/agent/scenario/Scenario.java +++ b/src/main/java/org/bench4q/agent/scenario/Scenario.java @@ -1,16 +1,9 @@ package org.bench4q.agent.scenario; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlElementWrapper; -import javax.xml.bind.annotation.XmlRootElement; - -@XmlRootElement(name = "scenario") public class Scenario { private UsePlugin[] usePlugins; private UserBehavior[] userBehaviors; - @XmlElementWrapper(name = "plugins") - @XmlElement(name = "plugin") public UsePlugin[] getUsePlugins() { return usePlugins; } @@ -19,8 +12,6 @@ public class Scenario { this.usePlugins = usePlugins; } - @XmlElementWrapper(name = "userBehaviors") - @XmlElement(name = "userBehavior") public UserBehavior[] getUserBehaviors() { return userBehaviors; } diff --git a/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java b/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java index bac15e19..fe7e682e 100644 --- a/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java +++ b/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java @@ -46,7 +46,7 @@ public class ScenarioEngine { return this.getRunningTests().get(uuid); } - public void runScenario(UUID uuid, final Scenario scenario, int totalCount) { + public void runScenario(UUID runId, final Scenario scenario, int totalCount) { try { ScenarioContext scenarioContext = new ScenarioContext(); scenarioContext.setScenario(scenario); @@ -60,7 +60,7 @@ public class ScenarioEngine { final List ret = Collections .synchronizedList(new ArrayList()); scenarioContext.setResults(ret); - this.getRunningTests().put(uuid, scenarioContext); + this.getRunningTests().put(runId, scenarioContext); Runnable runnable = new Runnable() { public void run() { ret.addAll(doRunScenario(scenario)); diff --git a/src/main/java/org/bench4q/agent/scenario/UsePlugin.java b/src/main/java/org/bench4q/agent/scenario/UsePlugin.java index 44a85143..ac353a2f 100644 --- a/src/main/java/org/bench4q/agent/scenario/UsePlugin.java +++ b/src/main/java/org/bench4q/agent/scenario/UsePlugin.java @@ -1,16 +1,10 @@ package org.bench4q.agent.scenario; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlElementWrapper; -import javax.xml.bind.annotation.XmlRootElement; - -@XmlRootElement(name = "usePlugin") public class UsePlugin { private String id; private String name; private Parameter[] parameters; - @XmlElement public String getId() { return id; } @@ -19,7 +13,6 @@ public class UsePlugin { this.id = id; } - @XmlElement public String getName() { return name; } @@ -28,8 +21,6 @@ public class UsePlugin { this.name = name; } - @XmlElementWrapper(name = "parameters") - @XmlElement(name = "parameter") public Parameter[] getParameters() { return parameters; } diff --git a/src/main/java/org/bench4q/agent/scenario/UserBehavior.java b/src/main/java/org/bench4q/agent/scenario/UserBehavior.java index 976800fd..37f3577d 100644 --- a/src/main/java/org/bench4q/agent/scenario/UserBehavior.java +++ b/src/main/java/org/bench4q/agent/scenario/UserBehavior.java @@ -1,16 +1,10 @@ package org.bench4q.agent.scenario; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlElementWrapper; -import javax.xml.bind.annotation.XmlRootElement; - -@XmlRootElement(name = "userBehavior") public class UserBehavior { private String use; private String name; private Parameter[] parameters; - @XmlElement public String getUse() { return use; } @@ -19,7 +13,6 @@ public class UserBehavior { this.use = use; } - @XmlElement public String getName() { return name; } @@ -28,8 +21,6 @@ public class UserBehavior { this.name = name; } - @XmlElementWrapper(name = "parameters") - @XmlElement(name = "parameter") public Parameter[] getParameters() { return parameters; } diff --git a/src/test/java/org/bench4q/agent/test/RunScenarioTest.java b/src/test/java/org/bench4q/agent/test/RunScenarioTest.java new file mode 100644 index 00000000..5336aa36 --- /dev/null +++ b/src/test/java/org/bench4q/agent/test/RunScenarioTest.java @@ -0,0 +1,107 @@ +package org.bench4q.agent.test; + +import java.io.BufferedReader; +import java.io.InputStreamReader; +import java.io.OutputStreamWriter; +import java.io.StringWriter; +import java.net.HttpURLConnection; +import java.net.URL; +import java.util.ArrayList; + +import javax.xml.bind.JAXBContext; +import javax.xml.bind.Marshaller; + +import org.bench4q.agent.api.model.ParameterModel; +import org.bench4q.agent.api.model.RunScenarioModel; +import org.bench4q.agent.api.model.UsePluginModel; +import org.bench4q.agent.api.model.UserBehaviorModel; +import org.junit.Test; + +public class RunScenarioTest { + + @Test + public void testRunScenario() { + try { + RunScenarioModel runScenarioModel = new RunScenarioModel(); + runScenarioModel.setTotalCount(300); + runScenarioModel.setUsePlugins(new ArrayList()); + runScenarioModel + .setUserBehaviors(new ArrayList()); + UsePluginModel httpUsePluginModel = new UsePluginModel(); + httpUsePluginModel.setId("http"); + httpUsePluginModel.setName("Http"); + httpUsePluginModel.setParameters(new ArrayList()); + UsePluginModel timerUsePluginModel = new UsePluginModel(); + timerUsePluginModel.setId("timer"); + timerUsePluginModel.setName("ConstantTimer"); + timerUsePluginModel.setParameters(new ArrayList()); + runScenarioModel.getUsePlugins().add(httpUsePluginModel); + runScenarioModel.getUsePlugins().add(timerUsePluginModel); + UserBehaviorModel getUserBehaviorModel = new UserBehaviorModel(); + getUserBehaviorModel.setName("Get"); + getUserBehaviorModel.setUse("http"); + getUserBehaviorModel.setParameters(new ArrayList()); + ParameterModel parameterModelOne = new ParameterModel(); + parameterModelOne.setKey("url"); + parameterModelOne.setValue("http://localhost:6565"); + getUserBehaviorModel.getParameters().add(parameterModelOne); + runScenarioModel.getUserBehaviors().add(getUserBehaviorModel); + UserBehaviorModel timerUserBehaviorModel = new UserBehaviorModel(); + timerUserBehaviorModel.setName("Sleep"); + timerUserBehaviorModel.setUse("timer"); + timerUserBehaviorModel + .setParameters(new ArrayList()); + ParameterModel parameterModelTwo = new ParameterModel(); + parameterModelTwo.setKey("time"); + parameterModelTwo.setValue("1000"); + timerUserBehaviorModel.getParameters().add(parameterModelTwo); + runScenarioModel.getUserBehaviors().add(timerUserBehaviorModel); + UserBehaviorModel postUserBehaviorModel = new UserBehaviorModel(); + postUserBehaviorModel.setName("Post"); + postUserBehaviorModel.setUse("http"); + postUserBehaviorModel + .setParameters(new ArrayList()); + ParameterModel parameterModelThree = new ParameterModel(); + parameterModelThree.setKey("url"); + parameterModelThree.setValue("http://localhost:6565"); + postUserBehaviorModel.getParameters().add(parameterModelThree); + ParameterModel parameterModelFour = new ParameterModel(); + parameterModelFour.setKey("content"); + parameterModelFour.setValue("Hello,world!"); + postUserBehaviorModel.getParameters().add(parameterModelFour); + runScenarioModel.getUserBehaviors().add(postUserBehaviorModel); + Marshaller marshaller = JAXBContext.newInstance( + runScenarioModel.getClass()).createMarshaller(); + ; + StringWriter stringWriter = new StringWriter(); + marshaller.marshal(runScenarioModel, stringWriter); + String url = "http://localhost:6565/test/run"; + String content = stringWriter.toString(); + System.out.println(content); + URL target = new URL(url); + HttpURLConnection httpURLConnection = (HttpURLConnection) target + .openConnection(); + httpURLConnection.setDoOutput(true); + httpURLConnection.setDoInput(true); + httpURLConnection.setUseCaches(false); + httpURLConnection.setRequestMethod("POST"); + httpURLConnection.setRequestProperty("Content-Type", "application/xml"); + OutputStreamWriter outputStreamWriter = new OutputStreamWriter( + httpURLConnection.getOutputStream()); + outputStreamWriter.write(content); + outputStreamWriter.flush(); + outputStreamWriter.close(); + BufferedReader bufferedReader = new BufferedReader( + new InputStreamReader(httpURLConnection.getInputStream())); + int temp = -1; + StringBuffer stringBuffer = new StringBuffer(); + while ((temp = bufferedReader.read()) != -1) { + stringBuffer.append((char) temp); + } + bufferedReader.close(); + System.out.println(stringBuffer.toString()); + } catch (Exception e) { + e.printStackTrace(); + } + } +} From baa00c10542a1706980150fea63a02e658346e9f Mon Sep 17 00:00:00 2001 From: Zhen Tang Date: Fri, 28 Jun 2013 22:40:20 +0800 Subject: [PATCH 018/196] test can be cancelled or cleaned up. --- .../bench4q/agent/api/AgentController.java | 5 ---- .../org/bench4q/agent/api/HomeController.java | 1 - .../org/bench4q/agent/api/TestController.java | 24 +++++++++++++++++++ .../agent/api/model/CleanTestResultModel.java | 19 +++++++++++++++ .../agent/api/model/StopTestModel.java | 19 +++++++++++++++ 5 files changed, 62 insertions(+), 6 deletions(-) delete mode 100644 src/main/java/org/bench4q/agent/api/AgentController.java create mode 100644 src/main/java/org/bench4q/agent/api/model/CleanTestResultModel.java create mode 100644 src/main/java/org/bench4q/agent/api/model/StopTestModel.java diff --git a/src/main/java/org/bench4q/agent/api/AgentController.java b/src/main/java/org/bench4q/agent/api/AgentController.java deleted file mode 100644 index d76de836..00000000 --- a/src/main/java/org/bench4q/agent/api/AgentController.java +++ /dev/null @@ -1,5 +0,0 @@ -package org.bench4q.agent.api; - -public class AgentController { - -} diff --git a/src/main/java/org/bench4q/agent/api/HomeController.java b/src/main/java/org/bench4q/agent/api/HomeController.java index 46a0f120..aab99baa 100644 --- a/src/main/java/org/bench4q/agent/api/HomeController.java +++ b/src/main/java/org/bench4q/agent/api/HomeController.java @@ -12,7 +12,6 @@ public class HomeController { @RequestMapping(method = { RequestMethod.GET, RequestMethod.POST }) @ResponseBody public String index() { - return "It works!"; } } diff --git a/src/main/java/org/bench4q/agent/api/TestController.java b/src/main/java/org/bench4q/agent/api/TestController.java index 57a4d27a..a11e12c2 100644 --- a/src/main/java/org/bench4q/agent/api/TestController.java +++ b/src/main/java/org/bench4q/agent/api/TestController.java @@ -4,9 +4,11 @@ import java.util.ArrayList; import java.util.List; import java.util.UUID; +import org.bench4q.agent.api.model.CleanTestResultModel; import org.bench4q.agent.api.model.ParameterModel; import org.bench4q.agent.api.model.RunScenarioModel; import org.bench4q.agent.api.model.RunScenarioResultModel; +import org.bench4q.agent.api.model.StopTestModel; import org.bench4q.agent.api.model.TestBriefStatusModel; import org.bench4q.agent.api.model.TestDetailModel; import org.bench4q.agent.api.model.TestDetailStatusModel; @@ -178,4 +180,26 @@ public class TestController { testBriefStatusModel.setTotalCount(scenarioContext.getTotalCount()); return testBriefStatusModel; } + + @RequestMapping(value = "/stop/{runId}", method = RequestMethod.GET) + @ResponseBody + public StopTestModel stop(@PathVariable UUID runId) { + this.getScenarioEngine().getRunningTests().get(runId) + .getExecutorService().shutdownNow(); + StopTestModel stopTestModel = new StopTestModel(); + stopTestModel.setSuccess(true); + return stopTestModel; + } + + @RequestMapping(value = "/clean/{runId}", method = RequestMethod.GET) + @ResponseBody + public CleanTestResultModel clean(@PathVariable UUID runId) { + this.getScenarioEngine().getRunningTests().get(runId) + .getExecutorService().shutdownNow(); + this.getScenarioEngine().getRunningTests().remove(runId); + System.gc(); + CleanTestResultModel cleanTestResultModel = new CleanTestResultModel(); + cleanTestResultModel.setSuccess(true); + return cleanTestResultModel; + } } diff --git a/src/main/java/org/bench4q/agent/api/model/CleanTestResultModel.java b/src/main/java/org/bench4q/agent/api/model/CleanTestResultModel.java new file mode 100644 index 00000000..8358871b --- /dev/null +++ b/src/main/java/org/bench4q/agent/api/model/CleanTestResultModel.java @@ -0,0 +1,19 @@ +package org.bench4q.agent.api.model; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; + +@XmlRootElement(name = "cleanTestResult") +public class CleanTestResultModel { + private boolean success; + + @XmlElement + public boolean isSuccess() { + return success; + } + + public void setSuccess(boolean success) { + this.success = success; + } + +} diff --git a/src/main/java/org/bench4q/agent/api/model/StopTestModel.java b/src/main/java/org/bench4q/agent/api/model/StopTestModel.java new file mode 100644 index 00000000..d95e5484 --- /dev/null +++ b/src/main/java/org/bench4q/agent/api/model/StopTestModel.java @@ -0,0 +1,19 @@ +package org.bench4q.agent.api.model; + +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; + } + +} From 7a07e7b07a683949fb9e2118509b0d0f33fa0aad Mon Sep 17 00:00:00 2001 From: Zhen Tang Date: Sat, 29 Jun 2013 12:31:50 +0800 Subject: [PATCH 019/196] plugin service updated. clients can get parameter types now. --- .../bench4q/agent/api/PluginController.java | 21 ++++++++++---- .../agent/api/model/BehaviorInfoModel.java | 6 ++-- .../agent/api/model/ParameterInfoModel.java | 29 +++++++++++++++++++ .../agent/api/model/PluginInfoModel.java | 6 ++-- .../bench4q/agent/plugin/BehaviorInfo.java | 6 ++-- .../bench4q/agent/plugin/ParameterInfo.java | 23 +++++++++++++++ .../org/bench4q/agent/plugin/PluginInfo.java | 6 ++-- .../bench4q/agent/plugin/PluginManager.java | 26 ++++++++++------- 8 files changed, 94 insertions(+), 29 deletions(-) create mode 100644 src/main/java/org/bench4q/agent/api/model/ParameterInfoModel.java create mode 100644 src/main/java/org/bench4q/agent/plugin/ParameterInfo.java diff --git a/src/main/java/org/bench4q/agent/api/PluginController.java b/src/main/java/org/bench4q/agent/api/PluginController.java index a701b443..fb6d8e46 100644 --- a/src/main/java/org/bench4q/agent/api/PluginController.java +++ b/src/main/java/org/bench4q/agent/api/PluginController.java @@ -4,9 +4,11 @@ import java.util.ArrayList; import java.util.List; import org.bench4q.agent.api.model.BehaviorInfoModel; +import org.bench4q.agent.api.model.ParameterInfoModel; import org.bench4q.agent.api.model.PluginInfoListModel; import org.bench4q.agent.api.model.PluginInfoModel; import org.bench4q.agent.plugin.BehaviorInfo; +import org.bench4q.agent.plugin.ParameterInfo; import org.bench4q.agent.plugin.PluginInfo; import org.bench4q.agent.plugin.PluginManager; import org.springframework.beans.factory.annotation.Autowired; @@ -38,17 +40,24 @@ public class PluginController { for (PluginInfo pluginInfo : pluginInfos) { PluginInfoModel pluginInfoModel = new PluginInfoModel(); pluginInfoModel.setName(pluginInfo.getName()); - pluginInfoModel.setParameters(new ArrayList()); - for (String param : pluginInfo.getParameters()) { - pluginInfoModel.getParameters().add(param); + pluginInfoModel.setParameters(new ArrayList()); + for (ParameterInfo param : pluginInfo.getParameters()) { + ParameterInfoModel model = new ParameterInfoModel(); + model.setName(param.getName()); + model.setType(param.getType()); + pluginInfoModel.getParameters().add(model); } pluginInfoModel.setBehaviors(new ArrayList()); for (BehaviorInfo behaviorInfo : pluginInfo.getBehaviors()) { BehaviorInfoModel behaviorInfoModel = new BehaviorInfoModel(); behaviorInfoModel.setName(behaviorInfo.getName()); - behaviorInfoModel.setParameters(new ArrayList()); - for (String param : behaviorInfo.getParameters()) { - behaviorInfoModel.getParameters().add(param); + behaviorInfoModel + .setParameters(new ArrayList()); + for (ParameterInfo param : behaviorInfo.getParameters()) { + ParameterInfoModel model = new ParameterInfoModel(); + model.setName(param.getName()); + model.setType(param.getType()); + behaviorInfoModel.getParameters().add(model); } pluginInfoModel.getBehaviors().add(behaviorInfoModel); } diff --git a/src/main/java/org/bench4q/agent/api/model/BehaviorInfoModel.java b/src/main/java/org/bench4q/agent/api/model/BehaviorInfoModel.java index 3b5de043..a74eb5b7 100644 --- a/src/main/java/org/bench4q/agent/api/model/BehaviorInfoModel.java +++ b/src/main/java/org/bench4q/agent/api/model/BehaviorInfoModel.java @@ -9,7 +9,7 @@ import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement(name = "behaviorInfo") public class BehaviorInfoModel { private String name; - private List parameters; + private List parameters; @XmlElement public String getName() { @@ -22,11 +22,11 @@ public class BehaviorInfoModel { @XmlElementWrapper(name = "parameters") @XmlElement(name = "parameter") - public List getParameters() { + public List getParameters() { return parameters; } - public void setParameters(List parameters) { + public void setParameters(List parameters) { this.parameters = parameters; } } diff --git a/src/main/java/org/bench4q/agent/api/model/ParameterInfoModel.java b/src/main/java/org/bench4q/agent/api/model/ParameterInfoModel.java new file mode 100644 index 00000000..138b39bf --- /dev/null +++ b/src/main/java/org/bench4q/agent/api/model/ParameterInfoModel.java @@ -0,0 +1,29 @@ +package org.bench4q.agent.api.model; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; + +@XmlRootElement(name = "parameterInfo") +public class ParameterInfoModel { + private String name; + private String type; + + @XmlElement + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + @XmlElement + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + +} diff --git a/src/main/java/org/bench4q/agent/api/model/PluginInfoModel.java b/src/main/java/org/bench4q/agent/api/model/PluginInfoModel.java index a04bf6d6..bdbddb19 100644 --- a/src/main/java/org/bench4q/agent/api/model/PluginInfoModel.java +++ b/src/main/java/org/bench4q/agent/api/model/PluginInfoModel.java @@ -9,7 +9,7 @@ import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement(name = "pluginInfoItem") public class PluginInfoModel { private String name; - private List parameters; + private List parameters; private List behaviors; @XmlElement @@ -23,11 +23,11 @@ public class PluginInfoModel { @XmlElementWrapper(name = "parameters") @XmlElement(name = "parameter") - public List getParameters() { + public List getParameters() { return parameters; } - public void setParameters(List parameters) { + public void setParameters(List parameters) { this.parameters = parameters; } diff --git a/src/main/java/org/bench4q/agent/plugin/BehaviorInfo.java b/src/main/java/org/bench4q/agent/plugin/BehaviorInfo.java index 96317ac3..8489b801 100644 --- a/src/main/java/org/bench4q/agent/plugin/BehaviorInfo.java +++ b/src/main/java/org/bench4q/agent/plugin/BehaviorInfo.java @@ -2,7 +2,7 @@ package org.bench4q.agent.plugin; public class BehaviorInfo { private String name; - private String[] parameters; + private ParameterInfo[] parameters; public String getName() { return name; @@ -12,11 +12,11 @@ public class BehaviorInfo { this.name = name; } - public String[] getParameters() { + public ParameterInfo[] getParameters() { return parameters; } - public void setParameters(String[] parameters) { + public void setParameters(ParameterInfo[] parameters) { this.parameters = parameters; } diff --git a/src/main/java/org/bench4q/agent/plugin/ParameterInfo.java b/src/main/java/org/bench4q/agent/plugin/ParameterInfo.java new file mode 100644 index 00000000..52be6ee2 --- /dev/null +++ b/src/main/java/org/bench4q/agent/plugin/ParameterInfo.java @@ -0,0 +1,23 @@ +package org.bench4q.agent.plugin; + +public class ParameterInfo { + private String name; + private String type; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + +} diff --git a/src/main/java/org/bench4q/agent/plugin/PluginInfo.java b/src/main/java/org/bench4q/agent/plugin/PluginInfo.java index d3c8aa39..0063d172 100644 --- a/src/main/java/org/bench4q/agent/plugin/PluginInfo.java +++ b/src/main/java/org/bench4q/agent/plugin/PluginInfo.java @@ -2,7 +2,7 @@ package org.bench4q.agent.plugin; public class PluginInfo { private String name; - private String parameters[]; + private ParameterInfo[] parameters; private BehaviorInfo[] behaviors; public String getName() { @@ -13,11 +13,11 @@ public class PluginInfo { this.name = name; } - public String[] getParameters() { + public ParameterInfo[] getParameters() { return parameters; } - public void setParameters(String[] parameters) { + public void setParameters(ParameterInfo[] parameters) { this.parameters = parameters; } diff --git a/src/main/java/org/bench4q/agent/plugin/PluginManager.java b/src/main/java/org/bench4q/agent/plugin/PluginManager.java index ce71b093..5c3e6f9d 100644 --- a/src/main/java/org/bench4q/agent/plugin/PluginManager.java +++ b/src/main/java/org/bench4q/agent/plugin/PluginManager.java @@ -84,7 +84,7 @@ public class PluginManager { CtClass ctClass = classPool.get(plugin.getCanonicalName()); pluginInfo.setName(((Plugin) ctClass .getAnnotation(Plugin.class)).value()); - pluginInfo.setParameters(this.getParameterNames(ctClass + pluginInfo.setParameters(this.getParameters(ctClass .getConstructors()[0])); CtMethod[] behaviors = this.getBehaviors(ctClass); pluginInfo.setBehaviors(new BehaviorInfo[behaviors.length]); @@ -95,7 +95,7 @@ public class PluginManager { behaviorInfo.setName(((Behavior) behaviorMethod .getAnnotation(Behavior.class)).value()); behaviorInfo.setParameters(this - .getParameterNames(behaviorMethod)); + .getParameters(behaviorMethod)); pluginInfo.getBehaviors()[i] = behaviorInfo; } ret.add(pluginInfo); @@ -107,19 +107,23 @@ public class PluginManager { } } - private String[] getParameterNames(CtBehavior behavior) { + private ParameterInfo[] getParameters(CtBehavior behavior) { try { MethodInfo methodInfo = behavior.getMethodInfo(); CodeAttribute codeAttribute = methodInfo.getCodeAttribute(); LocalVariableAttribute localVariableAttribute = (LocalVariableAttribute) codeAttribute .getAttribute(LocalVariableAttribute.tag); int parameterCount = behavior.getParameterTypes().length; - String parameterNames[] = new String[parameterCount]; + ParameterInfo[] parameterNames = new ParameterInfo[parameterCount]; int i; int pos = Modifier.isStatic(behavior.getModifiers()) ? 0 : 1; for (i = 0; i < parameterCount; i++) { - parameterNames[i] = localVariableAttribute - .variableName(i + pos); + ParameterInfo parameterInfo = new ParameterInfo(); + parameterInfo.setName(localVariableAttribute.variableName(i + + pos)); + parameterInfo + .setType(behavior.getParameterTypes()[i].getName()); + parameterNames[i] = parameterInfo; } return parameterNames; } catch (Exception e) { @@ -166,13 +170,13 @@ public class PluginManager { private Object[] prepareParameters(CtBehavior behavior, Map parameters) { try { - String[] parameterNames = this.getParameterNames(behavior); - Object values[] = new Object[parameterNames.length]; + ParameterInfo[] parameterInfo = this.getParameters(behavior); + Object values[] = new Object[parameterInfo.length]; int i = 0; - for (i = 0; i < parameterNames.length; i++) { + for (i = 0; i < parameterInfo.length; i++) { values[i] = this.getTypeConverter().convert( - parameters.get(parameterNames[i]), - behavior.getParameterTypes()[i].getName()); + parameters.get(parameterInfo[i].getName()), + parameterInfo[i].getType()); } return values; } catch (Exception e) { From a1a5e391b88bff78a548ea6518027b519df0dc63 Mon Sep 17 00:00:00 2001 From: Zhen Tang Date: Sat, 29 Jun 2013 12:39:35 +0800 Subject: [PATCH 020/196] small bugfix. --- .../org/bench4q/agent/api/TestController.java | 22 +++++++++++++++---- .../bench4q/agent/plugin/PluginManager.java | 10 ++++++--- 2 files changed, 25 insertions(+), 7 deletions(-) diff --git a/src/main/java/org/bench4q/agent/api/TestController.java b/src/main/java/org/bench4q/agent/api/TestController.java index a11e12c2..78243e58 100644 --- a/src/main/java/org/bench4q/agent/api/TestController.java +++ b/src/main/java/org/bench4q/agent/api/TestController.java @@ -103,6 +103,9 @@ public class TestController { public TestDetailStatusModel detail(@PathVariable UUID runId) { ScenarioContext scenarioContext = this.getScenarioEngine() .getRunningTests().get(runId); + if (scenarioContext == null) { + return null; + } TestDetailStatusModel testStatusModel = new TestDetailStatusModel(); testStatusModel.setStartDate(scenarioContext.getStartDate()); testStatusModel.setTestDetailModels(new ArrayList()); @@ -150,6 +153,9 @@ public class TestController { public TestBriefStatusModel brief(@PathVariable UUID runId) { ScenarioContext scenarioContext = this.getScenarioEngine() .getRunningTests().get(runId); + if (scenarioContext == null) { + return null; + } TestBriefStatusModel testBriefStatusModel = new TestBriefStatusModel(); testBriefStatusModel.setStartDate(scenarioContext.getStartDate()); int failCount = 0; @@ -184,8 +190,12 @@ public class TestController { @RequestMapping(value = "/stop/{runId}", method = RequestMethod.GET) @ResponseBody public StopTestModel stop(@PathVariable UUID runId) { - this.getScenarioEngine().getRunningTests().get(runId) - .getExecutorService().shutdownNow(); + ScenarioContext scenarioContext = this.getScenarioEngine() + .getRunningTests().get(runId); + if (scenarioContext == null) { + return null; + } + scenarioContext.getExecutorService().shutdownNow(); StopTestModel stopTestModel = new StopTestModel(); stopTestModel.setSuccess(true); return stopTestModel; @@ -194,8 +204,12 @@ public class TestController { @RequestMapping(value = "/clean/{runId}", method = RequestMethod.GET) @ResponseBody public CleanTestResultModel clean(@PathVariable UUID runId) { - this.getScenarioEngine().getRunningTests().get(runId) - .getExecutorService().shutdownNow(); + ScenarioContext scenarioContext = this.getScenarioEngine() + .getRunningTests().get(runId); + if (scenarioContext == null) { + return null; + } + scenarioContext.getExecutorService().shutdownNow(); this.getScenarioEngine().getRunningTests().remove(runId); System.gc(); CleanTestResultModel cleanTestResultModel = new CleanTestResultModel(); diff --git a/src/main/java/org/bench4q/agent/plugin/PluginManager.java b/src/main/java/org/bench4q/agent/plugin/PluginManager.java index 5c3e6f9d..70c87621 100644 --- a/src/main/java/org/bench4q/agent/plugin/PluginManager.java +++ b/src/main/java/org/bench4q/agent/plugin/PluginManager.java @@ -174,9 +174,13 @@ public class PluginManager { Object values[] = new Object[parameterInfo.length]; int i = 0; for (i = 0; i < parameterInfo.length; i++) { - values[i] = this.getTypeConverter().convert( - parameters.get(parameterInfo[i].getName()), - parameterInfo[i].getType()); + Object value = parameters.get(parameterInfo[i].getName()); + if (value == null) { + values[i] = null; + } else { + values[i] = this.getTypeConverter().convert(value, + parameterInfo[i].getType()); + } } return values; } catch (Exception e) { From f5f0455f3ca8cf5be166e655a278fd42fadb4548 Mon Sep 17 00:00:00 2001 From: Zhen Tang Date: Sat, 29 Jun 2013 20:50:40 +0800 Subject: [PATCH 021/196] http plugin updated. log plugin added. --- .../{timer => basic}/ConstantTimerPlugin.java | 2 +- .../agent/plugin/basic/HttpPlugin.java | 132 ++++++++++++++++++ .../bench4q/agent/plugin/basic/LogPlugin.java | 17 +++ .../bench4q/agent/plugin/http/HttpPlugin.java | 72 ---------- 4 files changed, 150 insertions(+), 73 deletions(-) rename src/main/java/org/bench4q/agent/plugin/{timer => basic}/ConstantTimerPlugin.java (85%) create mode 100644 src/main/java/org/bench4q/agent/plugin/basic/HttpPlugin.java create mode 100644 src/main/java/org/bench4q/agent/plugin/basic/LogPlugin.java delete mode 100644 src/main/java/org/bench4q/agent/plugin/http/HttpPlugin.java diff --git a/src/main/java/org/bench4q/agent/plugin/timer/ConstantTimerPlugin.java b/src/main/java/org/bench4q/agent/plugin/basic/ConstantTimerPlugin.java similarity index 85% rename from src/main/java/org/bench4q/agent/plugin/timer/ConstantTimerPlugin.java rename to src/main/java/org/bench4q/agent/plugin/basic/ConstantTimerPlugin.java index f0cd8dfe..e33bb276 100644 --- a/src/main/java/org/bench4q/agent/plugin/timer/ConstantTimerPlugin.java +++ b/src/main/java/org/bench4q/agent/plugin/basic/ConstantTimerPlugin.java @@ -1,4 +1,4 @@ -package org.bench4q.agent.plugin.timer; +package org.bench4q.agent.plugin.basic; import org.bench4q.agent.plugin.Behavior; import org.bench4q.agent.plugin.Plugin; diff --git a/src/main/java/org/bench4q/agent/plugin/basic/HttpPlugin.java b/src/main/java/org/bench4q/agent/plugin/basic/HttpPlugin.java new file mode 100644 index 00000000..35d47635 --- /dev/null +++ b/src/main/java/org/bench4q/agent/plugin/basic/HttpPlugin.java @@ -0,0 +1,132 @@ +package org.bench4q.agent.plugin.basic; + +import java.io.BufferedReader; +import java.io.InputStreamReader; +import java.io.OutputStreamWriter; +import java.net.HttpURLConnection; +import java.net.URL; +import org.bench4q.agent.plugin.Behavior; +import org.bench4q.agent.plugin.Plugin; + +@Plugin("Http") +public class HttpPlugin { + + public HttpPlugin() { + + } + + @Behavior("Get") + public boolean get(String url) { + try { + URL target = new URL(url); + HttpURLConnection httpURLConnection = (HttpURLConnection) target + .openConnection(); + httpURLConnection.setDoOutput(false); + httpURLConnection.setDoInput(true); + httpURLConnection.setUseCaches(false); + httpURLConnection.setRequestMethod("GET"); + BufferedReader bufferedReader = new BufferedReader( + new InputStreamReader(httpURLConnection.getInputStream())); + int temp = -1; + StringBuffer stringBuffer = new StringBuffer(); + while ((temp = bufferedReader.read()) != -1) { + stringBuffer.append((char) temp); + } + bufferedReader.close(); + return true; + } catch (Exception e) { + e.printStackTrace(); + return false; + } + } + + @Behavior("Post") + public boolean post(String url, String content) { + try { + URL target = new URL(url); + HttpURLConnection httpURLConnection = (HttpURLConnection) target + .openConnection(); + httpURLConnection.setDoOutput(true); + httpURLConnection.setDoInput(true); + httpURLConnection.setUseCaches(false); + httpURLConnection.setRequestMethod("POST"); + OutputStreamWriter outputStreamWriter = new OutputStreamWriter( + httpURLConnection.getOutputStream()); + outputStreamWriter.write(content); + outputStreamWriter.flush(); + outputStreamWriter.close(); + BufferedReader bufferedReader = new BufferedReader( + new InputStreamReader(httpURLConnection.getInputStream())); + int temp = -1; + StringBuffer stringBuffer = new StringBuffer(); + while ((temp = bufferedReader.read()) != -1) { + stringBuffer.append((char) temp); + } + bufferedReader.close(); + return true; + } catch (Exception e) { + e.printStackTrace(); + return false; + } + } + + @Behavior("Put") + public boolean put(String url, String content) { + try { + URL target = new URL(url); + HttpURLConnection httpURLConnection = (HttpURLConnection) target + .openConnection(); + httpURLConnection.setDoOutput(true); + httpURLConnection.setDoInput(true); + httpURLConnection.setUseCaches(false); + httpURLConnection.setRequestMethod("PUT"); + OutputStreamWriter outputStreamWriter = new OutputStreamWriter( + httpURLConnection.getOutputStream()); + outputStreamWriter.write(content); + outputStreamWriter.flush(); + outputStreamWriter.close(); + BufferedReader bufferedReader = new BufferedReader( + new InputStreamReader(httpURLConnection.getInputStream())); + int temp = -1; + StringBuffer stringBuffer = new StringBuffer(); + while ((temp = bufferedReader.read()) != -1) { + stringBuffer.append((char) temp); + } + bufferedReader.close(); + return true; + } catch (Exception e) { + e.printStackTrace(); + return false; + } + } + + @Behavior("Delete") + public boolean delete(String url, String content) { + try { + URL target = new URL(url); + HttpURLConnection httpURLConnection = (HttpURLConnection) target + .openConnection(); + httpURLConnection.setDoOutput(true); + httpURLConnection.setDoInput(true); + httpURLConnection.setUseCaches(false); + httpURLConnection.setRequestMethod("DELETE"); + OutputStreamWriter outputStreamWriter = new OutputStreamWriter( + httpURLConnection.getOutputStream()); + outputStreamWriter.write(content); + outputStreamWriter.flush(); + outputStreamWriter.close(); + BufferedReader bufferedReader = new BufferedReader( + new InputStreamReader(httpURLConnection.getInputStream())); + int temp = -1; + StringBuffer stringBuffer = new StringBuffer(); + while ((temp = bufferedReader.read()) != -1) { + stringBuffer.append((char) temp); + } + bufferedReader.close(); + return true; + } catch (Exception e) { + e.printStackTrace(); + return false; + } + } +} diff --git a/src/main/java/org/bench4q/agent/plugin/basic/LogPlugin.java b/src/main/java/org/bench4q/agent/plugin/basic/LogPlugin.java new file mode 100644 index 00000000..58d7007d --- /dev/null +++ b/src/main/java/org/bench4q/agent/plugin/basic/LogPlugin.java @@ -0,0 +1,17 @@ +package org.bench4q.agent.plugin.basic; + +import org.bench4q.agent.plugin.Behavior; +import org.bench4q.agent.plugin.Plugin; + +@Plugin("Log") +public class LogPlugin { + public LogPlugin() { + + } + + @Behavior("Log") + public boolean log(String message) { + System.out.println(message); + return true; + } +} diff --git a/src/main/java/org/bench4q/agent/plugin/http/HttpPlugin.java b/src/main/java/org/bench4q/agent/plugin/http/HttpPlugin.java deleted file mode 100644 index f50c861d..00000000 --- a/src/main/java/org/bench4q/agent/plugin/http/HttpPlugin.java +++ /dev/null @@ -1,72 +0,0 @@ -package org.bench4q.agent.plugin.http; - -import java.io.BufferedReader; -import java.io.InputStreamReader; -import java.io.OutputStreamWriter; -import java.net.HttpURLConnection; -import java.net.URL; -import org.bench4q.agent.plugin.Behavior; -import org.bench4q.agent.plugin.Plugin; - -@Plugin("Http") -public class HttpPlugin { - - public HttpPlugin() { - - } - - @Behavior("Get") - public boolean get(String url) { - try { - URL target = new URL(url); - HttpURLConnection httpURLConnection = (HttpURLConnection) target - .openConnection(); - httpURLConnection.setDoOutput(false); - httpURLConnection.setDoInput(true); - httpURLConnection.setUseCaches(false); - httpURLConnection.setRequestMethod("GET"); - BufferedReader bufferedReader = new BufferedReader( - new InputStreamReader(httpURLConnection.getInputStream())); - int temp = -1; - StringBuffer stringBuffer = new StringBuffer(); - while ((temp = bufferedReader.read()) != -1) { - stringBuffer.append((char) temp); - } - bufferedReader.close(); - return true; - } catch (Exception e) { - e.printStackTrace(); - return false; - } - } - - @Behavior("Post") - public boolean post(String url, String content) { - try { - URL target = new URL(url); - HttpURLConnection httpURLConnection = (HttpURLConnection) target - .openConnection(); - httpURLConnection.setDoOutput(true); - httpURLConnection.setDoInput(true); - httpURLConnection.setUseCaches(false); - httpURLConnection.setRequestMethod("POST"); - OutputStreamWriter outputStreamWriter = new OutputStreamWriter( - httpURLConnection.getOutputStream()); - outputStreamWriter.write(content); - outputStreamWriter.flush(); - outputStreamWriter.close(); - BufferedReader bufferedReader = new BufferedReader( - new InputStreamReader(httpURLConnection.getInputStream())); - int temp = -1; - StringBuffer stringBuffer = new StringBuffer(); - while ((temp = bufferedReader.read()) != -1) { - stringBuffer.append((char) temp); - } - bufferedReader.close(); - return true; - } catch (Exception e) { - e.printStackTrace(); - return false; - } - } -} From f4f22a47d4952b1b4da74308f0c37f8941d2a3f5 Mon Sep 17 00:00:00 2001 From: Zhen Tang Date: Sun, 30 Jun 2013 11:48:52 +0800 Subject: [PATCH 022/196] add pool size setting now. --- .../java/org/bench4q/agent/api/TestController.java | 3 ++- .../org/bench4q/agent/api/model/RunScenarioModel.java | 10 ++++++++++ .../org/bench4q/agent/scenario/ScenarioContext.java | 9 +++++++++ .../org/bench4q/agent/scenario/ScenarioEngine.java | 6 ++++-- .../java/org/bench4q/agent/test/RunScenarioTest.java | 6 ++++-- 5 files changed, 29 insertions(+), 5 deletions(-) diff --git a/src/main/java/org/bench4q/agent/api/TestController.java b/src/main/java/org/bench4q/agent/api/TestController.java index 78243e58..c215b0be 100644 --- a/src/main/java/org/bench4q/agent/api/TestController.java +++ b/src/main/java/org/bench4q/agent/api/TestController.java @@ -94,7 +94,8 @@ public class TestController { RunScenarioResultModel runScenarioResultModel = new RunScenarioResultModel(); runScenarioResultModel.setRunId(UUID.randomUUID()); this.getScenarioEngine().runScenario(runScenarioResultModel.getRunId(), - scenario, runScenarioModel.getTotalCount()); + scenario, runScenarioModel.getPoolSize(), + runScenarioModel.getTotalCount()); return runScenarioResultModel; } diff --git a/src/main/java/org/bench4q/agent/api/model/RunScenarioModel.java b/src/main/java/org/bench4q/agent/api/model/RunScenarioModel.java index 2bcc4aca..7d8cf9bd 100644 --- a/src/main/java/org/bench4q/agent/api/model/RunScenarioModel.java +++ b/src/main/java/org/bench4q/agent/api/model/RunScenarioModel.java @@ -8,10 +8,20 @@ import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement(name = "runScenario") public class RunScenarioModel { + private int poolSize; private int totalCount; private List usePlugins; private List userBehaviors; + @XmlElement + public int getPoolSize() { + return poolSize; + } + + public void setPoolSize(int poolSize) { + this.poolSize = poolSize; + } + @XmlElement public int getTotalCount() { return totalCount; diff --git a/src/main/java/org/bench4q/agent/scenario/ScenarioContext.java b/src/main/java/org/bench4q/agent/scenario/ScenarioContext.java index 08ec51c9..35ffde4e 100644 --- a/src/main/java/org/bench4q/agent/scenario/ScenarioContext.java +++ b/src/main/java/org/bench4q/agent/scenario/ScenarioContext.java @@ -7,12 +7,21 @@ import java.util.concurrent.ExecutorService; import org.bench4q.agent.plugin.BehaviorResult; public class ScenarioContext { + private int poolSize; private int totalCount; private Date startDate; private ExecutorService executorService; private Scenario scenario; private List results; + public int getPoolSize() { + return poolSize; + } + + public void setPoolSize(int poolSize) { + this.poolSize = poolSize; + } + public int getTotalCount() { return totalCount; } diff --git a/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java b/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java index fe7e682e..645e0434 100644 --- a/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java +++ b/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java @@ -46,15 +46,17 @@ public class ScenarioEngine { return this.getRunningTests().get(uuid); } - public void runScenario(UUID runId, final Scenario scenario, int totalCount) { + public void runScenario(UUID runId, final Scenario scenario, int poolSize, + int totalCount) { try { ScenarioContext scenarioContext = new ScenarioContext(); scenarioContext.setScenario(scenario); scenarioContext.setTotalCount(totalCount * scenario.getUserBehaviors().length); + scenarioContext.setPoolSize(poolSize); scenarioContext.setStartDate(new Date(System.currentTimeMillis())); ExecutorService executorService = Executors - .newFixedThreadPool(totalCount); + .newFixedThreadPool(poolSize); scenarioContext.setExecutorService(executorService); int i; final List ret = Collections diff --git a/src/test/java/org/bench4q/agent/test/RunScenarioTest.java b/src/test/java/org/bench4q/agent/test/RunScenarioTest.java index 5336aa36..2e1d5052 100644 --- a/src/test/java/org/bench4q/agent/test/RunScenarioTest.java +++ b/src/test/java/org/bench4q/agent/test/RunScenarioTest.java @@ -23,7 +23,8 @@ public class RunScenarioTest { public void testRunScenario() { try { RunScenarioModel runScenarioModel = new RunScenarioModel(); - runScenarioModel.setTotalCount(300); + runScenarioModel.setTotalCount(30000); + runScenarioModel.setPoolSize(300); runScenarioModel.setUsePlugins(new ArrayList()); runScenarioModel .setUserBehaviors(new ArrayList()); @@ -85,7 +86,8 @@ public class RunScenarioTest { httpURLConnection.setDoInput(true); httpURLConnection.setUseCaches(false); httpURLConnection.setRequestMethod("POST"); - httpURLConnection.setRequestProperty("Content-Type", "application/xml"); + httpURLConnection.setRequestProperty("Content-Type", + "application/xml"); OutputStreamWriter outputStreamWriter = new OutputStreamWriter( httpURLConnection.getOutputStream()); outputStreamWriter.write(content); From 55d2118740fadda8f16762473e0270b0f51377ff Mon Sep 17 00:00:00 2001 From: Zhen Tang Date: Sun, 30 Jun 2013 12:00:10 +0800 Subject: [PATCH 023/196] bug fix. avoid concurrency problem. --- src/main/java/org/bench4q/agent/api/TestController.java | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/bench4q/agent/api/TestController.java b/src/main/java/org/bench4q/agent/api/TestController.java index c215b0be..643e7496 100644 --- a/src/main/java/org/bench4q/agent/api/TestController.java +++ b/src/main/java/org/bench4q/agent/api/TestController.java @@ -112,7 +112,8 @@ public class TestController { testStatusModel.setTestDetailModels(new ArrayList()); int failCount = 0; int successCount = 0; - List behaviorResults = scenarioContext.getResults(); + List behaviorResults = new ArrayList( + scenarioContext.getResults()); long maxDate = 0; long totalResponseTime = 0; for (BehaviorResult behaviorResult : behaviorResults) { @@ -162,7 +163,8 @@ public class TestController { int failCount = 0; int successCount = 0; long totalResponseTime = 0; - List behaviorResults = scenarioContext.getResults(); + List behaviorResults = new ArrayList( + scenarioContext.getResults()); long maxDate = 0; for (BehaviorResult behaviorResult : behaviorResults) { if (behaviorResult.getEndDate().getTime() > maxDate) { From 14d9f54e3d18729ec281df61f2721569f21675f2 Mon Sep 17 00:00:00 2001 From: Zhen Tang Date: Sun, 30 Jun 2013 15:54:22 +0800 Subject: [PATCH 024/196] command line plugin added. --- .../agent/plugin/basic/CommandLinePlugin.java | 87 +++++++++++++++++++ 1 file changed, 87 insertions(+) create mode 100644 src/main/java/org/bench4q/agent/plugin/basic/CommandLinePlugin.java diff --git a/src/main/java/org/bench4q/agent/plugin/basic/CommandLinePlugin.java b/src/main/java/org/bench4q/agent/plugin/basic/CommandLinePlugin.java new file mode 100644 index 00000000..02741f3d --- /dev/null +++ b/src/main/java/org/bench4q/agent/plugin/basic/CommandLinePlugin.java @@ -0,0 +1,87 @@ +package org.bench4q.agent.plugin.basic; + +import java.io.BufferedReader; +import java.io.InputStreamReader; + +import org.bench4q.agent.plugin.Behavior; +import org.bench4q.agent.plugin.Plugin; + +@Plugin("CommandLine") +public class CommandLinePlugin { + private String standardOutput; + private String standardError; + + public String getStandardOutput() { + return standardOutput; + } + + private void setStandardOutput(String standardOutput) { + this.standardOutput = standardOutput; + } + + public String getStandardError() { + return standardError; + } + + private void setStandardError(String standardError) { + this.standardError = standardError; + } + + public CommandLinePlugin() { + + } + + @Behavior("Command") + public boolean command(String command) { + try { + final Process process = Runtime.getRuntime().exec(command); + new Thread() { + public void run() { + try { + BufferedReader reader = new BufferedReader( + new InputStreamReader(process.getInputStream())); + String streamline = ""; + try { + setStandardOutput(""); + while ((streamline = reader.readLine()) != null) { + setStandardOutput(getStandardOutput() + + streamline + + System.getProperty("line.separator")); + } + } finally { + reader.close(); + } + } catch (Exception e) { + e.printStackTrace(); + } + } + }.start(); + new Thread() { + public void run() { + try { + BufferedReader reader = new BufferedReader( + new InputStreamReader(process.getErrorStream())); + String streamline = ""; + try { + setStandardError(""); + while ((streamline = reader.readLine()) != null) { + setStandardError(getStandardError() + + streamline + + System.getProperty("line.separator")); + } + } finally { + reader.close(); + } + } catch (Exception e) { + e.printStackTrace(); + } + } + }.start(); + process.waitFor(); + return true; + } catch (Exception e) { + e.printStackTrace(); + return false; + } + } +} From 1aa4f9465c4442042ea42cd8043463e6ed93a127 Mon Sep 17 00:00:00 2001 From: Zhen Tang Date: Mon, 1 Jul 2013 16:48:07 +0800 Subject: [PATCH 025/196] add server status report. --- .../org/bench4q/agent/api/HomeController.java | 36 +++++++++++++++++-- .../agent/api/model/ServerStatusModel.java | 32 +++++++++++++++++ .../bench4q/agent/test/RunScenarioTest.java | 4 +-- 3 files changed, 68 insertions(+), 4 deletions(-) create mode 100644 src/main/java/org/bench4q/agent/api/model/ServerStatusModel.java diff --git a/src/main/java/org/bench4q/agent/api/HomeController.java b/src/main/java/org/bench4q/agent/api/HomeController.java index aab99baa..078b3e42 100644 --- a/src/main/java/org/bench4q/agent/api/HomeController.java +++ b/src/main/java/org/bench4q/agent/api/HomeController.java @@ -1,5 +1,14 @@ package org.bench4q.agent.api; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; + +import org.bench4q.agent.api.model.ServerStatusModel; +import org.bench4q.agent.scenario.ScenarioContext; +import org.bench4q.agent.scenario.ScenarioEngine; +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; @@ -8,10 +17,33 @@ import org.springframework.web.bind.annotation.ResponseBody; @Controller @RequestMapping("/") public class HomeController { + private ScenarioEngine scenarioEngine; + + private ScenarioEngine getScenarioEngine() { + return scenarioEngine; + } + + @Autowired + private void setScenarioEngine(ScenarioEngine scenarioEngine) { + this.scenarioEngine = scenarioEngine; + } @RequestMapping(method = { RequestMethod.GET, RequestMethod.POST }) @ResponseBody - public String index() { - return "It works!"; + public ServerStatusModel index() { + ServerStatusModel serverStatusModel = new ServerStatusModel(); + serverStatusModel.setFinishedTests(new ArrayList()); + serverStatusModel.setRunningTests(new ArrayList()); + Map contexts = new HashMap( + getScenarioEngine().getRunningTests()); + for (UUID key : contexts.keySet()) { + ScenarioContext value = contexts.get(key); + if (value.getResults().size() == value.getTotalCount()) { + serverStatusModel.getFinishedTests().add(key); + } else { + serverStatusModel.getRunningTests().add(key); + } + } + return serverStatusModel; } } diff --git a/src/main/java/org/bench4q/agent/api/model/ServerStatusModel.java b/src/main/java/org/bench4q/agent/api/model/ServerStatusModel.java new file mode 100644 index 00000000..bcf0e170 --- /dev/null +++ b/src/main/java/org/bench4q/agent/api/model/ServerStatusModel.java @@ -0,0 +1,32 @@ +package org.bench4q.agent.api.model; + +import java.util.List; +import java.util.UUID; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; + +@XmlRootElement(name = "serverStatus") +public class ServerStatusModel { + private List runningTests; + private List finishedTests; + + @XmlElement + public List getRunningTests() { + return runningTests; + } + + public void setRunningTests(List runningTests) { + this.runningTests = runningTests; + } + + @XmlElement + public List getFinishedTests() { + return finishedTests; + } + + public void setFinishedTests(List finishedTests) { + this.finishedTests = finishedTests; + } + +} diff --git a/src/test/java/org/bench4q/agent/test/RunScenarioTest.java b/src/test/java/org/bench4q/agent/test/RunScenarioTest.java index 2e1d5052..c2f10c91 100644 --- a/src/test/java/org/bench4q/agent/test/RunScenarioTest.java +++ b/src/test/java/org/bench4q/agent/test/RunScenarioTest.java @@ -23,8 +23,8 @@ public class RunScenarioTest { public void testRunScenario() { try { RunScenarioModel runScenarioModel = new RunScenarioModel(); - runScenarioModel.setTotalCount(30000); - runScenarioModel.setPoolSize(300); + runScenarioModel.setTotalCount(10000); + runScenarioModel.setPoolSize(100); runScenarioModel.setUsePlugins(new ArrayList()); runScenarioModel .setUserBehaviors(new ArrayList()); From 61ef0096253b11382c3e332425bf18aa586b91c1 Mon Sep 17 00:00:00 2001 From: Zhen Tang Date: Mon, 1 Jul 2013 16:53:01 +0800 Subject: [PATCH 026/196] small bug fix. --- .../org/bench4q/agent/api/model/ServerStatusModel.java | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/bench4q/agent/api/model/ServerStatusModel.java b/src/main/java/org/bench4q/agent/api/model/ServerStatusModel.java index bcf0e170..07a1ca7d 100644 --- a/src/main/java/org/bench4q/agent/api/model/ServerStatusModel.java +++ b/src/main/java/org/bench4q/agent/api/model/ServerStatusModel.java @@ -4,6 +4,7 @@ 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") @@ -11,7 +12,8 @@ public class ServerStatusModel { private List runningTests; private List finishedTests; - @XmlElement + @XmlElementWrapper(name = "runningTests") + @XmlElement(name = "runningTest") public List getRunningTests() { return runningTests; } @@ -20,7 +22,8 @@ public class ServerStatusModel { this.runningTests = runningTests; } - @XmlElement + @XmlElementWrapper(name = "finishedTests") + @XmlElement(name = "finishedTest") public List getFinishedTests() { return finishedTests; } From 607d1cc8e266b5d6d695df40f4123b7eb5004206 Mon Sep 17 00:00:00 2001 From: Zhen Tang Date: Tue, 2 Jul 2013 22:38:19 +0800 Subject: [PATCH 027/196] small bug fix. exclude timers' response time correctly. --- src/main/java/org/bench4q/agent/api/TestController.java | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/bench4q/agent/api/TestController.java b/src/main/java/org/bench4q/agent/api/TestController.java index 643e7496..c973e6e8 100644 --- a/src/main/java/org/bench4q/agent/api/TestController.java +++ b/src/main/java/org/bench4q/agent/api/TestController.java @@ -116,6 +116,7 @@ public class TestController { scenarioContext.getResults()); long maxDate = 0; long totalResponseTime = 0; + int validCount = 0; for (BehaviorResult behaviorResult : behaviorResults) { TestDetailModel testDetailModel = new TestDetailModel(); testDetailModel.setBehaviorName(behaviorResult.getBehaviorName()); @@ -136,10 +137,11 @@ public class TestController { } if (!behaviorResult.getPluginName().contains("Timer")) { totalResponseTime += behaviorResult.getResponseTime(); + validCount++; } } testStatusModel.setAverageResponseTime((totalResponseTime + 0.0) - / behaviorResults.size()); + / validCount); testStatusModel.setElapsedTime(maxDate - testStatusModel.getStartDate().getTime()); testStatusModel.setFailCount(failCount); @@ -166,6 +168,7 @@ public class TestController { List behaviorResults = new ArrayList( scenarioContext.getResults()); long maxDate = 0; + int validCount = 0; for (BehaviorResult behaviorResult : behaviorResults) { if (behaviorResult.getEndDate().getTime() > maxDate) { maxDate = behaviorResult.getEndDate().getTime(); @@ -177,10 +180,11 @@ public class TestController { } if (!behaviorResult.getPluginName().contains("Timer")) { totalResponseTime += behaviorResult.getResponseTime(); + validCount++; } } testBriefStatusModel.setAverageResponseTime((totalResponseTime + 0.0) - / behaviorResults.size()); + / validCount); testBriefStatusModel.setElapsedTime(maxDate - testBriefStatusModel.getStartDate().getTime()); testBriefStatusModel.setFailCount(failCount); From 00a2c4341bd3d64670c1ea49be9b62b54d0adbed Mon Sep 17 00:00:00 2001 From: Zhen Tang Date: Tue, 2 Jul 2013 22:50:51 +0800 Subject: [PATCH 028/196] test results can be saved to file now. --- .../org/bench4q/agent/api/TestController.java | 10 ++ .../agent/api/model/SaveTestResultModel.java | 19 +++ .../bench4q/agent/plugin/BehaviorResult.java | 10 ++ .../agent/scenario/ScenarioEngine.java | 78 +++++++++++- .../bench4q/agent/scenario/TestResult.java | 111 ++++++++++++++++++ .../agent/scenario/TestResultItem.java | 93 +++++++++++++++ .../bench4q/agent/test/RunScenarioTest.java | 3 +- 7 files changed, 318 insertions(+), 6 deletions(-) create mode 100644 src/main/java/org/bench4q/agent/api/model/SaveTestResultModel.java create mode 100644 src/main/java/org/bench4q/agent/scenario/TestResult.java create mode 100644 src/main/java/org/bench4q/agent/scenario/TestResultItem.java diff --git a/src/main/java/org/bench4q/agent/api/TestController.java b/src/main/java/org/bench4q/agent/api/TestController.java index c973e6e8..be332f7a 100644 --- a/src/main/java/org/bench4q/agent/api/TestController.java +++ b/src/main/java/org/bench4q/agent/api/TestController.java @@ -8,6 +8,7 @@ import org.bench4q.agent.api.model.CleanTestResultModel; import org.bench4q.agent.api.model.ParameterModel; import org.bench4q.agent.api.model.RunScenarioModel; import org.bench4q.agent.api.model.RunScenarioResultModel; +import org.bench4q.agent.api.model.SaveTestResultModel; import org.bench4q.agent.api.model.StopTestModel; import org.bench4q.agent.api.model.TestBriefStatusModel; import org.bench4q.agent.api.model.TestDetailModel; @@ -223,4 +224,13 @@ public class TestController { cleanTestResultModel.setSuccess(true); return cleanTestResultModel; } + + @RequestMapping(value = "/save/{runId}", method = RequestMethod.GET) + @ResponseBody + public SaveTestResultModel save(@PathVariable UUID runId) { + this.getScenarioEngine().saveTestResults(runId); + SaveTestResultModel saveTestResultModel = new SaveTestResultModel(); + saveTestResultModel.setSuccess(true); + return saveTestResultModel; + } } diff --git a/src/main/java/org/bench4q/agent/api/model/SaveTestResultModel.java b/src/main/java/org/bench4q/agent/api/model/SaveTestResultModel.java new file mode 100644 index 00000000..9fdff373 --- /dev/null +++ b/src/main/java/org/bench4q/agent/api/model/SaveTestResultModel.java @@ -0,0 +1,19 @@ +package org.bench4q.agent.api.model; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; + +@XmlRootElement(name = "saveTestResult") +public class SaveTestResultModel { + private boolean success; + + @XmlElement + public boolean isSuccess() { + return success; + } + + public void setSuccess(boolean success) { + this.success = success; + } + +} diff --git a/src/main/java/org/bench4q/agent/plugin/BehaviorResult.java b/src/main/java/org/bench4q/agent/plugin/BehaviorResult.java index 9676d8c4..d1fe0cbe 100644 --- a/src/main/java/org/bench4q/agent/plugin/BehaviorResult.java +++ b/src/main/java/org/bench4q/agent/plugin/BehaviorResult.java @@ -1,8 +1,10 @@ package org.bench4q.agent.plugin; import java.util.Date; +import java.util.UUID; public class BehaviorResult { + private UUID id; private String pluginId; private String pluginName; private String behaviorName; @@ -11,6 +13,14 @@ public class BehaviorResult { private long responseTime; private boolean success; + public UUID getId() { + return id; + } + + public void setId(UUID id) { + this.id = id; + } + public String getPluginId() { return pluginId; } diff --git a/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java b/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java index 645e0434..ab1100f4 100644 --- a/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java +++ b/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java @@ -1,5 +1,7 @@ package org.bench4q.agent.scenario; +import java.io.File; +import java.io.FileWriter; import java.util.ArrayList; import java.util.Collections; import java.util.Date; @@ -10,6 +12,9 @@ import java.util.UUID; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; +import javax.xml.bind.JAXBContext; +import javax.xml.bind.Marshaller; + import org.bench4q.agent.plugin.BehaviorResult; import org.bench4q.agent.plugin.Plugin; import org.bench4q.agent.plugin.PluginManager; @@ -42,10 +47,6 @@ public class ScenarioEngine { this.runningTests = runningTests; } - public ScenarioContext getState(UUID uuid) { - return this.getRunningTests().get(uuid); - } - public void runScenario(UUID runId, final Scenario scenario, int poolSize, int totalCount) { try { @@ -102,6 +103,7 @@ public class ScenarioEngine { .put(parameter.getKey(), parameter.getValue()); } BehaviorResult result = new BehaviorResult(); + result.setId(UUID.randomUUID()); result.setStartDate(new Date(System.currentTimeMillis())); boolean success = (Boolean) this.getPluginManager().doBehavior( plugin, behaviorName, behaviorParameters); @@ -117,4 +119,72 @@ public class ScenarioEngine { } return ret; } + + public String getPath() { + return System.getProperty("user.dir"); + } + + public void saveTestResults(UUID runId) { + try { + ScenarioContext scenarioContext = this.getRunningTests().get(runId); + if (scenarioContext == null) { + return; + } + TestResult testResult = new TestResult(); + testResult.setRunId(runId); + testResult.setPoolSize(scenarioContext.getPoolSize()); + testResult.setResults(new ArrayList()); + testResult.setStartDate(scenarioContext.getStartDate()); + testResult.setTotalCount(scenarioContext.getTotalCount()); + int failCount = 0; + int successCount = 0; + long totalResponseTime = 0; + List behaviorResults = new ArrayList( + scenarioContext.getResults()); + long maxDate = 0; + int validCount = 0; + for (BehaviorResult behaviorResult : behaviorResults) { + if (behaviorResult.getEndDate().getTime() > maxDate) { + maxDate = behaviorResult.getEndDate().getTime(); + } + if (behaviorResult.isSuccess()) { + successCount++; + } else { + failCount++; + } + if (!behaviorResult.getPluginName().contains("Timer")) { + totalResponseTime += behaviorResult.getResponseTime(); + validCount++; + } + TestResultItem testResultItem = new TestResultItem(); + testResultItem + .setBehaviorName(behaviorResult.getBehaviorName()); + testResultItem.setEndDate(behaviorResult.getEndDate()); + testResultItem.setId(behaviorResult.getId()); + testResultItem.setPluginId(behaviorResult.getPluginId()); + testResultItem.setPluginName(behaviorResult.getPluginName()); + testResultItem + .setResponseTime(behaviorResult.getResponseTime()); + testResultItem.setStartDate(behaviorResult.getStartDate()); + testResultItem.setSuccess(behaviorResult.isSuccess()); + testResult.getResults().add(testResultItem); + } + testResult.setAverageResponseTime((totalResponseTime + 0.0) + / validCount); + testResult.setElapsedTime(maxDate + - testResult.getStartDate().getTime()); + testResult.setFailCount(failCount); + testResult.setSuccessCount(successCount); + testResult.setFinishedCount(behaviorResults.size()); + Marshaller marshaller = JAXBContext.newInstance( + testResult.getClass()).createMarshaller(); + marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); + FileWriter fileWriter = new FileWriter(new File(this.getPath() + + "/" + runId.toString() + ".xml")); + marshaller.marshal(testResult, fileWriter); + fileWriter.close(); + } catch (Exception e) { + e.printStackTrace(); + } + } } diff --git a/src/main/java/org/bench4q/agent/scenario/TestResult.java b/src/main/java/org/bench4q/agent/scenario/TestResult.java new file mode 100644 index 00000000..26c000f3 --- /dev/null +++ b/src/main/java/org/bench4q/agent/scenario/TestResult.java @@ -0,0 +1,111 @@ +package org.bench4q.agent.scenario; + +import java.io.Serializable; +import java.util.Date; +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 = "testResult") +public class TestResult implements Serializable { + private static final long serialVersionUID = -370091935554266546L; + private UUID runId; + private int poolSize; + private int totalCount; + private Date startDate; + private long elapsedTime; + private int successCount; + private int failCount; + private int finishedCount; + private double averageResponseTime; + private List results; + + @XmlElement + public UUID getRunId() { + return runId; + } + + public void setRunId(UUID runId) { + this.runId = runId; + } + + @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; + } + + @XmlElement + public Date getStartDate() { + return startDate; + } + + public void setStartDate(Date startDate) { + this.startDate = startDate; + } + + public long getElapsedTime() { + return elapsedTime; + } + + public void setElapsedTime(long elapsedTime) { + this.elapsedTime = elapsedTime; + } + + public int getSuccessCount() { + return successCount; + } + + public void setSuccessCount(int successCount) { + this.successCount = successCount; + } + + public int getFailCount() { + return failCount; + } + + public void setFailCount(int failCount) { + this.failCount = failCount; + } + + public int getFinishedCount() { + return finishedCount; + } + + public void setFinishedCount(int finishedCount) { + this.finishedCount = finishedCount; + } + + public double getAverageResponseTime() { + return averageResponseTime; + } + + public void setAverageResponseTime(double averageResponseTime) { + this.averageResponseTime = averageResponseTime; + } + + @XmlElementWrapper(name = "results") + @XmlElement(name = "result") + public List getResults() { + return results; + } + + public void setResults(List results) { + this.results = results; + } +} diff --git a/src/main/java/org/bench4q/agent/scenario/TestResultItem.java b/src/main/java/org/bench4q/agent/scenario/TestResultItem.java new file mode 100644 index 00000000..da9e9271 --- /dev/null +++ b/src/main/java/org/bench4q/agent/scenario/TestResultItem.java @@ -0,0 +1,93 @@ +package org.bench4q.agent.scenario; + +import java.io.Serializable; +import java.util.Date; +import java.util.UUID; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; + +@XmlRootElement(name = "testResultItem") +public class TestResultItem implements Serializable { + private static final long serialVersionUID = 3307951299814477213L; + private UUID id; + private String pluginId; + private String pluginName; + private String behaviorName; + private Date startDate; + private Date endDate; + private long responseTime; + private boolean success; + + @XmlElement + public UUID getId() { + return id; + } + + public void setId(UUID id) { + this.id = id; + } + + @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; + } +} diff --git a/src/test/java/org/bench4q/agent/test/RunScenarioTest.java b/src/test/java/org/bench4q/agent/test/RunScenarioTest.java index c2f10c91..518e6afd 100644 --- a/src/test/java/org/bench4q/agent/test/RunScenarioTest.java +++ b/src/test/java/org/bench4q/agent/test/RunScenarioTest.java @@ -23,7 +23,7 @@ public class RunScenarioTest { public void testRunScenario() { try { RunScenarioModel runScenarioModel = new RunScenarioModel(); - runScenarioModel.setTotalCount(10000); + runScenarioModel.setTotalCount(1000); runScenarioModel.setPoolSize(100); runScenarioModel.setUsePlugins(new ArrayList()); runScenarioModel @@ -73,7 +73,6 @@ public class RunScenarioTest { runScenarioModel.getUserBehaviors().add(postUserBehaviorModel); Marshaller marshaller = JAXBContext.newInstance( runScenarioModel.getClass()).createMarshaller(); - ; StringWriter stringWriter = new StringWriter(); marshaller.marshal(runScenarioModel, stringWriter); String url = "http://localhost:6565/test/run"; From e6b57ec27adae01224014ebb98c27f1dacba5b6e Mon Sep 17 00:00:00 2001 From: Zhen Tang Date: Tue, 2 Jul 2013 22:59:12 +0800 Subject: [PATCH 029/196] some refactoring. --- .../org/bench4q/agent/api/TestController.java | 2 +- .../{plugin => scenario}/BehaviorResult.java | 2 +- .../agent/scenario/ScenarioContext.java | 1 - .../agent/scenario/ScenarioEngine.java | 146 +++++++++++------- 4 files changed, 90 insertions(+), 61 deletions(-) rename src/main/java/org/bench4q/agent/{plugin => scenario}/BehaviorResult.java (91%) diff --git a/src/main/java/org/bench4q/agent/api/TestController.java b/src/main/java/org/bench4q/agent/api/TestController.java index be332f7a..d063c94d 100644 --- a/src/main/java/org/bench4q/agent/api/TestController.java +++ b/src/main/java/org/bench4q/agent/api/TestController.java @@ -15,7 +15,7 @@ import org.bench4q.agent.api.model.TestDetailModel; import org.bench4q.agent.api.model.TestDetailStatusModel; import org.bench4q.agent.api.model.UsePluginModel; import org.bench4q.agent.api.model.UserBehaviorModel; -import org.bench4q.agent.plugin.BehaviorResult; +import org.bench4q.agent.scenario.BehaviorResult; import org.bench4q.agent.scenario.Parameter; import org.bench4q.agent.scenario.Scenario; import org.bench4q.agent.scenario.ScenarioContext; diff --git a/src/main/java/org/bench4q/agent/plugin/BehaviorResult.java b/src/main/java/org/bench4q/agent/scenario/BehaviorResult.java similarity index 91% rename from src/main/java/org/bench4q/agent/plugin/BehaviorResult.java rename to src/main/java/org/bench4q/agent/scenario/BehaviorResult.java index d1fe0cbe..6e38cfc1 100644 --- a/src/main/java/org/bench4q/agent/plugin/BehaviorResult.java +++ b/src/main/java/org/bench4q/agent/scenario/BehaviorResult.java @@ -1,4 +1,4 @@ -package org.bench4q.agent.plugin; +package org.bench4q.agent.scenario; import java.util.Date; import java.util.UUID; diff --git a/src/main/java/org/bench4q/agent/scenario/ScenarioContext.java b/src/main/java/org/bench4q/agent/scenario/ScenarioContext.java index 35ffde4e..fdf7b917 100644 --- a/src/main/java/org/bench4q/agent/scenario/ScenarioContext.java +++ b/src/main/java/org/bench4q/agent/scenario/ScenarioContext.java @@ -4,7 +4,6 @@ import java.util.Date; import java.util.List; import java.util.concurrent.ExecutorService; -import org.bench4q.agent.plugin.BehaviorResult; public class ScenarioContext { private int poolSize; diff --git a/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java b/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java index ab1100f4..c225d620 100644 --- a/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java +++ b/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java @@ -2,6 +2,7 @@ package org.bench4q.agent.scenario; import java.io.File; import java.io.FileWriter; +import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.Date; @@ -13,9 +14,10 @@ import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import javax.xml.bind.JAXBContext; +import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; +import javax.xml.bind.PropertyException; -import org.bench4q.agent.plugin.BehaviorResult; import org.bench4q.agent.plugin.Plugin; import org.bench4q.agent.plugin.PluginManager; import org.springframework.beans.factory.annotation.Autowired; @@ -102,12 +104,14 @@ public class ScenarioEngine { behaviorParameters .put(parameter.getKey(), parameter.getValue()); } - BehaviorResult result = new BehaviorResult(); - result.setId(UUID.randomUUID()); - result.setStartDate(new Date(System.currentTimeMillis())); + Date startDate = new Date(System.currentTimeMillis()); boolean success = (Boolean) this.getPluginManager().doBehavior( plugin, behaviorName, behaviorParameters); - result.setEndDate(new Date(System.currentTimeMillis())); + Date endDate = new Date(System.currentTimeMillis()); + BehaviorResult result = new BehaviorResult(); + result.setId(UUID.randomUUID()); + result.setStartDate(startDate); + result.setEndDate(endDate); result.setSuccess(success); result.setResponseTime(result.getEndDate().getTime() - result.getStartDate().getTime()); @@ -125,66 +129,92 @@ public class ScenarioEngine { } public void saveTestResults(UUID runId) { + ScenarioContext scenarioContext = this.getRunningTests().get(runId); + if (scenarioContext == null) { + return; + } + List results = new ArrayList(); + List behaviorResults = new ArrayList( + scenarioContext.getResults()); + int failCount = 0; + int successCount = 0; + long totalResponseTime = 0; + long maxDate = 0; + int validCount = 0; + for (BehaviorResult behaviorResult : behaviorResults) { + if (behaviorResult.getEndDate().getTime() > maxDate) { + maxDate = behaviorResult.getEndDate().getTime(); + } + if (behaviorResult.isSuccess()) { + successCount++; + } else { + failCount++; + } + if (!behaviorResult.getPluginName().contains("Timer")) { + totalResponseTime += behaviorResult.getResponseTime(); + validCount++; + } + results.add(buildTestResultItem(behaviorResult)); + } + TestResult testResult = buildTestResult(runId, scenarioContext, + results, behaviorResults, failCount, successCount, + totalResponseTime, maxDate, validCount); + doSaveTestResults(runId, testResult); + } + + private void doSaveTestResults(UUID runId, TestResult testResult) { + FileWriter fileWriter = null; try { - ScenarioContext scenarioContext = this.getRunningTests().get(runId); - if (scenarioContext == null) { - return; - } - TestResult testResult = new TestResult(); - testResult.setRunId(runId); - testResult.setPoolSize(scenarioContext.getPoolSize()); - testResult.setResults(new ArrayList()); - testResult.setStartDate(scenarioContext.getStartDate()); - testResult.setTotalCount(scenarioContext.getTotalCount()); - int failCount = 0; - int successCount = 0; - long totalResponseTime = 0; - List behaviorResults = new ArrayList( - scenarioContext.getResults()); - long maxDate = 0; - int validCount = 0; - for (BehaviorResult behaviorResult : behaviorResults) { - if (behaviorResult.getEndDate().getTime() > maxDate) { - maxDate = behaviorResult.getEndDate().getTime(); - } - if (behaviorResult.isSuccess()) { - successCount++; - } else { - failCount++; - } - if (!behaviorResult.getPluginName().contains("Timer")) { - totalResponseTime += behaviorResult.getResponseTime(); - validCount++; - } - TestResultItem testResultItem = new TestResultItem(); - testResultItem - .setBehaviorName(behaviorResult.getBehaviorName()); - testResultItem.setEndDate(behaviorResult.getEndDate()); - testResultItem.setId(behaviorResult.getId()); - testResultItem.setPluginId(behaviorResult.getPluginId()); - testResultItem.setPluginName(behaviorResult.getPluginName()); - testResultItem - .setResponseTime(behaviorResult.getResponseTime()); - testResultItem.setStartDate(behaviorResult.getStartDate()); - testResultItem.setSuccess(behaviorResult.isSuccess()); - testResult.getResults().add(testResultItem); - } - testResult.setAverageResponseTime((totalResponseTime + 0.0) - / validCount); - testResult.setElapsedTime(maxDate - - testResult.getStartDate().getTime()); - testResult.setFailCount(failCount); - testResult.setSuccessCount(successCount); - testResult.setFinishedCount(behaviorResults.size()); Marshaller marshaller = JAXBContext.newInstance( testResult.getClass()).createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); - FileWriter fileWriter = new FileWriter(new File(this.getPath() - + "/" + runId.toString() + ".xml")); + fileWriter = new FileWriter(new File(this.getPath() + "/" + + runId.toString() + ".xml")); marshaller.marshal(testResult, fileWriter); - fileWriter.close(); } catch (Exception e) { e.printStackTrace(); + } finally { + if (fileWriter != null) { + try { + fileWriter.close(); + } catch (Exception e) { + e.printStackTrace(); + } + } } } + + private TestResult buildTestResult(UUID runId, + ScenarioContext scenarioContext, List results, + List behaviorResults, int failCount, + int successCount, long totalResponseTime, long maxDate, + int validCount) { + TestResult testResult = new TestResult(); + testResult.setResults(results); + testResult.setStartDate(scenarioContext.getStartDate()); + testResult.setTotalCount(scenarioContext.getTotalCount()); + testResult.setRunId(runId); + testResult.setPoolSize(scenarioContext.getPoolSize()); + testResult.setAverageResponseTime((totalResponseTime + 0.0) + / validCount); + testResult + .setElapsedTime(maxDate - testResult.getStartDate().getTime()); + testResult.setFailCount(failCount); + testResult.setSuccessCount(successCount); + testResult.setFinishedCount(behaviorResults.size()); + return testResult; + } + + private TestResultItem buildTestResultItem(BehaviorResult behaviorResult) { + TestResultItem testResultItem = new TestResultItem(); + testResultItem.setBehaviorName(behaviorResult.getBehaviorName()); + testResultItem.setEndDate(behaviorResult.getEndDate()); + testResultItem.setId(behaviorResult.getId()); + testResultItem.setPluginId(behaviorResult.getPluginId()); + testResultItem.setPluginName(behaviorResult.getPluginName()); + testResultItem.setResponseTime(behaviorResult.getResponseTime()); + testResultItem.setStartDate(behaviorResult.getStartDate()); + testResultItem.setSuccess(behaviorResult.isSuccess()); + return testResultItem; + } } From 14e01cb3235b4a44d44053f04e04a9b26adaf9e8 Mon Sep 17 00:00:00 2001 From: Zhen Tang Date: Tue, 2 Jul 2013 23:14:50 +0800 Subject: [PATCH 030/196] some refactoring. --- .../bench4q/agent/api/PluginController.java | 59 ++++++---- .../org/bench4q/agent/api/TestController.java | 4 +- .../bench4q/agent/plugin/PluginManager.java | 91 ++++++++++------ .../agent/scenario/ScenarioEngine.java | 102 +++++++++++------- 4 files changed, 158 insertions(+), 98 deletions(-) diff --git a/src/main/java/org/bench4q/agent/api/PluginController.java b/src/main/java/org/bench4q/agent/api/PluginController.java index fb6d8e46..a2ff96b4 100644 --- a/src/main/java/org/bench4q/agent/api/PluginController.java +++ b/src/main/java/org/bench4q/agent/api/PluginController.java @@ -38,32 +38,45 @@ public class PluginController { PluginInfoListModel pluginInfoListModel = new PluginInfoListModel(); pluginInfoListModel.setPlugins(new ArrayList()); for (PluginInfo pluginInfo : pluginInfos) { - PluginInfoModel pluginInfoModel = new PluginInfoModel(); - pluginInfoModel.setName(pluginInfo.getName()); - pluginInfoModel.setParameters(new ArrayList()); - for (ParameterInfo param : pluginInfo.getParameters()) { - ParameterInfoModel model = new ParameterInfoModel(); - model.setName(param.getName()); - model.setType(param.getType()); - pluginInfoModel.getParameters().add(model); - } - pluginInfoModel.setBehaviors(new ArrayList()); - for (BehaviorInfo behaviorInfo : pluginInfo.getBehaviors()) { - BehaviorInfoModel behaviorInfoModel = new BehaviorInfoModel(); - behaviorInfoModel.setName(behaviorInfo.getName()); - behaviorInfoModel - .setParameters(new ArrayList()); - for (ParameterInfo param : behaviorInfo.getParameters()) { - ParameterInfoModel model = new ParameterInfoModel(); - model.setName(param.getName()); - model.setType(param.getType()); - behaviorInfoModel.getParameters().add(model); - } - pluginInfoModel.getBehaviors().add(behaviorInfoModel); - } + PluginInfoModel pluginInfoModel = buildPluginInfoModel(pluginInfo); pluginInfoListModel.getPlugins().add(pluginInfoModel); } return pluginInfoListModel; } + private PluginInfoModel buildPluginInfoModel(PluginInfo pluginInfo) { + PluginInfoModel pluginInfoModel = new PluginInfoModel(); + pluginInfoModel.setName(pluginInfo.getName()); + pluginInfoModel.setParameters(new ArrayList()); + for (ParameterInfo param : pluginInfo.getParameters()) { + ParameterInfoModel model = buildParameterInfoModel(param); + pluginInfoModel.getParameters().add(model); + } + pluginInfoModel.setBehaviors(new ArrayList()); + for (BehaviorInfo behaviorInfo : pluginInfo.getBehaviors()) { + BehaviorInfoModel behaviorInfoModel = buildBehaviorInfoModel(behaviorInfo); + pluginInfoModel.getBehaviors().add(behaviorInfoModel); + } + return pluginInfoModel; + } + + private BehaviorInfoModel buildBehaviorInfoModel(BehaviorInfo behaviorInfo) { + BehaviorInfoModel behaviorInfoModel = new BehaviorInfoModel(); + behaviorInfoModel.setName(behaviorInfo.getName()); + behaviorInfoModel + .setParameters(new ArrayList()); + for (ParameterInfo param : behaviorInfo.getParameters()) { + ParameterInfoModel model = buildParameterInfoModel(param); + behaviorInfoModel.getParameters().add(model); + } + return behaviorInfoModel; + } + + private ParameterInfoModel buildParameterInfoModel(ParameterInfo param) { + ParameterInfoModel model = new ParameterInfoModel(); + model.setName(param.getName()); + model.setType(param.getType()); + return model; + } + } diff --git a/src/main/java/org/bench4q/agent/api/TestController.java b/src/main/java/org/bench4q/agent/api/TestController.java index d063c94d..f8b849d5 100644 --- a/src/main/java/org/bench4q/agent/api/TestController.java +++ b/src/main/java/org/bench4q/agent/api/TestController.java @@ -63,15 +63,15 @@ public class TestController { usePlugin.setName(usePluginModel.getName()); usePlugin.setParameters(new Parameter[usePluginModel .getParameters().size()]); - scenario.getUsePlugins()[i] = usePlugin; for (j = 0; j < usePluginModel.getParameters().size(); j++) { ParameterModel parameterModel = usePluginModel.getParameters() .get(j); Parameter parameter = new Parameter(); parameter.setKey(parameterModel.getKey()); parameter.setValue(parameterModel.getValue()); - scenario.getUsePlugins()[i].getParameters()[j] = parameter; + usePlugin.getParameters()[j] = parameter; } + scenario.getUsePlugins()[i] = usePlugin; } for (i = 0; i < runScenarioModel.getUserBehaviors().size(); i++) { UserBehaviorModel userBehaviorModel = runScenarioModel diff --git a/src/main/java/org/bench4q/agent/plugin/PluginManager.java b/src/main/java/org/bench4q/agent/plugin/PluginManager.java index 70c87621..a26dd29f 100644 --- a/src/main/java/org/bench4q/agent/plugin/PluginManager.java +++ b/src/main/java/org/bench4q/agent/plugin/PluginManager.java @@ -12,6 +12,7 @@ import javassist.CtClass; import javassist.CtConstructor; import javassist.CtMethod; import javassist.Modifier; +import javassist.NotFoundException; import javassist.bytecode.CodeAttribute; import javassist.bytecode.LocalVariableAttribute; import javassist.bytecode.MethodInfo; @@ -90,12 +91,8 @@ public class PluginManager { pluginInfo.setBehaviors(new BehaviorInfo[behaviors.length]); int i = 0; for (i = 0; i < behaviors.length; i++) { - BehaviorInfo behaviorInfo = new BehaviorInfo(); CtMethod behaviorMethod = behaviors[i]; - behaviorInfo.setName(((Behavior) behaviorMethod - .getAnnotation(Behavior.class)).value()); - behaviorInfo.setParameters(this - .getParameters(behaviorMethod)); + BehaviorInfo behaviorInfo = buildBehaviorInfo(behaviorMethod); pluginInfo.getBehaviors()[i] = behaviorInfo; } ret.add(pluginInfo); @@ -107,6 +104,15 @@ public class PluginManager { } } + private BehaviorInfo buildBehaviorInfo(CtMethod behaviorMethod) + throws ClassNotFoundException { + BehaviorInfo behaviorInfo = new BehaviorInfo(); + behaviorInfo.setName(((Behavior) behaviorMethod + .getAnnotation(Behavior.class)).value()); + behaviorInfo.setParameters(this.getParameters(behaviorMethod)); + return behaviorInfo; + } + private ParameterInfo[] getParameters(CtBehavior behavior) { try { MethodInfo methodInfo = behavior.getMethodInfo(); @@ -118,11 +124,8 @@ public class PluginManager { int i; int pos = Modifier.isStatic(behavior.getModifiers()) ? 0 : 1; for (i = 0; i < parameterCount; i++) { - ParameterInfo parameterInfo = new ParameterInfo(); - parameterInfo.setName(localVariableAttribute.variableName(i - + pos)); - parameterInfo - .setType(behavior.getParameterTypes()[i].getName()); + ParameterInfo parameterInfo = buildParameterInfo(behavior, + localVariableAttribute, i, pos); parameterNames[i] = parameterInfo; } return parameterNames; @@ -132,6 +135,15 @@ public class PluginManager { } } + private ParameterInfo buildParameterInfo(CtBehavior behavior, + LocalVariableAttribute localVariableAttribute, int i, int pos) + throws NotFoundException { + ParameterInfo parameterInfo = new ParameterInfo(); + parameterInfo.setName(localVariableAttribute.variableName(i + pos)); + parameterInfo.setType(behavior.getParameterTypes()[i].getName()); + return parameterInfo; + } + private CtMethod[] getBehaviors(CtClass plugin) { try { CtMethod[] ctMethods = plugin.getMethods(); @@ -192,32 +204,11 @@ public class PluginManager { public Object doBehavior(Object plugin, String behaviorName, Map parameters) { try { - ClassPool classPool = ClassPool.getDefault(); - CtClass ctClass = classPool.get(plugin.getClass() - .getCanonicalName()); - CtMethod[] ctMethods = ctClass.getMethods(); - CtMethod ctMethod = null; - - int i = 0; - for (i = 0; i < ctMethods.length; i++) { - if (ctMethods[i].hasAnnotation(Behavior.class)) { - if (((Behavior) ctMethods[i].getAnnotation(Behavior.class)) - .value().equals(behaviorName)) { - ctMethod = ctMethods[i]; - break; - } - } - } + CtMethod ctMethod = findCtMethod(plugin, behaviorName); if (ctMethod == null) { return null; } - Method[] methods = plugin.getClass().getMethods(); - Method method = null; - for (i = 0; i < methods.length; i++) { - if (methods[i].getName().equals(ctMethod.getName())) { - method = methods[i]; - } - } + Method method = findMethod(plugin, ctMethod); if (method == null) { return null; } @@ -228,4 +219,38 @@ public class PluginManager { return null; } } + + private Method findMethod(Object plugin, CtMethod ctMethod) { + int i; + Method[] methods = plugin.getClass().getMethods(); + Method method = null; + for (i = 0; i < methods.length; i++) { + if (methods[i].getName().equals(ctMethod.getName())) { + method = methods[i]; + } + } + return method; + } + + private CtMethod findCtMethod(Object plugin, String behaviorName) { + try { + ClassPool classPool = ClassPool.getDefault(); + CtClass ctClass = classPool.get(plugin.getClass() + .getCanonicalName()); + CtMethod[] ctMethods = ctClass.getMethods(); + int i = 0; + for (i = 0; i < ctMethods.length; i++) { + if (ctMethods[i].hasAnnotation(Behavior.class)) { + if (((Behavior) ctMethods[i].getAnnotation(Behavior.class)) + .value().equals(behaviorName)) { + return ctMethods[i]; + } + } + } + return null; + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } } diff --git a/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java b/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java index c225d620..db59fec3 100644 --- a/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java +++ b/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java @@ -2,7 +2,6 @@ package org.bench4q.agent.scenario; import java.io.File; import java.io.FileWriter; -import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.Date; @@ -14,9 +13,7 @@ import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import javax.xml.bind.JAXBContext; -import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; -import javax.xml.bind.PropertyException; import org.bench4q.agent.plugin.Plugin; import org.bench4q.agent.plugin.PluginManager; @@ -52,19 +49,13 @@ public class ScenarioEngine { public void runScenario(UUID runId, final Scenario scenario, int poolSize, int totalCount) { try { - ScenarioContext scenarioContext = new ScenarioContext(); - scenarioContext.setScenario(scenario); - scenarioContext.setTotalCount(totalCount - * scenario.getUserBehaviors().length); - scenarioContext.setPoolSize(poolSize); - scenarioContext.setStartDate(new Date(System.currentTimeMillis())); ExecutorService executorService = Executors .newFixedThreadPool(poolSize); - scenarioContext.setExecutorService(executorService); - int i; final List ret = Collections .synchronizedList(new ArrayList()); - scenarioContext.setResults(ret); + ScenarioContext scenarioContext = buildScenarioContext(scenario, + poolSize, totalCount, executorService, ret); + int i; this.getRunningTests().put(runId, scenarioContext); Runnable runnable = new Runnable() { public void run() { @@ -80,8 +71,67 @@ public class ScenarioEngine { } } + private ScenarioContext buildScenarioContext(final Scenario scenario, + int poolSize, int totalCount, ExecutorService executorService, + final List ret) { + ScenarioContext scenarioContext = new ScenarioContext(); + scenarioContext.setScenario(scenario); + scenarioContext.setTotalCount(totalCount + * scenario.getUserBehaviors().length); + scenarioContext.setPoolSize(poolSize); + scenarioContext.setStartDate(new Date(System.currentTimeMillis())); + scenarioContext.setExecutorService(executorService); + scenarioContext.setResults(ret); + return scenarioContext; + } + private List doRunScenario(Scenario scenario) { Map plugins = new HashMap(); + preparePlugins(scenario, plugins); + + List ret = new ArrayList(); + for (UserBehavior userBehavior : scenario.getUserBehaviors()) { + Object plugin = plugins.get(userBehavior.getUse()); + String behaviorName = userBehavior.getName(); + Map behaviorParameters = prepareBehaviorParameters(userBehavior); + Date startDate = new Date(System.currentTimeMillis()); + boolean success = (Boolean) this.getPluginManager().doBehavior( + plugin, behaviorName, behaviorParameters); + Date endDate = new Date(System.currentTimeMillis()); + BehaviorResult result = buildBehaviorResult(userBehavior, plugin, + behaviorName, startDate, success, endDate); + ret.add(result); + } + return ret; + } + + private BehaviorResult buildBehaviorResult(UserBehavior userBehavior, + Object plugin, String behaviorName, Date startDate, + boolean success, Date endDate) { + BehaviorResult result = new BehaviorResult(); + result.setId(UUID.randomUUID()); + result.setStartDate(startDate); + result.setEndDate(endDate); + result.setSuccess(success); + result.setResponseTime(result.getEndDate().getTime() + - result.getStartDate().getTime()); + result.setBehaviorName(behaviorName); + result.setPluginId(userBehavior.getUse()); + result.setPluginName(plugin.getClass().getAnnotation(Plugin.class) + .value()); + return result; + } + + private Map prepareBehaviorParameters( + UserBehavior userBehavior) { + Map behaviorParameters = new HashMap(); + for (Parameter parameter : userBehavior.getParameters()) { + behaviorParameters.put(parameter.getKey(), parameter.getValue()); + } + return behaviorParameters; + } + + private void preparePlugins(Scenario scenario, Map plugins) { for (UsePlugin usePlugin : scenario.getUsePlugins()) { String pluginId = usePlugin.getId(); Class pluginClass = this.getPluginManager().getPlugins() @@ -94,34 +144,6 @@ public class ScenarioEngine { pluginClass, initParameters); plugins.put(pluginId, plugin); } - - List ret = new ArrayList(); - for (UserBehavior userBehavior : scenario.getUserBehaviors()) { - Object plugin = plugins.get(userBehavior.getUse()); - String behaviorName = userBehavior.getName(); - Map behaviorParameters = new HashMap(); - for (Parameter parameter : userBehavior.getParameters()) { - behaviorParameters - .put(parameter.getKey(), parameter.getValue()); - } - Date startDate = new Date(System.currentTimeMillis()); - boolean success = (Boolean) this.getPluginManager().doBehavior( - plugin, behaviorName, behaviorParameters); - Date endDate = new Date(System.currentTimeMillis()); - BehaviorResult result = new BehaviorResult(); - result.setId(UUID.randomUUID()); - result.setStartDate(startDate); - result.setEndDate(endDate); - result.setSuccess(success); - result.setResponseTime(result.getEndDate().getTime() - - result.getStartDate().getTime()); - result.setBehaviorName(behaviorName); - result.setPluginId(userBehavior.getUse()); - result.setPluginName(plugin.getClass().getAnnotation(Plugin.class) - .value()); - ret.add(result); - } - return ret; } public String getPath() { From e855a32649c2993c481d944b44ab01e5dd757e9b Mon Sep 17 00:00:00 2001 From: Zhen Tang Date: Tue, 2 Jul 2013 23:27:16 +0800 Subject: [PATCH 031/196] some refactoring. --- .../org/bench4q/agent/api/TestController.java | 113 +++++++++++------- 1 file changed, 72 insertions(+), 41 deletions(-) diff --git a/src/main/java/org/bench4q/agent/api/TestController.java b/src/main/java/org/bench4q/agent/api/TestController.java index f8b849d5..f945c900 100644 --- a/src/main/java/org/bench4q/agent/api/TestController.java +++ b/src/main/java/org/bench4q/agent/api/TestController.java @@ -48,56 +48,87 @@ public class TestController { @ResponseBody public RunScenarioResultModel run( @RequestBody RunScenarioModel runScenarioModel) { + Scenario scenario = extractScenario(runScenarioModel); + UUID runId = UUID.randomUUID(); + this.getScenarioEngine().runScenario(runId, scenario, + runScenarioModel.getPoolSize(), + runScenarioModel.getTotalCount()); + RunScenarioResultModel runScenarioResultModel = new RunScenarioResultModel(); + runScenarioResultModel.setRunId(runId); + return runScenarioResultModel; + } + + private Scenario extractScenario(RunScenarioModel runScenarioModel) { Scenario scenario = new Scenario(); scenario.setUsePlugins(new UsePlugin[runScenarioModel.getUsePlugins() .size()]); scenario.setUserBehaviors(new UserBehavior[runScenarioModel .getUserBehaviors().size()]); - int i = 0; - int j = 0; + extractUsePlugins(runScenarioModel, scenario); + extractUserBehaviors(runScenarioModel, scenario); + return scenario; + } + + private void extractUserBehaviors(RunScenarioModel runScenarioModel, + Scenario scenario) { + int i; + List userBehaviorModels = runScenarioModel + .getUserBehaviors(); + for (i = 0; i < runScenarioModel.getUserBehaviors().size(); i++) { + UserBehaviorModel userBehaviorModel = userBehaviorModels.get(i); + UserBehavior userBehavior = extractUserBehavior(userBehaviorModel); + scenario.getUserBehaviors()[i] = userBehavior; + } + } + + private void extractUsePlugins(RunScenarioModel runScenarioModel, + Scenario scenario) { + int i; + List usePluginModels = runScenarioModel.getUsePlugins(); for (i = 0; i < runScenarioModel.getUsePlugins().size(); i++) { - UsePluginModel usePluginModel = runScenarioModel.getUsePlugins() - .get(i); - UsePlugin usePlugin = new UsePlugin(); - usePlugin.setId(usePluginModel.getId()); - usePlugin.setName(usePluginModel.getName()); - usePlugin.setParameters(new Parameter[usePluginModel - .getParameters().size()]); - for (j = 0; j < usePluginModel.getParameters().size(); j++) { - ParameterModel parameterModel = usePluginModel.getParameters() - .get(j); - Parameter parameter = new Parameter(); - parameter.setKey(parameterModel.getKey()); - parameter.setValue(parameterModel.getValue()); - usePlugin.getParameters()[j] = parameter; - } + UsePluginModel usePluginModel = usePluginModels.get(i); + UsePlugin usePlugin = extractUsePlugin(usePluginModel); scenario.getUsePlugins()[i] = usePlugin; } - for (i = 0; i < runScenarioModel.getUserBehaviors().size(); i++) { - UserBehaviorModel userBehaviorModel = runScenarioModel - .getUserBehaviors().get(i); - UserBehavior userBehavior = new UserBehavior(); - userBehavior.setName(userBehaviorModel.getName()); - userBehavior.setUse(userBehaviorModel.getUse()); - userBehavior.setParameters(new Parameter[userBehaviorModel - .getParameters().size()]); - scenario.getUserBehaviors()[i] = userBehavior; - for (j = 0; j < userBehaviorModel.getParameters().size(); j++) { - ParameterModel parameterModel = userBehaviorModel - .getParameters().get(j); - Parameter parameter = new Parameter(); - parameter.setKey(parameterModel.getKey()); - parameter.setValue(parameterModel.getValue()); - scenario.getUserBehaviors()[i].getParameters()[j] = parameter; - } - } + } - RunScenarioResultModel runScenarioResultModel = new RunScenarioResultModel(); - runScenarioResultModel.setRunId(UUID.randomUUID()); - this.getScenarioEngine().runScenario(runScenarioResultModel.getRunId(), - scenario, runScenarioModel.getPoolSize(), - runScenarioModel.getTotalCount()); - return runScenarioResultModel; + private UserBehavior extractUserBehavior(UserBehaviorModel userBehaviorModel) { + UserBehavior userBehavior = new UserBehavior(); + userBehavior.setName(userBehaviorModel.getName()); + userBehavior.setUse(userBehaviorModel.getUse()); + userBehavior.setParameters(new Parameter[userBehaviorModel + .getParameters().size()]); + int k = 0; + for (k = 0; k < userBehaviorModel.getParameters().size(); k++) { + ParameterModel parameterModel = userBehaviorModel.getParameters() + .get(k); + Parameter parameter = extractParameter(parameterModel); + userBehavior.getParameters()[k] = parameter; + } + return userBehavior; + } + + private UsePlugin extractUsePlugin(UsePluginModel usePluginModel) { + UsePlugin usePlugin = new UsePlugin(); + usePlugin.setId(usePluginModel.getId()); + usePlugin.setName(usePluginModel.getName()); + usePlugin.setParameters(new Parameter[usePluginModel.getParameters() + .size()]); + int k = 0; + for (k = 0; k < usePluginModel.getParameters().size(); k++) { + ParameterModel parameterModel = usePluginModel.getParameters().get( + k); + Parameter parameter = extractParameter(parameterModel); + usePlugin.getParameters()[k] = parameter; + } + return usePlugin; + } + + private Parameter extractParameter(ParameterModel parameterModel) { + Parameter parameter = new Parameter(); + parameter.setKey(parameterModel.getKey()); + parameter.setValue(parameterModel.getValue()); + return parameter; } @RequestMapping(value = "/detail/{runId}", method = RequestMethod.GET) From 8a1a5a8cac858d2902936dfe59cdecac8c25a8c9 Mon Sep 17 00:00:00 2001 From: Zhen Tang Date: Wed, 3 Jul 2013 23:10:01 +0800 Subject: [PATCH 032/196] hdfs service added. --- pom.xml | 5 + .../bench4q/agent/storage/HdfsService.java | 138 ++++++++++++++++++ 2 files changed, 143 insertions(+) create mode 100644 src/main/java/org/bench4q/agent/storage/HdfsService.java diff --git a/pom.xml b/pom.xml index 3b566634..5e033447 100644 --- a/pom.xml +++ b/pom.xml @@ -42,6 +42,11 @@ javassist 3.18.0-GA + + org.apache.hadoop + hadoop-core + 1.1.2 + bench4q-agent diff --git a/src/main/java/org/bench4q/agent/storage/HdfsService.java b/src/main/java/org/bench4q/agent/storage/HdfsService.java new file mode 100644 index 00000000..fcb33f84 --- /dev/null +++ b/src/main/java/org/bench4q/agent/storage/HdfsService.java @@ -0,0 +1,138 @@ +package org.bench4q.agent.storage; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; + +import org.apache.hadoop.conf.Configuration; +import org.apache.hadoop.fs.FSDataInputStream; +import org.apache.hadoop.fs.FSDataOutputStream; +import org.apache.hadoop.fs.FileStatus; +import org.apache.hadoop.fs.FileSystem; +import org.apache.hadoop.fs.Path; +import org.apache.hadoop.io.IOUtils; +import org.springframework.stereotype.Component; + +@Component +public class HdfsService { + private FileSystem getFileSystem() throws IOException { + Configuration conf = new Configuration(); + return FileSystem.get(conf); + } + + public boolean uploadFile(String localPath, String remotePath) { + try { + FileSystem fs = this.getFileSystem(); + fs.copyFromLocalFile(new Path(localPath), new Path(remotePath)); + return true; + } catch (Exception e) { + e.printStackTrace(); + return false; + } + } + + public boolean writeFile(String content, String remotePath) { + try { + InputStream in = new ByteArrayInputStream(content.getBytes()); + FileSystem fs = this.getFileSystem(); + OutputStream out = fs.create(new Path(remotePath)); + IOUtils.copyBytes(in, out, 4096, true); + return true; + } catch (Exception e) { + e.printStackTrace(); + return false; + } + } + + public boolean downloadFile(String localPath, String remotePath) { + try { + FileSystem fs = this.getFileSystem(); + fs.copyToLocalFile(new Path(remotePath), new Path(localPath)); + return true; + } catch (Exception e) { + e.printStackTrace(); + return false; + } + } + + public String readFile(String remotePath) { + try { + FileSystem fs = this.getFileSystem(); + FSDataInputStream hdfsInStream = fs.open(new Path(remotePath)); + OutputStream out = new ByteArrayOutputStream(); + byte[] ioBuffer = new byte[1024]; + int readLen = hdfsInStream.read(ioBuffer); + while (-1 != readLen) { + out.write(ioBuffer, 0, readLen); + readLen = hdfsInStream.read(ioBuffer); + } + out.close(); + String ret = out.toString(); + hdfsInStream.close(); + return ret; + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } + + public boolean appendFile(String content, String remotePath) { + try { + FileSystem fs = this.getFileSystem(); + FSDataOutputStream out = fs.append(new Path(remotePath)); + int readLen = content.getBytes().length; + while (-1 != readLen) { + out.write(content.getBytes(), 0, readLen); + } + out.close(); + return true; + } catch (Exception e) { + e.printStackTrace(); + return false; + } + } + + public boolean deleteFile(String remotePath) { + try { + FileSystem fs = this.getFileSystem(); + return fs.delete(new Path(remotePath), false); + } catch (Exception e) { + e.printStackTrace(); + return false; + } + } + + public boolean deleteDirectory(String remotePath) { + try { + FileSystem fs = this.getFileSystem(); + return fs.delete(new Path(remotePath), true); + } catch (Exception e) { + e.printStackTrace(); + return false; + } + } + + public boolean renameFile(String fromPath, String toPath) { + try { + FileSystem fs = this.getFileSystem(); + return fs.rename(new Path(fromPath), new Path(toPath)); + } catch (Exception e) { + e.printStackTrace(); + return false; + } + } + + public FileStatus[] listFile(String remotePath) { + try { + FileSystem fs = this.getFileSystem(); + FileStatus[] fileList = fs.listStatus(new Path(remotePath)); + return fileList; + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } + +} From 3230a6bebeda7d21d636e8671e108461a66b0e01 Mon Sep 17 00:00:00 2001 From: Zhen Tang Date: Fri, 5 Jul 2013 11:35:31 +0800 Subject: [PATCH 033/196] hdfs storage tested. jar package configuration added. --- descriptor.xml | 25 ++++++++++++++++ pom.xml | 26 ++++++++++++++++ .../java/org/bench4q/agent/AgentServer.java | 5 ++-- .../agent/scenario/ScenarioEngine.java | 30 +++++++++++++------ .../{HdfsService.java => HdfsStorage.java} | 4 ++- .../agent/config}/application-context.xml | 0 .../bench4q/agent/test/RunScenarioTest.java | 6 ++-- 7 files changed, 81 insertions(+), 15 deletions(-) create mode 100644 descriptor.xml rename src/main/java/org/bench4q/agent/storage/{HdfsService.java => HdfsStorage.java} (92%) rename src/main/resources/{ => org/bench4q/agent/config}/application-context.xml (100%) diff --git a/descriptor.xml b/descriptor.xml new file mode 100644 index 00000000..276d32a3 --- /dev/null +++ b/descriptor.xml @@ -0,0 +1,25 @@ + + + jar-with-dependencies + + jar + + false + + + / + false + false + runtime + + + + + ${project.build.outputDirectory} + / + + + \ No newline at end of file diff --git a/pom.xml b/pom.xml index 5e033447..af774e3f 100644 --- a/pom.xml +++ b/pom.xml @@ -49,6 +49,32 @@ + + + maven-assembly-plugin + + + descriptor.xml + + false + + + org.bench4q.agent.Main + true + + + + + + make-assembly + package + + assembly + + + + + bench4q-agent \ No newline at end of file diff --git a/src/main/java/org/bench4q/agent/AgentServer.java b/src/main/java/org/bench4q/agent/AgentServer.java index f1940cd1..bfd0ac52 100644 --- a/src/main/java/org/bench4q/agent/AgentServer.java +++ b/src/main/java/org/bench4q/agent/AgentServer.java @@ -40,8 +40,9 @@ public class AgentServer { ServletContextHandler servletContextHandler = new ServletContextHandler(); ServletHolder servletHolder = servletContextHandler.addServlet( DispatcherServlet.class, "/"); - servletHolder.setInitParameter("contextConfigLocation", - "classpath*:/application-context.xml"); + servletHolder + .setInitParameter("contextConfigLocation", + "classpath*:/org/bench4q/agent/config/application-context.xml"); this.getServer().setHandler(servletContextHandler); this.getServer().start(); return true; diff --git a/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java b/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java index db59fec3..5103a7e4 100644 --- a/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java +++ b/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java @@ -1,7 +1,6 @@ package org.bench4q.agent.scenario; -import java.io.File; -import java.io.FileWriter; +import java.io.StringWriter; import java.util.ArrayList; import java.util.Collections; import java.util.Date; @@ -17,6 +16,7 @@ import javax.xml.bind.Marshaller; import org.bench4q.agent.plugin.Plugin; import org.bench4q.agent.plugin.PluginManager; +import org.bench4q.agent.storage.HdfsStorage; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @@ -24,6 +24,7 @@ import org.springframework.stereotype.Component; public class ScenarioEngine { private PluginManager pluginManager; private Map runningTests; + private HdfsStorage hdfsStorage; public ScenarioEngine() { this.setRunningTests(new HashMap()); @@ -38,6 +39,15 @@ public class ScenarioEngine { this.pluginManager = pluginManager; } + private HdfsStorage getHdfsStorage() { + return hdfsStorage; + } + + @Autowired + private void setHdfsStorage(HdfsStorage hdfsStorage) { + this.hdfsStorage = hdfsStorage; + } + public Map getRunningTests() { return runningTests; } @@ -147,7 +157,7 @@ public class ScenarioEngine { } public String getPath() { - return System.getProperty("user.dir"); + return "hdfs://133.133.12.21:9000/home/bench4q/results"; } public void saveTestResults(UUID runId) { @@ -185,20 +195,22 @@ public class ScenarioEngine { } private void doSaveTestResults(UUID runId, TestResult testResult) { - FileWriter fileWriter = null; + StringWriter stringWriter = null; try { Marshaller marshaller = JAXBContext.newInstance( testResult.getClass()).createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); - fileWriter = new FileWriter(new File(this.getPath() + "/" - + runId.toString() + ".xml")); - marshaller.marshal(testResult, fileWriter); + stringWriter = new StringWriter(); + String fileName = this.getPath() + "/" + runId.toString() + ".xml"; + marshaller.marshal(testResult, stringWriter); + String content = stringWriter.toString(); + this.getHdfsStorage().writeFile(content, fileName); } catch (Exception e) { e.printStackTrace(); } finally { - if (fileWriter != null) { + if (stringWriter != null) { try { - fileWriter.close(); + stringWriter.close(); } catch (Exception e) { e.printStackTrace(); } diff --git a/src/main/java/org/bench4q/agent/storage/HdfsService.java b/src/main/java/org/bench4q/agent/storage/HdfsStorage.java similarity index 92% rename from src/main/java/org/bench4q/agent/storage/HdfsService.java rename to src/main/java/org/bench4q/agent/storage/HdfsStorage.java index fcb33f84..4d3b6c69 100644 --- a/src/main/java/org/bench4q/agent/storage/HdfsService.java +++ b/src/main/java/org/bench4q/agent/storage/HdfsStorage.java @@ -16,9 +16,11 @@ import org.apache.hadoop.io.IOUtils; import org.springframework.stereotype.Component; @Component -public class HdfsService { +public class HdfsStorage { private FileSystem getFileSystem() throws IOException { Configuration conf = new Configuration(); + conf.set("mapred.jop.tracker", "hdfs://133.133.12.21:9001"); + conf.set("fs.default.name", "hdfs://133.133.12.21:9000"); return FileSystem.get(conf); } diff --git a/src/main/resources/application-context.xml b/src/main/resources/org/bench4q/agent/config/application-context.xml similarity index 100% rename from src/main/resources/application-context.xml rename to src/main/resources/org/bench4q/agent/config/application-context.xml diff --git a/src/test/java/org/bench4q/agent/test/RunScenarioTest.java b/src/test/java/org/bench4q/agent/test/RunScenarioTest.java index 518e6afd..e50d9bb5 100644 --- a/src/test/java/org/bench4q/agent/test/RunScenarioTest.java +++ b/src/test/java/org/bench4q/agent/test/RunScenarioTest.java @@ -44,7 +44,7 @@ public class RunScenarioTest { getUserBehaviorModel.setParameters(new ArrayList()); ParameterModel parameterModelOne = new ParameterModel(); parameterModelOne.setKey("url"); - parameterModelOne.setValue("http://localhost:6565"); + parameterModelOne.setValue("http://Bench4Q-Agent-1:6565"); getUserBehaviorModel.getParameters().add(parameterModelOne); runScenarioModel.getUserBehaviors().add(getUserBehaviorModel); UserBehaviorModel timerUserBehaviorModel = new UserBehaviorModel(); @@ -64,7 +64,7 @@ public class RunScenarioTest { .setParameters(new ArrayList()); ParameterModel parameterModelThree = new ParameterModel(); parameterModelThree.setKey("url"); - parameterModelThree.setValue("http://localhost:6565"); + parameterModelThree.setValue("http://Bench4Q-Agent-1:6565"); postUserBehaviorModel.getParameters().add(parameterModelThree); ParameterModel parameterModelFour = new ParameterModel(); parameterModelFour.setKey("content"); @@ -75,7 +75,7 @@ public class RunScenarioTest { runScenarioModel.getClass()).createMarshaller(); StringWriter stringWriter = new StringWriter(); marshaller.marshal(runScenarioModel, stringWriter); - String url = "http://localhost:6565/test/run"; + String url = "http://Bench4Q-Agent-1:6565/test/run"; String content = stringWriter.toString(); System.out.println(content); URL target = new URL(url); From d6ee08a98382b249cc942a3705d479e75fabf984 Mon Sep 17 00:00:00 2001 From: Zhen Tang Date: Fri, 5 Jul 2013 12:19:52 +0800 Subject: [PATCH 034/196] package plugin configuration updated. --- descriptor.xml | 16 ++++++++-------- pom.xml | 19 ++++++++++++------- 2 files changed, 20 insertions(+), 15 deletions(-) diff --git a/descriptor.xml b/descriptor.xml index 276d32a3..2e790ab9 100644 --- a/descriptor.xml +++ b/descriptor.xml @@ -3,23 +3,23 @@ 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"> - jar-with-dependencies + dir - jar + dir false - / + lib false false runtime - - - ${project.build.outputDirectory} + + + target/bench4q-agent.jar / - - + + \ No newline at end of file diff --git a/pom.xml b/pom.xml index af774e3f..2e39d853 100644 --- a/pom.xml +++ b/pom.xml @@ -51,26 +51,31 @@ - maven-assembly-plugin + maven-jar-plugin - - descriptor.xml - - false org.bench4q.agent.Main true + lib/ + + + maven-assembly-plugin - make-assembly + make-zip package - assembly + single + + + descriptor.xml + + From 07aef554307bac2db7ab6bfb1b1aca6e2fb659dc Mon Sep 17 00:00:00 2001 From: Zhen Tang Date: Fri, 5 Jul 2013 13:56:40 +0800 Subject: [PATCH 035/196] update the plugin discovery function. javassist removed. --- pom.xml | 5 - .../org/bench4q/agent/plugin/Parameter.java | 12 ++ .../bench4q/agent/plugin/PluginManager.java | 156 ++++++++++-------- .../agent/plugin/basic/CommandLinePlugin.java | 3 +- .../plugin/basic/ConstantTimerPlugin.java | 3 +- .../agent/plugin/basic/HttpPlugin.java | 13 +- .../bench4q/agent/plugin/basic/LogPlugin.java | 3 +- 7 files changed, 110 insertions(+), 85 deletions(-) create mode 100644 src/main/java/org/bench4q/agent/plugin/Parameter.java diff --git a/pom.xml b/pom.xml index 2e39d853..16b2063b 100644 --- a/pom.xml +++ b/pom.xml @@ -37,11 +37,6 @@ jackson-mapper-asl 1.9.12 - - org.javassist - javassist - 3.18.0-GA - org.apache.hadoop hadoop-core diff --git a/src/main/java/org/bench4q/agent/plugin/Parameter.java b/src/main/java/org/bench4q/agent/plugin/Parameter.java new file mode 100644 index 00000000..ee7d8a11 --- /dev/null +++ b/src/main/java/org/bench4q/agent/plugin/Parameter.java @@ -0,0 +1,12 @@ +package org.bench4q.agent.plugin; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Target(ElementType.PARAMETER) +@Retention(RetentionPolicy.RUNTIME) +public @interface Parameter { + String value(); +} diff --git a/src/main/java/org/bench4q/agent/plugin/PluginManager.java b/src/main/java/org/bench4q/agent/plugin/PluginManager.java index a26dd29f..08bb4205 100644 --- a/src/main/java/org/bench4q/agent/plugin/PluginManager.java +++ b/src/main/java/org/bench4q/agent/plugin/PluginManager.java @@ -1,22 +1,13 @@ package org.bench4q.agent.plugin; +import java.lang.annotation.Annotation; +import java.lang.reflect.Constructor; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; -import javassist.ClassPool; -import javassist.CtBehavior; -import javassist.CtClass; -import javassist.CtConstructor; -import javassist.CtMethod; -import javassist.Modifier; -import javassist.NotFoundException; -import javassist.bytecode.CodeAttribute; -import javassist.bytecode.LocalVariableAttribute; -import javassist.bytecode.MethodInfo; - import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @@ -81,17 +72,15 @@ public class PluginManager { List ret = new ArrayList(); for (Class plugin : plugins.values()) { PluginInfo pluginInfo = new PluginInfo(); - ClassPool classPool = ClassPool.getDefault(); - CtClass ctClass = classPool.get(plugin.getCanonicalName()); - pluginInfo.setName(((Plugin) ctClass - .getAnnotation(Plugin.class)).value()); - pluginInfo.setParameters(this.getParameters(ctClass + pluginInfo + .setName((plugin.getAnnotation(Plugin.class)).value()); + pluginInfo.setParameters(this.getParameters(plugin .getConstructors()[0])); - CtMethod[] behaviors = this.getBehaviors(ctClass); + Method[] behaviors = this.getBehaviors(plugin); pluginInfo.setBehaviors(new BehaviorInfo[behaviors.length]); int i = 0; for (i = 0; i < behaviors.length; i++) { - CtMethod behaviorMethod = behaviors[i]; + Method behaviorMethod = behaviors[i]; BehaviorInfo behaviorInfo = buildBehaviorInfo(behaviorMethod); pluginInfo.getBehaviors()[i] = behaviorInfo; } @@ -104,28 +93,28 @@ public class PluginManager { } } - private BehaviorInfo buildBehaviorInfo(CtMethod behaviorMethod) + private BehaviorInfo buildBehaviorInfo(Method behaviorMethod) throws ClassNotFoundException { BehaviorInfo behaviorInfo = new BehaviorInfo(); - behaviorInfo.setName(((Behavior) behaviorMethod - .getAnnotation(Behavior.class)).value()); + behaviorInfo.setName((behaviorMethod.getAnnotation(Behavior.class)) + .value()); behaviorInfo.setParameters(this.getParameters(behaviorMethod)); return behaviorInfo; } - private ParameterInfo[] getParameters(CtBehavior behavior) { + private ParameterInfo[] getParameters(Method behavior) { try { - MethodInfo methodInfo = behavior.getMethodInfo(); - CodeAttribute codeAttribute = methodInfo.getCodeAttribute(); - LocalVariableAttribute localVariableAttribute = (LocalVariableAttribute) codeAttribute - .getAttribute(LocalVariableAttribute.tag); int parameterCount = behavior.getParameterTypes().length; + Annotation[][] parameterAnnotations = behavior + .getParameterAnnotations(); ParameterInfo[] parameterNames = new ParameterInfo[parameterCount]; int i; - int pos = Modifier.isStatic(behavior.getModifiers()) ? 0 : 1; for (i = 0; i < parameterCount; i++) { - ParameterInfo parameterInfo = buildParameterInfo(behavior, - localVariableAttribute, i, pos); + Annotation[] annotations = parameterAnnotations[i]; + Parameter parameter = (Parameter) annotations[0]; + Class type = behavior.getParameterTypes()[i]; + ParameterInfo parameterInfo = buildParameterInfo( + parameter.value(), type.getName()); parameterNames[i] = parameterInfo; } return parameterNames; @@ -135,26 +124,46 @@ public class PluginManager { } } - private ParameterInfo buildParameterInfo(CtBehavior behavior, - LocalVariableAttribute localVariableAttribute, int i, int pos) - throws NotFoundException { + private ParameterInfo[] getParameters(Constructor behavior) { + try { + int parameterCount = behavior.getParameterTypes().length; + Annotation[][] parameterAnnotations = behavior + .getParameterAnnotations(); + ParameterInfo[] parameterNames = new ParameterInfo[parameterCount]; + int i; + for (i = 0; i < parameterCount; i++) { + Annotation[] annotations = parameterAnnotations[i]; + Parameter parameter = (Parameter) annotations[0]; + Class type = behavior.getParameterTypes()[i]; + ParameterInfo parameterInfo = buildParameterInfo( + parameter.value(), type.getName()); + parameterNames[i] = parameterInfo; + } + return parameterNames; + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } + + private ParameterInfo buildParameterInfo(String name, String type) { ParameterInfo parameterInfo = new ParameterInfo(); - parameterInfo.setName(localVariableAttribute.variableName(i + pos)); - parameterInfo.setType(behavior.getParameterTypes()[i].getName()); + parameterInfo.setName(name); + parameterInfo.setType(type); return parameterInfo; } - private CtMethod[] getBehaviors(CtClass plugin) { + private Method[] getBehaviors(Class plugin) { try { - CtMethod[] ctMethods = plugin.getMethods(); - List ret = new ArrayList(); + Method[] methods = plugin.getMethods(); + List ret = new ArrayList(); int i = 0; - for (i = 0; i < ctMethods.length; i++) { - if (ctMethods[i].hasAnnotation(Behavior.class)) { - ret.add(ctMethods[i]); + for (i = 0; i < methods.length; i++) { + if (methods[i].isAnnotationPresent(Behavior.class)) { + ret.add(methods[i]); } } - return ret.toArray(new CtMethod[0]); + return ret.toArray(new Method[0]); } catch (Exception e) { e.printStackTrace(); return null; @@ -164,13 +173,11 @@ public class PluginManager { public Object initializePlugin(Class plugin, Map parameters) { try { - ClassPool classPool = ClassPool.getDefault(); - CtClass ctClass = classPool.get(plugin.getCanonicalName()); - CtConstructor[] ctConstructors = ctClass.getConstructors(); + Constructor[] ctConstructors = plugin.getConstructors(); if (ctConstructors.length != 1) { return null; } - CtConstructor constructor = ctConstructors[0]; + Constructor constructor = ctConstructors[0]; Object[] params = prepareParameters(constructor, parameters); return plugin.getConstructors()[0].newInstance(params); } catch (Exception e) { @@ -179,7 +186,29 @@ public class PluginManager { } } - private Object[] prepareParameters(CtBehavior behavior, + private Object[] prepareParameters(Constructor behavior, + Map parameters) { + try { + ParameterInfo[] parameterInfo = this.getParameters(behavior); + Object values[] = new Object[parameterInfo.length]; + int i = 0; + for (i = 0; i < parameterInfo.length; i++) { + Object value = parameters.get(parameterInfo[i].getName()); + if (value == null) { + values[i] = null; + } else { + values[i] = this.getTypeConverter().convert(value, + parameterInfo[i].getType()); + } + } + return values; + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } + + private Object[] prepareParameters(Method behavior, Map parameters) { try { ParameterInfo[] parameterInfo = this.getParameters(behavior); @@ -204,15 +233,11 @@ public class PluginManager { public Object doBehavior(Object plugin, String behaviorName, Map parameters) { try { - CtMethod ctMethod = findCtMethod(plugin, behaviorName); - if (ctMethod == null) { - return null; - } - Method method = findMethod(plugin, ctMethod); + Method method = findMethod(plugin, behaviorName); if (method == null) { return null; } - Object[] params = prepareParameters(ctMethod, parameters); + Object[] params = prepareParameters(method, parameters); return method.invoke(plugin, params); } catch (Exception e) { e.printStackTrace(); @@ -220,30 +245,15 @@ public class PluginManager { } } - private Method findMethod(Object plugin, CtMethod ctMethod) { - int i; - Method[] methods = plugin.getClass().getMethods(); - Method method = null; - for (i = 0; i < methods.length; i++) { - if (methods[i].getName().equals(ctMethod.getName())) { - method = methods[i]; - } - } - return method; - } - - private CtMethod findCtMethod(Object plugin, String behaviorName) { + private Method findMethod(Object plugin, String behaviorName) { try { - ClassPool classPool = ClassPool.getDefault(); - CtClass ctClass = classPool.get(plugin.getClass() - .getCanonicalName()); - CtMethod[] ctMethods = ctClass.getMethods(); + Method[] methods = plugin.getClass().getMethods(); int i = 0; - for (i = 0; i < ctMethods.length; i++) { - if (ctMethods[i].hasAnnotation(Behavior.class)) { - if (((Behavior) ctMethods[i].getAnnotation(Behavior.class)) + for (i = 0; i < methods.length; i++) { + if (methods[i].isAnnotationPresent(Behavior.class)) { + if (((Behavior) methods[i].getAnnotation(Behavior.class)) .value().equals(behaviorName)) { - return ctMethods[i]; + return methods[i]; } } } diff --git a/src/main/java/org/bench4q/agent/plugin/basic/CommandLinePlugin.java b/src/main/java/org/bench4q/agent/plugin/basic/CommandLinePlugin.java index 02741f3d..255caa9e 100644 --- a/src/main/java/org/bench4q/agent/plugin/basic/CommandLinePlugin.java +++ b/src/main/java/org/bench4q/agent/plugin/basic/CommandLinePlugin.java @@ -4,6 +4,7 @@ import java.io.BufferedReader; import java.io.InputStreamReader; import org.bench4q.agent.plugin.Behavior; +import org.bench4q.agent.plugin.Parameter; import org.bench4q.agent.plugin.Plugin; @Plugin("CommandLine") @@ -32,7 +33,7 @@ public class CommandLinePlugin { } @Behavior("Command") - public boolean command(String command) { + public boolean command(@Parameter("command") String command) { try { final Process process = Runtime.getRuntime().exec(command); new Thread() { diff --git a/src/main/java/org/bench4q/agent/plugin/basic/ConstantTimerPlugin.java b/src/main/java/org/bench4q/agent/plugin/basic/ConstantTimerPlugin.java index e33bb276..1e041d7a 100644 --- a/src/main/java/org/bench4q/agent/plugin/basic/ConstantTimerPlugin.java +++ b/src/main/java/org/bench4q/agent/plugin/basic/ConstantTimerPlugin.java @@ -1,6 +1,7 @@ package org.bench4q.agent.plugin.basic; import org.bench4q.agent.plugin.Behavior; +import org.bench4q.agent.plugin.Parameter; import org.bench4q.agent.plugin.Plugin; @Plugin("ConstantTimer") @@ -10,7 +11,7 @@ public class ConstantTimerPlugin { } @Behavior("Sleep") - public boolean sleep(int time) { + public boolean sleep(@Parameter("time") int time) { try { Thread.sleep(time); return true; diff --git a/src/main/java/org/bench4q/agent/plugin/basic/HttpPlugin.java b/src/main/java/org/bench4q/agent/plugin/basic/HttpPlugin.java index 35d47635..b3f53942 100644 --- a/src/main/java/org/bench4q/agent/plugin/basic/HttpPlugin.java +++ b/src/main/java/org/bench4q/agent/plugin/basic/HttpPlugin.java @@ -5,7 +5,9 @@ import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.HttpURLConnection; import java.net.URL; + import org.bench4q.agent.plugin.Behavior; +import org.bench4q.agent.plugin.Parameter; import org.bench4q.agent.plugin.Plugin; @Plugin("Http") @@ -16,7 +18,7 @@ public class HttpPlugin { } @Behavior("Get") - public boolean get(String url) { + public boolean get(@Parameter("url") String url) { try { URL target = new URL(url); HttpURLConnection httpURLConnection = (HttpURLConnection) target @@ -41,7 +43,8 @@ public class HttpPlugin { } @Behavior("Post") - public boolean post(String url, String content) { + public boolean post(@Parameter("url") String url, + @Parameter("content") String content) { try { URL target = new URL(url); HttpURLConnection httpURLConnection = (HttpURLConnection) target @@ -71,7 +74,8 @@ public class HttpPlugin { } @Behavior("Put") - public boolean put(String url, String content) { + public boolean put(@Parameter("url") String url, + @Parameter("content") String content) { try { URL target = new URL(url); HttpURLConnection httpURLConnection = (HttpURLConnection) target @@ -101,7 +105,8 @@ public class HttpPlugin { } @Behavior("Delete") - public boolean delete(String url, String content) { + public boolean delete(@Parameter("url") String url, + @Parameter("content") String content) { try { URL target = new URL(url); HttpURLConnection httpURLConnection = (HttpURLConnection) target diff --git a/src/main/java/org/bench4q/agent/plugin/basic/LogPlugin.java b/src/main/java/org/bench4q/agent/plugin/basic/LogPlugin.java index 58d7007d..bf128e32 100644 --- a/src/main/java/org/bench4q/agent/plugin/basic/LogPlugin.java +++ b/src/main/java/org/bench4q/agent/plugin/basic/LogPlugin.java @@ -1,6 +1,7 @@ package org.bench4q.agent.plugin.basic; import org.bench4q.agent.plugin.Behavior; +import org.bench4q.agent.plugin.Parameter; import org.bench4q.agent.plugin.Plugin; @Plugin("Log") @@ -10,7 +11,7 @@ public class LogPlugin { } @Behavior("Log") - public boolean log(String message) { + public boolean log(@Parameter("message") String message) { System.out.println(message); return true; } From 9f87dadc6a97dbdd0ff2bb28e03ac303b0d751d1 Mon Sep 17 00:00:00 2001 From: Zhen Tang Date: Mon, 15 Jul 2013 11:32:56 +0800 Subject: [PATCH 036/196] gitignore added. --- .gitignore | 4 ++++ descriptor.xml | 4 ++-- src/test/java/org/bench4q/agent/test/RunScenarioTest.java | 2 +- 3 files changed, 7 insertions(+), 3 deletions(-) create mode 100644 .gitignore diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..a8754446 --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +.project +.classpath +/.settings +/target \ No newline at end of file diff --git a/descriptor.xml b/descriptor.xml index 2e790ab9..a7581f81 100644 --- a/descriptor.xml +++ b/descriptor.xml @@ -3,9 +3,9 @@ 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"> - dir + publish - dir + tar.gz false diff --git a/src/test/java/org/bench4q/agent/test/RunScenarioTest.java b/src/test/java/org/bench4q/agent/test/RunScenarioTest.java index e50d9bb5..a6155c9a 100644 --- a/src/test/java/org/bench4q/agent/test/RunScenarioTest.java +++ b/src/test/java/org/bench4q/agent/test/RunScenarioTest.java @@ -23,7 +23,7 @@ public class RunScenarioTest { public void testRunScenario() { try { RunScenarioModel runScenarioModel = new RunScenarioModel(); - runScenarioModel.setTotalCount(1000); + runScenarioModel.setTotalCount(100); runScenarioModel.setPoolSize(100); runScenarioModel.setUsePlugins(new ArrayList()); runScenarioModel From e68215db04975d142d01cbf69333c722967f3e60 Mon Sep 17 00:00:00 2001 From: Zhen Tang Date: Mon, 15 Jul 2013 15:10:41 +0800 Subject: [PATCH 037/196] local file storage added. --- .../agent/scenario/ScenarioEngine.java | 39 ++++++++++++---- .../bench4q/agent/storage/HdfsStorage.java | 2 +- .../bench4q/agent/storage/LocalStorage.java | 44 +++++++++++++++++++ .../org/bench4q/agent/storage/Storage.java | 7 +++ .../bench4q/agent/storage/StorageHelper.java | 29 ++++++++++++ .../bench4q/agent/test/RunScenarioTest.java | 6 +-- 6 files changed, 114 insertions(+), 13 deletions(-) create mode 100644 src/main/java/org/bench4q/agent/storage/LocalStorage.java create mode 100644 src/main/java/org/bench4q/agent/storage/Storage.java create mode 100644 src/main/java/org/bench4q/agent/storage/StorageHelper.java diff --git a/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java b/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java index 5103a7e4..c5900abe 100644 --- a/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java +++ b/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java @@ -1,5 +1,6 @@ package org.bench4q.agent.scenario; +import java.io.File; import java.io.StringWriter; import java.util.ArrayList; import java.util.Collections; @@ -16,7 +17,7 @@ import javax.xml.bind.Marshaller; import org.bench4q.agent.plugin.Plugin; import org.bench4q.agent.plugin.PluginManager; -import org.bench4q.agent.storage.HdfsStorage; +import org.bench4q.agent.storage.StorageHelper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @@ -24,7 +25,7 @@ import org.springframework.stereotype.Component; public class ScenarioEngine { private PluginManager pluginManager; private Map runningTests; - private HdfsStorage hdfsStorage; + private StorageHelper storageHelper; public ScenarioEngine() { this.setRunningTests(new HashMap()); @@ -39,13 +40,13 @@ public class ScenarioEngine { this.pluginManager = pluginManager; } - private HdfsStorage getHdfsStorage() { - return hdfsStorage; + public StorageHelper getStorageHelper() { + return storageHelper; } @Autowired - private void setHdfsStorage(HdfsStorage hdfsStorage) { - this.hdfsStorage = hdfsStorage; + public void setStorageHelper(StorageHelper storageHelper) { + this.storageHelper = storageHelper; } public Map getRunningTests() { @@ -156,10 +157,28 @@ public class ScenarioEngine { } } - public String getPath() { + public String getHdfsPath() { return "hdfs://133.133.12.21:9000/home/bench4q/results"; } + public String getLocalPath() { + String directory = this.getClass().getProtectionDomain() + .getCodeSource().getLocation().getFile().replace("\\", "/"); + File file = new File(directory); + if (!file.isDirectory()) { + directory = directory.substring(0, directory.lastIndexOf("/")); + } + if (!directory.endsWith("/")) { + directory += "/"; + } + directory += "results"; + File toCreate = new File(directory); + if (!toCreate.exists()) { + toCreate.mkdirs(); + } + return directory; + } + public void saveTestResults(UUID runId) { ScenarioContext scenarioContext = this.getRunningTests().get(runId); if (scenarioContext == null) { @@ -201,10 +220,12 @@ public class ScenarioEngine { testResult.getClass()).createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); stringWriter = new StringWriter(); - String fileName = this.getPath() + "/" + runId.toString() + ".xml"; + String fileName = this.getLocalPath() + "/" + runId.toString() + + ".xml"; marshaller.marshal(testResult, stringWriter); String content = stringWriter.toString(); - this.getHdfsStorage().writeFile(content, fileName); + this.getStorageHelper().getLocalStorage() + .writeFile(content, fileName); } catch (Exception e) { e.printStackTrace(); } finally { diff --git a/src/main/java/org/bench4q/agent/storage/HdfsStorage.java b/src/main/java/org/bench4q/agent/storage/HdfsStorage.java index 4d3b6c69..8738ef3b 100644 --- a/src/main/java/org/bench4q/agent/storage/HdfsStorage.java +++ b/src/main/java/org/bench4q/agent/storage/HdfsStorage.java @@ -16,7 +16,7 @@ import org.apache.hadoop.io.IOUtils; import org.springframework.stereotype.Component; @Component -public class HdfsStorage { +public class HdfsStorage implements Storage { private FileSystem getFileSystem() throws IOException { Configuration conf = new Configuration(); conf.set("mapred.jop.tracker", "hdfs://133.133.12.21:9001"); diff --git a/src/main/java/org/bench4q/agent/storage/LocalStorage.java b/src/main/java/org/bench4q/agent/storage/LocalStorage.java new file mode 100644 index 00000000..9f771605 --- /dev/null +++ b/src/main/java/org/bench4q/agent/storage/LocalStorage.java @@ -0,0 +1,44 @@ +package org.bench4q.agent.storage; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.InputStreamReader; +import java.io.OutputStreamWriter; + +import org.springframework.stereotype.Component; + +@Component +public class LocalStorage implements Storage { + + public String readFile(String path) { + try { + InputStreamReader inputStreamReader = new InputStreamReader( + new FileInputStream(new File(path)), "UTF-8"); + StringBuffer ret = new StringBuffer(); + int toRead; + while ((toRead = inputStreamReader.read()) != -1) { + ret.append((char) toRead); + } + inputStreamReader.close(); + return ret.toString(); + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } + + public boolean writeFile(String content, String path) { + try { + OutputStreamWriter outputStreamWriter = new OutputStreamWriter( + new FileOutputStream(new File(path)), "UTF-8"); + outputStreamWriter.write(content); + outputStreamWriter.flush(); + outputStreamWriter.close(); + return true; + } catch (Exception e) { + e.printStackTrace(); + return false; + } + } +} diff --git a/src/main/java/org/bench4q/agent/storage/Storage.java b/src/main/java/org/bench4q/agent/storage/Storage.java new file mode 100644 index 00000000..6dbbe36d --- /dev/null +++ b/src/main/java/org/bench4q/agent/storage/Storage.java @@ -0,0 +1,7 @@ +package org.bench4q.agent.storage; + +public interface Storage { + public String readFile(String path); + + public boolean writeFile(String content, String path); +} diff --git a/src/main/java/org/bench4q/agent/storage/StorageHelper.java b/src/main/java/org/bench4q/agent/storage/StorageHelper.java new file mode 100644 index 00000000..6843b039 --- /dev/null +++ b/src/main/java/org/bench4q/agent/storage/StorageHelper.java @@ -0,0 +1,29 @@ +package org.bench4q.agent.storage; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +@Component +public class StorageHelper { + private HdfsStorage hdfsStorage; + private LocalStorage localStorage; + + public HdfsStorage getHdfsStorage() { + return hdfsStorage; + } + + @Autowired + public void setHdfsStorage(HdfsStorage hdfsStorage) { + this.hdfsStorage = hdfsStorage; + } + + public LocalStorage getLocalStorage() { + return localStorage; + } + + @Autowired + public void setLocalStorage(LocalStorage localStorage) { + this.localStorage = localStorage; + } + +} diff --git a/src/test/java/org/bench4q/agent/test/RunScenarioTest.java b/src/test/java/org/bench4q/agent/test/RunScenarioTest.java index a6155c9a..62b2c5ff 100644 --- a/src/test/java/org/bench4q/agent/test/RunScenarioTest.java +++ b/src/test/java/org/bench4q/agent/test/RunScenarioTest.java @@ -44,7 +44,7 @@ public class RunScenarioTest { getUserBehaviorModel.setParameters(new ArrayList()); ParameterModel parameterModelOne = new ParameterModel(); parameterModelOne.setKey("url"); - parameterModelOne.setValue("http://Bench4Q-Agent-1:6565"); + parameterModelOne.setValue("http://localhost:6565"); getUserBehaviorModel.getParameters().add(parameterModelOne); runScenarioModel.getUserBehaviors().add(getUserBehaviorModel); UserBehaviorModel timerUserBehaviorModel = new UserBehaviorModel(); @@ -64,7 +64,7 @@ public class RunScenarioTest { .setParameters(new ArrayList()); ParameterModel parameterModelThree = new ParameterModel(); parameterModelThree.setKey("url"); - parameterModelThree.setValue("http://Bench4Q-Agent-1:6565"); + parameterModelThree.setValue("http://localhost:6565"); postUserBehaviorModel.getParameters().add(parameterModelThree); ParameterModel parameterModelFour = new ParameterModel(); parameterModelFour.setKey("content"); @@ -75,7 +75,7 @@ public class RunScenarioTest { runScenarioModel.getClass()).createMarshaller(); StringWriter stringWriter = new StringWriter(); marshaller.marshal(runScenarioModel, stringWriter); - String url = "http://Bench4Q-Agent-1:6565/test/run"; + String url = "http://localhost:6565/test/run"; String content = stringWriter.toString(); System.out.println(content); URL target = new URL(url); From b22874f6877ae8fed80fb497d11dc18e7efaed50 Mon Sep 17 00:00:00 2001 From: Zhen Tang Date: Mon, 15 Jul 2013 15:42:42 +0800 Subject: [PATCH 038/196] disable unit testing during build. --- pom.xml | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/pom.xml b/pom.xml index 16b2063b..177de9d1 100644 --- a/pom.xml +++ b/pom.xml @@ -74,6 +74,13 @@ + + org.apache.maven.plugins + maven-surefire-plugin + + true + + bench4q-agent From 86942822354258f9f52f3b51465fded481bdb86a Mon Sep 17 00:00:00 2001 From: Zhen Tang Date: Wed, 17 Jul 2013 11:44:15 +0800 Subject: [PATCH 039/196] unit test stubs added. --- .../agent/test/HomeControllerTest.java | 5 + .../bench4q/agent/test/HttpPluginTest.java | 5 + .../agent/test/PluginControllerTest.java | 5 + .../bench4q/agent/test/RunScenarioTest.java | 108 ------------------ .../agent/test/TestControllerTest.java | 5 + 5 files changed, 20 insertions(+), 108 deletions(-) create mode 100644 src/test/java/org/bench4q/agent/test/HomeControllerTest.java create mode 100644 src/test/java/org/bench4q/agent/test/HttpPluginTest.java create mode 100644 src/test/java/org/bench4q/agent/test/PluginControllerTest.java delete mode 100644 src/test/java/org/bench4q/agent/test/RunScenarioTest.java create mode 100644 src/test/java/org/bench4q/agent/test/TestControllerTest.java diff --git a/src/test/java/org/bench4q/agent/test/HomeControllerTest.java b/src/test/java/org/bench4q/agent/test/HomeControllerTest.java new file mode 100644 index 00000000..b71431f8 --- /dev/null +++ b/src/test/java/org/bench4q/agent/test/HomeControllerTest.java @@ -0,0 +1,5 @@ +package org.bench4q.agent.test; + +public class HomeControllerTest { + +} diff --git a/src/test/java/org/bench4q/agent/test/HttpPluginTest.java b/src/test/java/org/bench4q/agent/test/HttpPluginTest.java new file mode 100644 index 00000000..c7849cc1 --- /dev/null +++ b/src/test/java/org/bench4q/agent/test/HttpPluginTest.java @@ -0,0 +1,5 @@ +package org.bench4q.agent.test; + +public class HttpPluginTest { + +} diff --git a/src/test/java/org/bench4q/agent/test/PluginControllerTest.java b/src/test/java/org/bench4q/agent/test/PluginControllerTest.java new file mode 100644 index 00000000..f800f1b5 --- /dev/null +++ b/src/test/java/org/bench4q/agent/test/PluginControllerTest.java @@ -0,0 +1,5 @@ +package org.bench4q.agent.test; + +public class PluginControllerTest { + +} diff --git a/src/test/java/org/bench4q/agent/test/RunScenarioTest.java b/src/test/java/org/bench4q/agent/test/RunScenarioTest.java deleted file mode 100644 index 62b2c5ff..00000000 --- a/src/test/java/org/bench4q/agent/test/RunScenarioTest.java +++ /dev/null @@ -1,108 +0,0 @@ -package org.bench4q.agent.test; - -import java.io.BufferedReader; -import java.io.InputStreamReader; -import java.io.OutputStreamWriter; -import java.io.StringWriter; -import java.net.HttpURLConnection; -import java.net.URL; -import java.util.ArrayList; - -import javax.xml.bind.JAXBContext; -import javax.xml.bind.Marshaller; - -import org.bench4q.agent.api.model.ParameterModel; -import org.bench4q.agent.api.model.RunScenarioModel; -import org.bench4q.agent.api.model.UsePluginModel; -import org.bench4q.agent.api.model.UserBehaviorModel; -import org.junit.Test; - -public class RunScenarioTest { - - @Test - public void testRunScenario() { - try { - RunScenarioModel runScenarioModel = new RunScenarioModel(); - runScenarioModel.setTotalCount(100); - runScenarioModel.setPoolSize(100); - runScenarioModel.setUsePlugins(new ArrayList()); - runScenarioModel - .setUserBehaviors(new ArrayList()); - UsePluginModel httpUsePluginModel = new UsePluginModel(); - httpUsePluginModel.setId("http"); - httpUsePluginModel.setName("Http"); - httpUsePluginModel.setParameters(new ArrayList()); - UsePluginModel timerUsePluginModel = new UsePluginModel(); - timerUsePluginModel.setId("timer"); - timerUsePluginModel.setName("ConstantTimer"); - timerUsePluginModel.setParameters(new ArrayList()); - runScenarioModel.getUsePlugins().add(httpUsePluginModel); - runScenarioModel.getUsePlugins().add(timerUsePluginModel); - UserBehaviorModel getUserBehaviorModel = new UserBehaviorModel(); - getUserBehaviorModel.setName("Get"); - getUserBehaviorModel.setUse("http"); - getUserBehaviorModel.setParameters(new ArrayList()); - ParameterModel parameterModelOne = new ParameterModel(); - parameterModelOne.setKey("url"); - parameterModelOne.setValue("http://localhost:6565"); - getUserBehaviorModel.getParameters().add(parameterModelOne); - runScenarioModel.getUserBehaviors().add(getUserBehaviorModel); - UserBehaviorModel timerUserBehaviorModel = new UserBehaviorModel(); - timerUserBehaviorModel.setName("Sleep"); - timerUserBehaviorModel.setUse("timer"); - timerUserBehaviorModel - .setParameters(new ArrayList()); - ParameterModel parameterModelTwo = new ParameterModel(); - parameterModelTwo.setKey("time"); - parameterModelTwo.setValue("1000"); - timerUserBehaviorModel.getParameters().add(parameterModelTwo); - runScenarioModel.getUserBehaviors().add(timerUserBehaviorModel); - UserBehaviorModel postUserBehaviorModel = new UserBehaviorModel(); - postUserBehaviorModel.setName("Post"); - postUserBehaviorModel.setUse("http"); - postUserBehaviorModel - .setParameters(new ArrayList()); - ParameterModel parameterModelThree = new ParameterModel(); - parameterModelThree.setKey("url"); - parameterModelThree.setValue("http://localhost:6565"); - postUserBehaviorModel.getParameters().add(parameterModelThree); - ParameterModel parameterModelFour = new ParameterModel(); - parameterModelFour.setKey("content"); - parameterModelFour.setValue("Hello,world!"); - postUserBehaviorModel.getParameters().add(parameterModelFour); - runScenarioModel.getUserBehaviors().add(postUserBehaviorModel); - Marshaller marshaller = JAXBContext.newInstance( - runScenarioModel.getClass()).createMarshaller(); - StringWriter stringWriter = new StringWriter(); - marshaller.marshal(runScenarioModel, stringWriter); - String url = "http://localhost:6565/test/run"; - String content = stringWriter.toString(); - System.out.println(content); - URL target = new URL(url); - HttpURLConnection httpURLConnection = (HttpURLConnection) target - .openConnection(); - httpURLConnection.setDoOutput(true); - httpURLConnection.setDoInput(true); - httpURLConnection.setUseCaches(false); - httpURLConnection.setRequestMethod("POST"); - httpURLConnection.setRequestProperty("Content-Type", - "application/xml"); - OutputStreamWriter outputStreamWriter = new OutputStreamWriter( - httpURLConnection.getOutputStream()); - outputStreamWriter.write(content); - outputStreamWriter.flush(); - outputStreamWriter.close(); - BufferedReader bufferedReader = new BufferedReader( - new InputStreamReader(httpURLConnection.getInputStream())); - int temp = -1; - StringBuffer stringBuffer = new StringBuffer(); - while ((temp = bufferedReader.read()) != -1) { - stringBuffer.append((char) temp); - } - bufferedReader.close(); - System.out.println(stringBuffer.toString()); - } catch (Exception e) { - e.printStackTrace(); - } - } -} diff --git a/src/test/java/org/bench4q/agent/test/TestControllerTest.java b/src/test/java/org/bench4q/agent/test/TestControllerTest.java new file mode 100644 index 00000000..79a68271 --- /dev/null +++ b/src/test/java/org/bench4q/agent/test/TestControllerTest.java @@ -0,0 +1,5 @@ +package org.bench4q.agent.test; + +public class TestControllerTest { + +} From 3cad8792ff52667836001411f9547c541a430240 Mon Sep 17 00:00:00 2001 From: coderfengyun Date: Thu, 25 Jul 2013 18:19:30 +0800 Subject: [PATCH 040/196] adapted it to my code --- .../java/org/bench4q/agent/api/TestController.java | 13 ++++++++++++- .../agent/api/model/RunScenarioResultModel.java | 10 ++++++++++ .../org/bench4q/agent/test/TestControllerTest.java | 2 +- 3 files changed, 23 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/bench4q/agent/api/TestController.java b/src/main/java/org/bench4q/agent/api/TestController.java index f945c900..a6f5cbdc 100644 --- a/src/main/java/org/bench4q/agent/api/TestController.java +++ b/src/main/java/org/bench4q/agent/api/TestController.java @@ -1,5 +1,7 @@ package org.bench4q.agent.api; +import java.net.InetAddress; +import java.net.UnknownHostException; import java.util.ArrayList; import java.util.List; import java.util.UUID; @@ -47,17 +49,26 @@ public class TestController { @RequestMapping(value = "/run", method = RequestMethod.POST) @ResponseBody public RunScenarioResultModel run( - @RequestBody RunScenarioModel runScenarioModel) { + @RequestBody RunScenarioModel runScenarioModel) + throws UnknownHostException { Scenario scenario = extractScenario(runScenarioModel); UUID runId = UUID.randomUUID(); this.getScenarioEngine().runScenario(runId, scenario, runScenarioModel.getPoolSize(), runScenarioModel.getTotalCount()); RunScenarioResultModel runScenarioResultModel = new RunScenarioResultModel(); + runScenarioResultModel.setHostName(getLocalIpAdress()); runScenarioResultModel.setRunId(runId); + return runScenarioResultModel; } + private String getLocalIpAdress() throws UnknownHostException { + InetAddress addr = InetAddress.getLocalHost(); + String hostName = addr.getHostAddress().toString(); + return hostName; + } + private Scenario extractScenario(RunScenarioModel runScenarioModel) { Scenario scenario = new Scenario(); scenario.setUsePlugins(new UsePlugin[runScenarioModel.getUsePlugins() diff --git a/src/main/java/org/bench4q/agent/api/model/RunScenarioResultModel.java b/src/main/java/org/bench4q/agent/api/model/RunScenarioResultModel.java index 4f0c177a..6ebb626c 100644 --- a/src/main/java/org/bench4q/agent/api/model/RunScenarioResultModel.java +++ b/src/main/java/org/bench4q/agent/api/model/RunScenarioResultModel.java @@ -8,6 +8,7 @@ import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement(name = "runScenarioResult") public class RunScenarioResultModel { private UUID runId; + private String hostName; @XmlElement public UUID getRunId() { @@ -18,4 +19,13 @@ public class RunScenarioResultModel { this.runId = runId; } + @XmlElement + public String getHostName() { + return hostName; + } + + public void setHostName(String hostName) { + this.hostName = hostName; + } + } diff --git a/src/test/java/org/bench4q/agent/test/TestControllerTest.java b/src/test/java/org/bench4q/agent/test/TestControllerTest.java index 79a68271..c22b4e26 100644 --- a/src/test/java/org/bench4q/agent/test/TestControllerTest.java +++ b/src/test/java/org/bench4q/agent/test/TestControllerTest.java @@ -1,5 +1,5 @@ package org.bench4q.agent.test; public class TestControllerTest { - + } From 02e2b25ff9354efe0580d3b6dc6337c1c4b2b659 Mon Sep 17 00:00:00 2001 From: coderfengyun Date: Fri, 26 Jul 2013 11:14:48 +0800 Subject: [PATCH 041/196] do a small modify to get the infomation i want --- .../java/org/bench4q/agent/api/TestController.java | 4 +++- .../bench4q/agent/api/model/TestBriefStatusModel.java | 10 ++++++++++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/src/main/java/org/bench4q/agent/api/TestController.java b/src/main/java/org/bench4q/agent/api/TestController.java index a6f5cbdc..ca0ef3ef 100644 --- a/src/main/java/org/bench4q/agent/api/TestController.java +++ b/src/main/java/org/bench4q/agent/api/TestController.java @@ -57,7 +57,7 @@ public class TestController { runScenarioModel.getPoolSize(), runScenarioModel.getTotalCount()); RunScenarioResultModel runScenarioResultModel = new RunScenarioResultModel(); - runScenarioResultModel.setHostName(getLocalIpAdress()); + runScenarioResultModel.setHostName(this.getLocalIpAdress()); runScenarioResultModel.setRunId(runId); return runScenarioResultModel; @@ -234,6 +234,8 @@ public class TestController { testBriefStatusModel.setSuccessCount(successCount); testBriefStatusModel.setFinishedCount(behaviorResults.size()); testBriefStatusModel.setTotalCount(scenarioContext.getTotalCount()); + testBriefStatusModel.setScenarioBehaviorCount(scenarioContext + .getScenario().getUserBehaviors().length); return testBriefStatusModel; } diff --git a/src/main/java/org/bench4q/agent/api/model/TestBriefStatusModel.java b/src/main/java/org/bench4q/agent/api/model/TestBriefStatusModel.java index e6dd9467..3eead89d 100644 --- a/src/main/java/org/bench4q/agent/api/model/TestBriefStatusModel.java +++ b/src/main/java/org/bench4q/agent/api/model/TestBriefStatusModel.java @@ -13,6 +13,7 @@ public class TestBriefStatusModel { private int failCount; private int finishedCount; private int totalCount; + private int scenarioBehaviorCount; private double averageResponseTime; @XmlElement @@ -78,4 +79,13 @@ public class TestBriefStatusModel { this.averageResponseTime = averageResponseTime; } + @XmlElement + public int getScenarioBehaviorCount() { + return scenarioBehaviorCount; + } + + public void setScenarioBehaviorCount(int scenarioBehaviorCount) { + this.scenarioBehaviorCount = scenarioBehaviorCount; + } + } From c505bc4edf26aaf697348bbad43a9a7469d96783 Mon Sep 17 00:00:00 2001 From: coderfengyun Date: Fri, 16 Aug 2013 15:04:16 +0800 Subject: [PATCH 042/196] edit for the information of finishedScenarioCount, to get it for moving task --- .../java/org/bench4q/agent/api/TestController.java | 8 -------- .../agent/api/model/RunScenarioResultModel.java | 10 ---------- .../bench4q/agent/api/model/TestBriefStatusModel.java | 10 ++++++++++ .../org/bench4q/agent/scenario/ScenarioContext.java | 11 +++++++++-- .../org/bench4q/agent/scenario/ScenarioEngine.java | 1 + 5 files changed, 20 insertions(+), 20 deletions(-) diff --git a/src/main/java/org/bench4q/agent/api/TestController.java b/src/main/java/org/bench4q/agent/api/TestController.java index ca0ef3ef..a373cd13 100644 --- a/src/main/java/org/bench4q/agent/api/TestController.java +++ b/src/main/java/org/bench4q/agent/api/TestController.java @@ -1,6 +1,5 @@ package org.bench4q.agent.api; -import java.net.InetAddress; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.List; @@ -57,18 +56,11 @@ public class TestController { runScenarioModel.getPoolSize(), runScenarioModel.getTotalCount()); RunScenarioResultModel runScenarioResultModel = new RunScenarioResultModel(); - runScenarioResultModel.setHostName(this.getLocalIpAdress()); runScenarioResultModel.setRunId(runId); return runScenarioResultModel; } - private String getLocalIpAdress() throws UnknownHostException { - InetAddress addr = InetAddress.getLocalHost(); - String hostName = addr.getHostAddress().toString(); - return hostName; - } - private Scenario extractScenario(RunScenarioModel runScenarioModel) { Scenario scenario = new Scenario(); scenario.setUsePlugins(new UsePlugin[runScenarioModel.getUsePlugins() diff --git a/src/main/java/org/bench4q/agent/api/model/RunScenarioResultModel.java b/src/main/java/org/bench4q/agent/api/model/RunScenarioResultModel.java index 6ebb626c..4f0c177a 100644 --- a/src/main/java/org/bench4q/agent/api/model/RunScenarioResultModel.java +++ b/src/main/java/org/bench4q/agent/api/model/RunScenarioResultModel.java @@ -8,7 +8,6 @@ import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement(name = "runScenarioResult") public class RunScenarioResultModel { private UUID runId; - private String hostName; @XmlElement public UUID getRunId() { @@ -19,13 +18,4 @@ public class RunScenarioResultModel { this.runId = runId; } - @XmlElement - public String getHostName() { - return hostName; - } - - public void setHostName(String hostName) { - this.hostName = hostName; - } - } diff --git a/src/main/java/org/bench4q/agent/api/model/TestBriefStatusModel.java b/src/main/java/org/bench4q/agent/api/model/TestBriefStatusModel.java index 3eead89d..5f5ece56 100644 --- a/src/main/java/org/bench4q/agent/api/model/TestBriefStatusModel.java +++ b/src/main/java/org/bench4q/agent/api/model/TestBriefStatusModel.java @@ -13,6 +13,7 @@ public class TestBriefStatusModel { private int failCount; private int finishedCount; private int totalCount; + private int finishedScenarioCount; private int scenarioBehaviorCount; private double averageResponseTime; @@ -70,6 +71,15 @@ public class TestBriefStatusModel { this.totalCount = totalCount; } + @XmlElement + public int getFinishedScenarioCount() { + return finishedScenarioCount; + } + + public void setFinishedScenarioCount(int finishedScenarioCount) { + this.finishedScenarioCount = finishedScenarioCount; + } + @XmlElement public double getAverageResponseTime() { return averageResponseTime; diff --git a/src/main/java/org/bench4q/agent/scenario/ScenarioContext.java b/src/main/java/org/bench4q/agent/scenario/ScenarioContext.java index fdf7b917..7f3f9b04 100644 --- a/src/main/java/org/bench4q/agent/scenario/ScenarioContext.java +++ b/src/main/java/org/bench4q/agent/scenario/ScenarioContext.java @@ -4,10 +4,10 @@ import java.util.Date; import java.util.List; import java.util.concurrent.ExecutorService; - public class ScenarioContext { private int poolSize; private int totalCount; + private int finishedCount; private Date startDate; private ExecutorService executorService; private Scenario scenario; @@ -29,6 +29,14 @@ public class ScenarioContext { this.totalCount = totalCount; } + public int getFinishedCount() { + return finishedCount; + } + + public void setFinishedCount(int finishedCount) { + this.finishedCount = finishedCount; + } + public Date getStartDate() { return startDate; } @@ -60,5 +68,4 @@ public class ScenarioContext { public void setResults(List results) { this.results = results; } - } diff --git a/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java b/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java index c5900abe..bf8dcec4 100644 --- a/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java +++ b/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java @@ -74,6 +74,7 @@ public class ScenarioEngine { } }; for (i = 0; i < totalCount; i++) { + scenarioContext.setFinishedCount(i - 1); executorService.execute(runnable); } executorService.shutdown(); From f073d37fe7549db62ba59a310399a2c06af5bb9f Mon Sep 17 00:00:00 2001 From: coderfengyun Date: Wed, 21 Aug 2013 17:40:33 +0800 Subject: [PATCH 043/196] add things about controlling the test by timer --- .../org/bench4q/agent/api/HomeController.java | 2 +- .../org/bench4q/agent/api/TestController.java | 6 ++- .../agent/api/model/TestBriefStatusModel.java | 10 ---- .../agent/scenario/RunnableExecutor.java | 49 +++++++++++++++++++ .../agent/scenario/ScenarioContext.java | 10 ++++ .../agent/scenario/ScenarioEngine.java | 12 ++--- 6 files changed, 68 insertions(+), 21 deletions(-) create mode 100644 src/main/java/org/bench4q/agent/scenario/RunnableExecutor.java diff --git a/src/main/java/org/bench4q/agent/api/HomeController.java b/src/main/java/org/bench4q/agent/api/HomeController.java index 078b3e42..4f129404 100644 --- a/src/main/java/org/bench4q/agent/api/HomeController.java +++ b/src/main/java/org/bench4q/agent/api/HomeController.java @@ -38,7 +38,7 @@ public class HomeController { getScenarioEngine().getRunningTests()); for (UUID key : contexts.keySet()) { ScenarioContext value = contexts.get(key); - if (value.getResults().size() == value.getTotalCount()) { + if (value.isFinished()) { serverStatusModel.getFinishedTests().add(key); } else { serverStatusModel.getRunningTests().add(key); diff --git a/src/main/java/org/bench4q/agent/api/TestController.java b/src/main/java/org/bench4q/agent/api/TestController.java index a373cd13..c9887f8e 100644 --- a/src/main/java/org/bench4q/agent/api/TestController.java +++ b/src/main/java/org/bench4q/agent/api/TestController.java @@ -231,15 +231,19 @@ public class TestController { return testBriefStatusModel; } - @RequestMapping(value = "/stop/{runId}", method = RequestMethod.GET) + @RequestMapping(value = "/stop/{runId}", method = { RequestMethod.GET, + RequestMethod.POST }) @ResponseBody public StopTestModel stop(@PathVariable UUID runId) { + System.out.println("stop method"); ScenarioContext scenarioContext = this.getScenarioEngine() .getRunningTests().get(runId); if (scenarioContext == null) { return null; } scenarioContext.getExecutorService().shutdownNow(); + scenarioContext.setFinished(true); + StopTestModel stopTestModel = new StopTestModel(); stopTestModel.setSuccess(true); return stopTestModel; diff --git a/src/main/java/org/bench4q/agent/api/model/TestBriefStatusModel.java b/src/main/java/org/bench4q/agent/api/model/TestBriefStatusModel.java index 5f5ece56..3eead89d 100644 --- a/src/main/java/org/bench4q/agent/api/model/TestBriefStatusModel.java +++ b/src/main/java/org/bench4q/agent/api/model/TestBriefStatusModel.java @@ -13,7 +13,6 @@ public class TestBriefStatusModel { private int failCount; private int finishedCount; private int totalCount; - private int finishedScenarioCount; private int scenarioBehaviorCount; private double averageResponseTime; @@ -71,15 +70,6 @@ public class TestBriefStatusModel { this.totalCount = totalCount; } - @XmlElement - public int getFinishedScenarioCount() { - return finishedScenarioCount; - } - - public void setFinishedScenarioCount(int finishedScenarioCount) { - this.finishedScenarioCount = finishedScenarioCount; - } - @XmlElement public double getAverageResponseTime() { return averageResponseTime; diff --git a/src/main/java/org/bench4q/agent/scenario/RunnableExecutor.java b/src/main/java/org/bench4q/agent/scenario/RunnableExecutor.java new file mode 100644 index 00000000..994a7147 --- /dev/null +++ b/src/main/java/org/bench4q/agent/scenario/RunnableExecutor.java @@ -0,0 +1,49 @@ +package org.bench4q.agent.scenario; + +import java.util.List; +import java.util.UUID; + +public class RunnableExecutor implements Runnable { + private ScenarioEngine scenarioEngine; + private UUID runId; + private List behaviorResults; + private Scenario scenario; + + private void setScenarioEngine(ScenarioEngine scenarioEngine) { + this.scenarioEngine = scenarioEngine; + } + + private void setBehaviorResults(List behaviorResults) { + this.behaviorResults = behaviorResults; + } + + private void setRunId(UUID runId) { + this.runId = runId; + } + + private void setScenario(Scenario scenario) { + this.scenario = scenario; + } + + public RunnableExecutor(ScenarioEngine scenarioEngine, UUID runId, + Scenario scenario, List behaviorResults) { + this.setScenarioEngine(scenarioEngine); + this.setRunId(runId); + this.setScenario(scenario); + this.setBehaviorResults(behaviorResults); + } + + public void run() { + this.behaviorResults.addAll(this.scenarioEngine + .doRunScenario(this.scenario)); + + ScenarioContext scenarioContext = this.scenarioEngine.getRunningTests() + .get(this.runId); + if (scenarioContext.getExecutorService().isShutdown()) { + return; + } + scenarioContext.getExecutorService().execute( + new RunnableExecutor(this.scenarioEngine, this.runId, + this.scenario, this.behaviorResults)); + } +} diff --git a/src/main/java/org/bench4q/agent/scenario/ScenarioContext.java b/src/main/java/org/bench4q/agent/scenario/ScenarioContext.java index 7f3f9b04..3695ce91 100644 --- a/src/main/java/org/bench4q/agent/scenario/ScenarioContext.java +++ b/src/main/java/org/bench4q/agent/scenario/ScenarioContext.java @@ -12,6 +12,7 @@ public class ScenarioContext { private ExecutorService executorService; private Scenario scenario; private List results; + private boolean finished; public int getPoolSize() { return poolSize; @@ -68,4 +69,13 @@ public class ScenarioContext { public void setResults(List results) { this.results = results; } + + public boolean isFinished() { + return finished; + } + + public void setFinished(boolean finished) { + this.finished = finished; + } + } diff --git a/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java b/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java index bf8dcec4..033ae4f3 100644 --- a/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java +++ b/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java @@ -68,16 +68,10 @@ public class ScenarioEngine { poolSize, totalCount, executorService, ret); int i; this.getRunningTests().put(runId, scenarioContext); - Runnable runnable = new Runnable() { - public void run() { - ret.addAll(doRunScenario(scenario)); - } - }; - for (i = 0; i < totalCount; i++) { - scenarioContext.setFinishedCount(i - 1); + Runnable runnable = new RunnableExecutor(this, runId, scenario, ret); + for (i = 0; i < poolSize; i++) { executorService.execute(runnable); } - executorService.shutdown(); } catch (Exception e) { e.printStackTrace(); } @@ -97,7 +91,7 @@ public class ScenarioEngine { return scenarioContext; } - private List doRunScenario(Scenario scenario) { + public List doRunScenario(Scenario scenario) { Map plugins = new HashMap(); preparePlugins(scenario, plugins); From ba89338a9e83518e1ae86c32b3fc59966ffde60f Mon Sep 17 00:00:00 2001 From: coderfengyun Date: Wed, 28 Aug 2013 14:25:28 +0800 Subject: [PATCH 044/196] edit for runningTime of the agent runId --- .../java/org/bench4q/agent/api/TestController.java | 6 +++++- .../bench4q/agent/api/model/TestBriefStatusModel.java | 10 ++++++++++ 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/src/main/java/org/bench4q/agent/api/TestController.java b/src/main/java/org/bench4q/agent/api/TestController.java index c9887f8e..c8ecfa39 100644 --- a/src/main/java/org/bench4q/agent/api/TestController.java +++ b/src/main/java/org/bench4q/agent/api/TestController.java @@ -202,12 +202,15 @@ public class TestController { long totalResponseTime = 0; List behaviorResults = new ArrayList( scenarioContext.getResults()); - long maxDate = 0; + long maxDate = 0, minDate = Long.MAX_VALUE; int validCount = 0; for (BehaviorResult behaviorResult : behaviorResults) { if (behaviorResult.getEndDate().getTime() > maxDate) { maxDate = behaviorResult.getEndDate().getTime(); } + if (behaviorResult.getStartDate().getTime() < minDate) { + minDate = behaviorResult.getStartDate().getTime(); + } if (behaviorResult.isSuccess()) { successCount++; } else { @@ -222,6 +225,7 @@ public class TestController { / validCount); testBriefStatusModel.setElapsedTime(maxDate - testBriefStatusModel.getStartDate().getTime()); + testBriefStatusModel.setRunningTime(maxDate - minDate); testBriefStatusModel.setFailCount(failCount); testBriefStatusModel.setSuccessCount(successCount); testBriefStatusModel.setFinishedCount(behaviorResults.size()); diff --git a/src/main/java/org/bench4q/agent/api/model/TestBriefStatusModel.java b/src/main/java/org/bench4q/agent/api/model/TestBriefStatusModel.java index 3eead89d..ab1a9cf5 100644 --- a/src/main/java/org/bench4q/agent/api/model/TestBriefStatusModel.java +++ b/src/main/java/org/bench4q/agent/api/model/TestBriefStatusModel.java @@ -9,6 +9,7 @@ import javax.xml.bind.annotation.XmlRootElement; public class TestBriefStatusModel { private Date startDate; private long elapsedTime; + private long runningTime; private int successCount; private int failCount; private int finishedCount; @@ -34,6 +35,15 @@ public class TestBriefStatusModel { this.elapsedTime = elapsedTime; } + @XmlElement + public long getRunningTime() { + return runningTime; + } + + public void setRunningTime(long runningTime) { + this.runningTime = runningTime; + } + @XmlElement public int getSuccessCount() { return successCount; From 0f56154c393cd6de93f05dc9663ced16c44b187e Mon Sep 17 00:00:00 2001 From: coderfengyun Date: Fri, 30 Aug 2013 09:22:01 +0800 Subject: [PATCH 045/196] get agent's already runed time by brief --- .../org/bench4q/agent/api/TestController.java | 29 ++++++++++++++++++- .../agent/scenario/ScenarioContext.java | 18 ++++++++++++ .../agent/scenario/ScenarioEngine.java | 19 ++++++++++++ 3 files changed, 65 insertions(+), 1 deletion(-) diff --git a/src/main/java/org/bench4q/agent/api/TestController.java b/src/main/java/org/bench4q/agent/api/TestController.java index c8ecfa39..21f81bfe 100644 --- a/src/main/java/org/bench4q/agent/api/TestController.java +++ b/src/main/java/org/bench4q/agent/api/TestController.java @@ -205,6 +205,11 @@ public class TestController { long maxDate = 0, minDate = Long.MAX_VALUE; int validCount = 0; for (BehaviorResult behaviorResult : behaviorResults) { + // TODO: remove this + if (behaviorResult.getStartDate().getTime() < scenarioContext + .getStartDate().getTime()) { + continue; + } if (behaviorResult.getEndDate().getTime() > maxDate) { maxDate = behaviorResult.getEndDate().getTime(); } @@ -225,13 +230,15 @@ public class TestController { / validCount); testBriefStatusModel.setElapsedTime(maxDate - testBriefStatusModel.getStartDate().getTime()); - testBriefStatusModel.setRunningTime(maxDate - minDate); + testBriefStatusModel.setRunningTime(maxDate + - scenarioContext.getStartDate().getTime()); testBriefStatusModel.setFailCount(failCount); testBriefStatusModel.setSuccessCount(successCount); testBriefStatusModel.setFinishedCount(behaviorResults.size()); testBriefStatusModel.setTotalCount(scenarioContext.getTotalCount()); testBriefStatusModel.setScenarioBehaviorCount(scenarioContext .getScenario().getUserBehaviors().length); + testBriefStatusModel.setRunningTime(maxDate - minDate); return testBriefStatusModel; } @@ -277,4 +284,24 @@ public class TestController { saveTestResultModel.setSuccess(true); return saveTestResultModel; } + + @RequestMapping(value = "/startSave/{runId}", method = { RequestMethod.GET, + RequestMethod.POST }) + @ResponseBody + public SaveTestResultModel startSave(@PathVariable UUID runId) { + this.getScenarioEngine().startSaveResultsWithEdit(runId); + SaveTestResultModel saveTestResultModel = new SaveTestResultModel(); + saveTestResultModel.setSuccess(true); + return saveTestResultModel; + } + + @RequestMapping(value = "/stopSave/{runId}", method = { RequestMethod.GET, + RequestMethod.POST }) + @ResponseBody + public SaveTestResultModel stopSave(@PathVariable UUID runId) { + this.getScenarioEngine().stopSaveResultWithEdit(runId); + SaveTestResultModel saveTestResultModel = new SaveTestResultModel(); + saveTestResultModel.setSuccess(true); + return saveTestResultModel; + } } diff --git a/src/main/java/org/bench4q/agent/scenario/ScenarioContext.java b/src/main/java/org/bench4q/agent/scenario/ScenarioContext.java index 3695ce91..d1f0d0e1 100644 --- a/src/main/java/org/bench4q/agent/scenario/ScenarioContext.java +++ b/src/main/java/org/bench4q/agent/scenario/ScenarioContext.java @@ -9,10 +9,12 @@ public class ScenarioContext { private int totalCount; private int finishedCount; private Date startDate; + private Date stopDate; private ExecutorService executorService; private Scenario scenario; private List results; private boolean finished; + private boolean toSave; public int getPoolSize() { return poolSize; @@ -46,6 +48,14 @@ public class ScenarioContext { this.startDate = startDate; } + public Date getStopDate() { + return stopDate; + } + + public void setStopDate(Date stopDate) { + this.stopDate = stopDate; + } + public ExecutorService getExecutorService() { return executorService; } @@ -78,4 +88,12 @@ public class ScenarioContext { this.finished = finished; } + public boolean isToSave() { + return toSave; + } + + public void setToSave(boolean startToSave) { + this.toSave = startToSave; + } + } diff --git a/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java b/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java index 033ae4f3..69685b69 100644 --- a/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java +++ b/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java @@ -85,6 +85,7 @@ public class ScenarioEngine { scenarioContext.setTotalCount(totalCount * scenario.getUserBehaviors().length); scenarioContext.setPoolSize(poolSize); + // TODO: set it to null scenarioContext.setStartDate(new Date(System.currentTimeMillis())); scenarioContext.setExecutorService(executorService); scenarioContext.setResults(ret); @@ -174,6 +175,24 @@ public class ScenarioEngine { return directory; } + public void startSaveResultsWithEdit(UUID runId) { + ScenarioContext scenarioContext = this.getRunningTests().get(runId); + if (scenarioContext == null) { + return; + } + scenarioContext.setStartDate(new Date(System.currentTimeMillis())); + scenarioContext.setToSave(true); + } + + public void stopSaveResultWithEdit(UUID runId) { + ScenarioContext scenarioContext = this.getRunningTests().get(runId); + if (scenarioContext == null) { + return; + } + scenarioContext.setStopDate(new Date(System.currentTimeMillis())); + scenarioContext.setToSave(false); + } + public void saveTestResults(UUID runId) { ScenarioContext scenarioContext = this.getRunningTests().get(runId); if (scenarioContext == null) { From a7c74ee4a2492754a3ca61c6d4959b9d7f7aab45 Mon Sep 17 00:00:00 2001 From: coderfengyun Date: Fri, 30 Aug 2013 09:39:39 +0800 Subject: [PATCH 046/196] edit it --- src/main/java/org/bench4q/agent/api/TestController.java | 5 ----- src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java | 1 - 2 files changed, 6 deletions(-) diff --git a/src/main/java/org/bench4q/agent/api/TestController.java b/src/main/java/org/bench4q/agent/api/TestController.java index 21f81bfe..51f6c129 100644 --- a/src/main/java/org/bench4q/agent/api/TestController.java +++ b/src/main/java/org/bench4q/agent/api/TestController.java @@ -205,11 +205,6 @@ public class TestController { long maxDate = 0, minDate = Long.MAX_VALUE; int validCount = 0; for (BehaviorResult behaviorResult : behaviorResults) { - // TODO: remove this - if (behaviorResult.getStartDate().getTime() < scenarioContext - .getStartDate().getTime()) { - continue; - } if (behaviorResult.getEndDate().getTime() > maxDate) { maxDate = behaviorResult.getEndDate().getTime(); } diff --git a/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java b/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java index 69685b69..930a75c6 100644 --- a/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java +++ b/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java @@ -85,7 +85,6 @@ public class ScenarioEngine { scenarioContext.setTotalCount(totalCount * scenario.getUserBehaviors().length); scenarioContext.setPoolSize(poolSize); - // TODO: set it to null scenarioContext.setStartDate(new Date(System.currentTimeMillis())); scenarioContext.setExecutorService(executorService); scenarioContext.setResults(ret); From a95b2854d3b90804ef5c86c1d69a7a4cb09b1fc9 Mon Sep 17 00:00:00 2001 From: coderfengyun Date: Fri, 30 Aug 2013 17:34:22 +0800 Subject: [PATCH 047/196] add the support of moose --- .../org/bench4q/agent/storage/MooseStorage.java | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 src/main/java/org/bench4q/agent/storage/MooseStorage.java diff --git a/src/main/java/org/bench4q/agent/storage/MooseStorage.java b/src/main/java/org/bench4q/agent/storage/MooseStorage.java new file mode 100644 index 00000000..d168b225 --- /dev/null +++ b/src/main/java/org/bench4q/agent/storage/MooseStorage.java @@ -0,0 +1,15 @@ +package org.bench4q.agent.storage; + +public class MooseStorage implements Storage { + + public String readFile(String path) { + // TODO Auto-generated method stub + return null; + } + + public boolean writeFile(String content, String path) { + // TODO Auto-generated method stub + return false; + } + +} From 92373397f65505d4c53279154039089cb2f465e4 Mon Sep 17 00:00:00 2001 From: Tienan Chen Date: Tue, 3 Sep 2013 18:42:59 +0800 Subject: [PATCH 048/196] add something about save detail in fs --- .../org/bench4q/agent/api/TestController.java | 5 +++++ .../agent/scenario/ScenarioContext.java | 18 +++++++++--------- .../bench4q/agent/scenario/ScenarioEngine.java | 13 ++++++++++--- .../bench4q/agent/storage/MooseStorage.java | 5 ++++- .../bench4q/agent/storage/StorageHelper.java | 10 ++++++++++ 5 files changed, 38 insertions(+), 13 deletions(-) diff --git a/src/main/java/org/bench4q/agent/api/TestController.java b/src/main/java/org/bench4q/agent/api/TestController.java index 51f6c129..39899bb1 100644 --- a/src/main/java/org/bench4q/agent/api/TestController.java +++ b/src/main/java/org/bench4q/agent/api/TestController.java @@ -142,6 +142,11 @@ public class TestController { if (scenarioContext == null) { return null; } + return buildTestDetailStatusModel(scenarioContext); + } + + private TestDetailStatusModel buildTestDetailStatusModel( + ScenarioContext scenarioContext) { TestDetailStatusModel testStatusModel = new TestDetailStatusModel(); testStatusModel.setStartDate(scenarioContext.getStartDate()); testStatusModel.setTestDetailModels(new ArrayList()); diff --git a/src/main/java/org/bench4q/agent/scenario/ScenarioContext.java b/src/main/java/org/bench4q/agent/scenario/ScenarioContext.java index d1f0d0e1..3beb80d5 100644 --- a/src/main/java/org/bench4q/agent/scenario/ScenarioContext.java +++ b/src/main/java/org/bench4q/agent/scenario/ScenarioContext.java @@ -8,8 +8,8 @@ public class ScenarioContext { private int poolSize; private int totalCount; private int finishedCount; - private Date startDate; - private Date stopDate; + private Date saveStartDate; + private Date saveStopDate; private ExecutorService executorService; private Scenario scenario; private List results; @@ -41,19 +41,19 @@ public class ScenarioContext { } public Date getStartDate() { - return startDate; + return saveStartDate; } - public void setStartDate(Date startDate) { - this.startDate = startDate; + public void setSaveStartDate(Date saveStartDate) { + this.saveStartDate = saveStartDate; } - public Date getStopDate() { - return stopDate; + public Date getSaveStopDate() { + return saveStopDate; } - public void setStopDate(Date stopDate) { - this.stopDate = stopDate; + public void setStopDate(Date saveStopDate) { + this.saveStopDate = saveStopDate; } public ExecutorService getExecutorService() { diff --git a/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java b/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java index 930a75c6..f8cfce20 100644 --- a/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java +++ b/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java @@ -26,9 +26,10 @@ public class ScenarioEngine { private PluginManager pluginManager; private Map runningTests; private StorageHelper storageHelper; + private static int saveThreshold = 10000; public ScenarioEngine() { - this.setRunningTests(new HashMap()); + this.setRunningTests(new HashMap()); } private PluginManager getPluginManager() { @@ -85,7 +86,7 @@ public class ScenarioEngine { scenarioContext.setTotalCount(totalCount * scenario.getUserBehaviors().length); scenarioContext.setPoolSize(poolSize); - scenarioContext.setStartDate(new Date(System.currentTimeMillis())); + scenarioContext.setSaveStartDate(new Date(System.currentTimeMillis())); scenarioContext.setExecutorService(executorService); scenarioContext.setResults(ret); return scenarioContext; @@ -179,8 +180,14 @@ public class ScenarioEngine { if (scenarioContext == null) { return; } - scenarioContext.setStartDate(new Date(System.currentTimeMillis())); + + scenarioContext.setSaveStartDate(new Date(System.currentTimeMillis())); scenarioContext.setToSave(true); + + while (scenarioContext.isToSave() + && scenarioContext.getResults().size() >= saveThreshold) { + // saveTestResults(runId); + } } public void stopSaveResultWithEdit(UUID runId) { diff --git a/src/main/java/org/bench4q/agent/storage/MooseStorage.java b/src/main/java/org/bench4q/agent/storage/MooseStorage.java index d168b225..2f58dff4 100644 --- a/src/main/java/org/bench4q/agent/storage/MooseStorage.java +++ b/src/main/java/org/bench4q/agent/storage/MooseStorage.java @@ -1,9 +1,12 @@ package org.bench4q.agent.storage; +import org.springframework.stereotype.Component; + +@Component public class MooseStorage implements Storage { public String readFile(String path) { - // TODO Auto-generated method stub + return null; } diff --git a/src/main/java/org/bench4q/agent/storage/StorageHelper.java b/src/main/java/org/bench4q/agent/storage/StorageHelper.java index 6843b039..7a49f28c 100644 --- a/src/main/java/org/bench4q/agent/storage/StorageHelper.java +++ b/src/main/java/org/bench4q/agent/storage/StorageHelper.java @@ -7,6 +7,7 @@ import org.springframework.stereotype.Component; public class StorageHelper { private HdfsStorage hdfsStorage; private LocalStorage localStorage; + private MooseStorage mooseStorage; public HdfsStorage getHdfsStorage() { return hdfsStorage; @@ -26,4 +27,13 @@ public class StorageHelper { this.localStorage = localStorage; } + public MooseStorage getMooseStorage() { + return mooseStorage; + } + + @Autowired + public void setMooseStorage(MooseStorage mooseStorage) { + this.mooseStorage = mooseStorage; + } + } From 2fc2bcff643c40915211adb4a936753b97d7e4ce Mon Sep 17 00:00:00 2001 From: Tienan Chen Date: Wed, 11 Sep 2013 15:13:32 +0800 Subject: [PATCH 049/196] add about a test isFinish --- .../java/org/bench4q/agent/api/TestController.java | 1 + .../bench4q/agent/api/model/TestBriefStatusModel.java | 10 ++++++++++ 2 files changed, 11 insertions(+) diff --git a/src/main/java/org/bench4q/agent/api/TestController.java b/src/main/java/org/bench4q/agent/api/TestController.java index 39899bb1..e934da82 100644 --- a/src/main/java/org/bench4q/agent/api/TestController.java +++ b/src/main/java/org/bench4q/agent/api/TestController.java @@ -239,6 +239,7 @@ public class TestController { testBriefStatusModel.setScenarioBehaviorCount(scenarioContext .getScenario().getUserBehaviors().length); testBriefStatusModel.setRunningTime(maxDate - minDate); + testBriefStatusModel.setFinished(scenarioContext.isFinished()); return testBriefStatusModel; } diff --git a/src/main/java/org/bench4q/agent/api/model/TestBriefStatusModel.java b/src/main/java/org/bench4q/agent/api/model/TestBriefStatusModel.java index ab1a9cf5..742eae1d 100644 --- a/src/main/java/org/bench4q/agent/api/model/TestBriefStatusModel.java +++ b/src/main/java/org/bench4q/agent/api/model/TestBriefStatusModel.java @@ -16,6 +16,7 @@ public class TestBriefStatusModel { private int totalCount; private int scenarioBehaviorCount; private double averageResponseTime; + private boolean finished; @XmlElement public Date getStartDate() { @@ -98,4 +99,13 @@ public class TestBriefStatusModel { this.scenarioBehaviorCount = scenarioBehaviorCount; } + @XmlElement + public boolean isFinished() { + return finished; + } + + public void setFinished(boolean finished) { + this.finished = finished; + } + } From 18acc9d0dfec94b9cbde7c6a0c67ce84449afd20 Mon Sep 17 00:00:00 2001 From: fanfuxiaoran <495538672@qq.com> Date: Thu, 12 Sep 2013 18:11:37 +0800 Subject: [PATCH 050/196] debug when validCount = 0 --- src/main/java/org/bench4q/agent/api/TestController.java | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/main/java/org/bench4q/agent/api/TestController.java b/src/main/java/org/bench4q/agent/api/TestController.java index e934da82..3cba0b2c 100644 --- a/src/main/java/org/bench4q/agent/api/TestController.java +++ b/src/main/java/org/bench4q/agent/api/TestController.java @@ -226,6 +226,9 @@ public class TestController { validCount++; } } + if (validCount == 0) { + return null; + } testBriefStatusModel.setAverageResponseTime((totalResponseTime + 0.0) / validCount); testBriefStatusModel.setElapsedTime(maxDate From 1853b50539979fbd7d769f56d6ee392a38c70bf4 Mon Sep 17 00:00:00 2001 From: Tienan Chen Date: Thu, 26 Sep 2013 09:12:33 +0800 Subject: [PATCH 051/196] add parameter to post --- .../org/bench4q/agent/plugin/basic/HttpPlugin.java | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/src/main/java/org/bench4q/agent/plugin/basic/HttpPlugin.java b/src/main/java/org/bench4q/agent/plugin/basic/HttpPlugin.java index b3f53942..bff89256 100644 --- a/src/main/java/org/bench4q/agent/plugin/basic/HttpPlugin.java +++ b/src/main/java/org/bench4q/agent/plugin/basic/HttpPlugin.java @@ -44,7 +44,9 @@ public class HttpPlugin { @Behavior("Post") public boolean post(@Parameter("url") String url, - @Parameter("content") String content) { + @Parameter("content") String content, + @Parameter("contentType") String contentType, + @Parameter("accept") String accept) { try { URL target = new URL(url); HttpURLConnection httpURLConnection = (HttpURLConnection) target @@ -53,6 +55,13 @@ public class HttpPlugin { httpURLConnection.setDoInput(true); httpURLConnection.setUseCaches(false); httpURLConnection.setRequestMethod("POST"); + if (contentType != null && contentType.length() > 0) { + httpURLConnection.setRequestProperty("Content-Type", + contentType); + } + if (accept != null && accept.length() > 0) { + httpURLConnection.setRequestProperty("Accept", accept); + } OutputStreamWriter outputStreamWriter = new OutputStreamWriter( httpURLConnection.getOutputStream()); outputStreamWriter.write(content); From f895690e019bf811be28a2eb3633c6744e9f1e67 Mon Sep 17 00:00:00 2001 From: Tienan Chen Date: Fri, 27 Sep 2013 15:44:07 +0800 Subject: [PATCH 052/196] add license --- license.txt | 339 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 339 insertions(+) create mode 100644 license.txt diff --git a/license.txt b/license.txt new file mode 100644 index 00000000..ed5165d8 --- /dev/null +++ b/license.txt @@ -0,0 +1,339 @@ +GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc., [http://fsf.org/] + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Lesser General Public License instead.) You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +this service if you wish), that you receive source code or can get it +if you want it, that you can change the software or use pieces of it +in new free programs; and that you know you can do these things. + + To protect your rights, we need to make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. You must make sure that they, too, receive or can get the +source code. And you must show them these terms so they know their +rights. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute verbatim copies of the Program's +source code as you receive it, in any medium, provided that you +conspicuously and appropriately publish on each copy an appropriate +copyright notice and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + +Each version is given a distinguishing version number. If the Program +specifies a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY +FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN +OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES +PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED +OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS +TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE +PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, +REPAIR OR CORRECTION. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING +OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED +TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY +YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER +PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE +POSSIBILITY OF SUCH DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + {description} + Copyright (C) {year} {fullname} + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along + with this program; if not, write to the Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + +Also add information on how to contact you by electronic and paper mail. + +If the program is interactive, make it output a short notice like this +when it starts in an interactive mode: + + Gnomovision version 69, Copyright (C) year name of author + Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, the commands you use may +be called something other than `show w' and `show c'; they could even be +mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program + `Gnomovision' (which makes passes at compilers) written by James Hacker. + + {signature of Ty Coon}, 1 April 1989 + Ty Coon, President of Vice + +This General Public License does not permit incorporating your program into +proprietary programs. If your program is a subroutine library, you may +consider it more useful to permit linking proprietary applications with the +library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. \ No newline at end of file From c25eee268937ec5f33850d66135950e95af6c2e2 Mon Sep 17 00:00:00 2001 From: Tienan Chen Date: Fri, 18 Oct 2013 10:15:15 +0800 Subject: [PATCH 053/196] refactor, remove total count from testbrief resul model --- .../java/org/bench4q/agent/api/TestController.java | 4 ++-- .../bench4q/agent/api/model/TestBriefStatusModel.java | 10 ---------- .../org/bench4q/agent/scenario/ScenarioEngine.java | 6 +++--- 3 files changed, 5 insertions(+), 15 deletions(-) diff --git a/src/main/java/org/bench4q/agent/api/TestController.java b/src/main/java/org/bench4q/agent/api/TestController.java index 3cba0b2c..0fc99886 100644 --- a/src/main/java/org/bench4q/agent/api/TestController.java +++ b/src/main/java/org/bench4q/agent/api/TestController.java @@ -188,7 +188,7 @@ public class TestController { testStatusModel.setSuccessCount(successCount); testStatusModel.setFinishedCount(testStatusModel.getTestDetailModels() .size()); - testStatusModel.setTotalCount(scenarioContext.getTotalCount()); + // testStatusModel.setTotalCount(scenarioContext.getTotalCount()); return testStatusModel; } @@ -238,7 +238,7 @@ public class TestController { testBriefStatusModel.setFailCount(failCount); testBriefStatusModel.setSuccessCount(successCount); testBriefStatusModel.setFinishedCount(behaviorResults.size()); - testBriefStatusModel.setTotalCount(scenarioContext.getTotalCount()); + // testBriefStatusModel.setTotalCount(scenarioContext.getTotalCount()); testBriefStatusModel.setScenarioBehaviorCount(scenarioContext .getScenario().getUserBehaviors().length); testBriefStatusModel.setRunningTime(maxDate - minDate); diff --git a/src/main/java/org/bench4q/agent/api/model/TestBriefStatusModel.java b/src/main/java/org/bench4q/agent/api/model/TestBriefStatusModel.java index 742eae1d..71cf96d3 100644 --- a/src/main/java/org/bench4q/agent/api/model/TestBriefStatusModel.java +++ b/src/main/java/org/bench4q/agent/api/model/TestBriefStatusModel.java @@ -13,7 +13,6 @@ public class TestBriefStatusModel { private int successCount; private int failCount; private int finishedCount; - private int totalCount; private int scenarioBehaviorCount; private double averageResponseTime; private boolean finished; @@ -72,15 +71,6 @@ public class TestBriefStatusModel { this.finishedCount = finishedCount; } - @XmlElement - public int getTotalCount() { - return totalCount; - } - - public void setTotalCount(int totalCount) { - this.totalCount = totalCount; - } - @XmlElement public double getAverageResponseTime() { return averageResponseTime; diff --git a/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java b/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java index f8cfce20..0de9a226 100644 --- a/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java +++ b/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java @@ -83,8 +83,8 @@ public class ScenarioEngine { final List ret) { ScenarioContext scenarioContext = new ScenarioContext(); scenarioContext.setScenario(scenario); - scenarioContext.setTotalCount(totalCount - * scenario.getUserBehaviors().length); + // scenarioContext.setTotalCount(totalCount + // * scenario.getUserBehaviors().length); scenarioContext.setPoolSize(poolSize); scenarioContext.setSaveStartDate(new Date(System.currentTimeMillis())); scenarioContext.setExecutorService(executorService); @@ -267,7 +267,7 @@ public class ScenarioEngine { TestResult testResult = new TestResult(); testResult.setResults(results); testResult.setStartDate(scenarioContext.getStartDate()); - testResult.setTotalCount(scenarioContext.getTotalCount()); + // testResult.setTotalCount(scenarioContext.getTotalCount()); testResult.setRunId(runId); testResult.setPoolSize(scenarioContext.getPoolSize()); testResult.setAverageResponseTime((totalResponseTime + 0.0) From bf2c2aaaf2dc4918c79ba50c4518680a178a46a1 Mon Sep 17 00:00:00 2001 From: Tienan Chen Date: Mon, 21 Oct 2013 09:05:03 +0800 Subject: [PATCH 054/196] edit spring from 3.2.3 to 3.2.4 --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index 177de9d1..0678b859 100644 --- a/pom.xml +++ b/pom.xml @@ -30,7 +30,7 @@ org.springframework spring-webmvc - 3.2.3.RELEASE + 3.2.4.RELEASE org.codehaus.jackson From f290873a473582d6679a4a3a4c4384068e5cff76 Mon Sep 17 00:00:00 2001 From: Tienan Chen Date: Wed, 30 Oct 2013 10:13:44 +0800 Subject: [PATCH 055/196] refactor --- .../java/org/bench4q/agent/api/TestController.java | 1 - .../org/bench4q/agent/scenario/RunnableExecutor.java | 10 ++++------ .../java/org/bench4q/agent/storage/MooseStorage.java | 1 - 3 files changed, 4 insertions(+), 8 deletions(-) diff --git a/src/main/java/org/bench4q/agent/api/TestController.java b/src/main/java/org/bench4q/agent/api/TestController.java index 0fc99886..da0f3844 100644 --- a/src/main/java/org/bench4q/agent/api/TestController.java +++ b/src/main/java/org/bench4q/agent/api/TestController.java @@ -188,7 +188,6 @@ public class TestController { testStatusModel.setSuccessCount(successCount); testStatusModel.setFinishedCount(testStatusModel.getTestDetailModels() .size()); - // testStatusModel.setTotalCount(scenarioContext.getTotalCount()); return testStatusModel; } diff --git a/src/main/java/org/bench4q/agent/scenario/RunnableExecutor.java b/src/main/java/org/bench4q/agent/scenario/RunnableExecutor.java index 994a7147..b183c85c 100644 --- a/src/main/java/org/bench4q/agent/scenario/RunnableExecutor.java +++ b/src/main/java/org/bench4q/agent/scenario/RunnableExecutor.java @@ -34,16 +34,14 @@ public class RunnableExecutor implements Runnable { } public void run() { - this.behaviorResults.addAll(this.scenarioEngine - .doRunScenario(this.scenario)); - ScenarioContext scenarioContext = this.scenarioEngine.getRunningTests() .get(this.runId); if (scenarioContext.getExecutorService().isShutdown()) { return; } - scenarioContext.getExecutorService().execute( - new RunnableExecutor(this.scenarioEngine, this.runId, - this.scenario, this.behaviorResults)); + while (!scenarioContext.getExecutorService().isShutdown()) { + this.behaviorResults.addAll(this.scenarioEngine + .doRunScenario(this.scenario)); + } } } diff --git a/src/main/java/org/bench4q/agent/storage/MooseStorage.java b/src/main/java/org/bench4q/agent/storage/MooseStorage.java index 2f58dff4..729e8520 100644 --- a/src/main/java/org/bench4q/agent/storage/MooseStorage.java +++ b/src/main/java/org/bench4q/agent/storage/MooseStorage.java @@ -11,7 +11,6 @@ public class MooseStorage implements Storage { } public boolean writeFile(String content, String path) { - // TODO Auto-generated method stub return false; } From cdafe0633d7d546d1c8885ebdd304d26e814a515 Mon Sep 17 00:00:00 2001 From: Tienan Chen Date: Wed, 30 Oct 2013 11:34:48 +0800 Subject: [PATCH 056/196] refactor and remove a bug when run scenario --- .../bench4q/agent/scenario/RunnableExecutor.java | 3 --- .../bench4q/agent/scenario/ScenarioEngine.java | 16 ++++++++++------ 2 files changed, 10 insertions(+), 9 deletions(-) diff --git a/src/main/java/org/bench4q/agent/scenario/RunnableExecutor.java b/src/main/java/org/bench4q/agent/scenario/RunnableExecutor.java index b183c85c..1564dff9 100644 --- a/src/main/java/org/bench4q/agent/scenario/RunnableExecutor.java +++ b/src/main/java/org/bench4q/agent/scenario/RunnableExecutor.java @@ -36,9 +36,6 @@ public class RunnableExecutor implements Runnable { public void run() { ScenarioContext scenarioContext = this.scenarioEngine.getRunningTests() .get(this.runId); - if (scenarioContext.getExecutorService().isShutdown()) { - return; - } while (!scenarioContext.getExecutorService().isShutdown()) { this.behaviorResults.addAll(this.scenarioEngine .doRunScenario(this.scenario)); diff --git a/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java b/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java index 0de9a226..c656cfad 100644 --- a/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java +++ b/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java @@ -29,7 +29,7 @@ public class ScenarioEngine { private static int saveThreshold = 10000; public ScenarioEngine() { - this.setRunningTests(new HashMap()); + this.setRunningTests(new HashMap()); } private PluginManager getPluginManager() { @@ -65,11 +65,17 @@ public class ScenarioEngine { .newFixedThreadPool(poolSize); final List ret = Collections .synchronizedList(new ArrayList()); - ScenarioContext scenarioContext = buildScenarioContext(scenario, - poolSize, totalCount, executorService, ret); + final ScenarioContext scenarioContext = buildScenarioContext( + scenario, poolSize, totalCount, executorService, ret); int i; this.getRunningTests().put(runId, scenarioContext); - Runnable runnable = new RunnableExecutor(this, runId, scenario, ret); + Runnable runnable = new Runnable() { + public void run() { + while (!scenarioContext.getExecutorService().isShutdown()) { + ret.addAll(doRunScenario(scenario)); + } + } + }; for (i = 0; i < poolSize; i++) { executorService.execute(runnable); } @@ -83,8 +89,6 @@ public class ScenarioEngine { final List ret) { ScenarioContext scenarioContext = new ScenarioContext(); scenarioContext.setScenario(scenario); - // scenarioContext.setTotalCount(totalCount - // * scenario.getUserBehaviors().length); scenarioContext.setPoolSize(poolSize); scenarioContext.setSaveStartDate(new Date(System.currentTimeMillis())); scenarioContext.setExecutorService(executorService); From 283876374e17f08d3c3fd89a95942c314d292c99 Mon Sep 17 00:00:00 2001 From: Tienan Chen Date: Thu, 31 Oct 2013 14:50:27 +0800 Subject: [PATCH 057/196] add some test and log to determine there the bug is --- pom.xml | 5 + .../org/bench4q/agent/api/TestController.java | 28 +- src/main/resources/log4j.properties | 31 ++ .../java/Communication/HttpRequester.java | 276 ++++++++++++++++++ .../agent/test/TestWithScriptFile.java | 93 ++++++ 5 files changed, 432 insertions(+), 1 deletion(-) create mode 100644 src/main/resources/log4j.properties create mode 100644 src/test/java/Communication/HttpRequester.java create mode 100644 src/test/java/org/bench4q/agent/test/TestWithScriptFile.java diff --git a/pom.xml b/pom.xml index 0678b859..fa33d735 100644 --- a/pom.xml +++ b/pom.xml @@ -42,6 +42,11 @@ hadoop-core 1.1.2 + + log4j + log4j + 1.2.17 + diff --git a/src/main/java/org/bench4q/agent/api/TestController.java b/src/main/java/org/bench4q/agent/api/TestController.java index da0f3844..bcdee269 100644 --- a/src/main/java/org/bench4q/agent/api/TestController.java +++ b/src/main/java/org/bench4q/agent/api/TestController.java @@ -1,10 +1,16 @@ package org.bench4q.agent.api; +import java.io.ByteArrayOutputStream; import java.net.UnknownHostException; import java.util.ArrayList; 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.apache.log4j.Logger; import org.bench4q.agent.api.model.CleanTestResultModel; import org.bench4q.agent.api.model.ParameterModel; import org.bench4q.agent.api.model.RunScenarioModel; @@ -35,6 +41,11 @@ import org.springframework.web.bind.annotation.ResponseBody; @RequestMapping("/test") public class TestController { private ScenarioEngine scenarioEngine; + private Logger logger = Logger.getLogger(TestController.class); + + private Logger getLogger() { + return logger; + } private ScenarioEngine getScenarioEngine() { return scenarioEngine; @@ -52,15 +63,30 @@ public class TestController { throws UnknownHostException { Scenario scenario = extractScenario(runScenarioModel); UUID runId = UUID.randomUUID(); + System.out.println(runScenarioModel.getPoolSize()); + this.getLogger().info(marshalRunScenarioModel(runScenarioModel)); this.getScenarioEngine().runScenario(runId, scenario, runScenarioModel.getPoolSize(), runScenarioModel.getTotalCount()); RunScenarioResultModel runScenarioResultModel = new RunScenarioResultModel(); runScenarioResultModel.setRunId(runId); - return runScenarioResultModel; } + private String marshalRunScenarioModel(RunScenarioModel inModel) { + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + Marshaller marshaller; + try { + marshaller = JAXBContext.newInstance(RunScenarioModel.class) + .createMarshaller(); + marshaller.marshal(inModel, outputStream); + return outputStream.toString(); + } catch (JAXBException e) { + return "exception in marshal"; + } + + } + private Scenario extractScenario(RunScenarioModel runScenarioModel) { Scenario scenario = new Scenario(); scenario.setUsePlugins(new UsePlugin[runScenarioModel.getUsePlugins() diff --git a/src/main/resources/log4j.properties b/src/main/resources/log4j.properties new file mode 100644 index 00000000..92df3136 --- /dev/null +++ b/src/main/resources/log4j.properties @@ -0,0 +1,31 @@ +log4j.rootLogger = INFO,WARN,ERROR,FALTAL,D + +log4j.appender.WARN = org.apache.log4j.DailyRollingFileAppender +log4j.appender.WARN.File = logs/log.log +log4j.appender.WARN.Append = true +log4j.appender.WARN.Threshold = WARN +log4j.appender.WARN.layout = org.apache.log4j.PatternLayout +log4j.appender.WARN.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n + +log4j.appender.ERROR = org.apache.log4j.DailyRollingFileAppender +log4j.appender.ERROR.File = logs/log.log +log4j.appender.ERROR.Append = true +log4j.appender.ERROR.Threshold = ERROR +log4j.appender.ERROR.layout = org.apache.log4j.PatternLayout +log4j.appender.ERROR.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n + +log4j.appender.FALTAL = org.apache.log4j.DailyRollingFileAppender +log4j.appender.FALTAL.File = logs/log.log +log4j.appender.FALTAL.Append = true +log4j.appender.FALTAL.Threshold = ERROR +log4j.appender.FALTAL.layout = org.apache.log4j.PatternLayout +log4j.appender.FALTAL.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n + + +log4j.appender.D = org.apache.log4j.DailyRollingFileAppender +log4j.appender.D.File = logs/log.log +log4j.appender.D.Append = true +log4j.appender.D.Threshold = INFO +log4j.appender.D.layout = org.apache.log4j.PatternLayout +log4j.appender.D.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n + diff --git a/src/test/java/Communication/HttpRequester.java b/src/test/java/Communication/HttpRequester.java new file mode 100644 index 00000000..1c72da9d --- /dev/null +++ b/src/test/java/Communication/HttpRequester.java @@ -0,0 +1,276 @@ +package Communication; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +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 params, + Map properties) throws IOException { + return this.send(urlString, "POST", params, "", properties); + } + + public HttpResponse sendPostXml(String urlString, String contentString, + Map properties) throws IOException { + if (properties == null) { + properties = new HashMap(); + } + properties.put("Content-Type", "application/xml"); + return this.send(urlString, "POST", null, contentString, properties); + } + + public HttpResponse sendGet(String urlString, Map params, + Map properties) throws IOException { + return this.send(urlString, "GET", params, "", properties); + } + + private HttpResponse send(String urlString, String method, + Map parameters, String Content, + Map 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; + } + 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(); + } + return this.makeContent(urlString, urlConnection); + } + + private HttpResponse makeContent(String urlString, + HttpURLConnection urlConnection) { + HttpResponse httpResponser = new HttpResponse(); + try { + InputStream in = urlConnection.getInputStream(); + BufferedReader bufferedReader = new BufferedReader( + new InputStreamReader(in)); + httpResponser.contentCollection = new Vector(); + 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 (Exception 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 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 getContentCollection() { + return contentCollection; + } + + public void setContentCollection(Vector contentCollection) { + this.contentCollection = contentCollection; + } + + } +} diff --git a/src/test/java/org/bench4q/agent/test/TestWithScriptFile.java b/src/test/java/org/bench4q/agent/test/TestWithScriptFile.java new file mode 100644 index 00000000..75ef3042 --- /dev/null +++ b/src/test/java/org/bench4q/agent/test/TestWithScriptFile.java @@ -0,0 +1,93 @@ +package org.bench4q.agent.test; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.IOException; + +import javax.xml.bind.JAXBContext; +import javax.xml.bind.JAXBException; +import javax.xml.bind.Unmarshaller; + +import org.apache.commons.io.FileUtils; +import org.bench4q.agent.api.model.RunScenarioModel; + +import Communication.HttpRequester; + +public class TestWithScriptFile { + private HttpRequester httpRequester; + private String url = "http://localhost:6565/test/run"; + private String filePath; + private static int load = 300; + + public String getFilePath() { + return filePath; + } + + public void setFilePath(String filePath) { + this.filePath = filePath; + } + + public HttpRequester getHttpRequester() { + return httpRequester; + } + + public void setHttpRequester(HttpRequester httpRequester) { + this.httpRequester = httpRequester; + } + + public TestWithScriptFile() { + this.setFilePath("scripts" + System.getProperty("file.separator") + + "script.xml"); + this.setHttpRequester(new HttpRequester()); + } + + public void testWithScript() throws JAXBException { + File file = new File(this.getFilePath()); + if (!file.exists()) { + return; + } + String scriptContent; + try { + scriptContent = FileUtils.readFileToString(file); + RunScenarioModel runScenarioModel = extractRunScenarioModel(scriptContent); + if (runScenarioModel == null) { + System.out.println("can't execute an unvalid script"); + return; + } + runScenarioModel.setPoolSize(load); + + this.getHttpRequester().sendPostXml(this.url, + marshalRunScenarioModel(runScenarioModel), null); + } catch (IOException e) { + System.out.println("IO exception!"); + } + } + + private RunScenarioModel extractRunScenarioModel(String scriptContent) { + try { + Unmarshaller unmarshaller = JAXBContext.newInstance( + RunScenarioModel.class).createUnmarshaller(); + return (RunScenarioModel) unmarshaller + .unmarshal(new ByteArrayInputStream(scriptContent + .getBytes())); + } catch (JAXBException e) { + System.out.println("model unmarshal has an exception!"); + return null; + } + + } + + private String marshalRunScenarioModel(RunScenarioModel model) + throws JAXBException { + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + JAXBContext.newInstance(RunScenarioModel.class).createMarshaller() + .marshal(model, outputStream); + return outputStream.toString(); + } + + public static void main(String[] args) throws JAXBException { + TestWithScriptFile testWithScriptFile = new TestWithScriptFile(); + testWithScriptFile.testWithScript(); + } +} From 2a4e4baa863ace7a65ebcfd4bf9a0770f2f9b5f3 Mon Sep 17 00:00:00 2001 From: Tienan Chen Date: Thu, 31 Oct 2013 15:28:45 +0800 Subject: [PATCH 058/196] add some logger to record error --- .../org/bench4q/agent/scenario/ScenarioEngine.java | 13 +++++++++++++ .../org/bench4q/agent/test/TestWithScriptFile.java | 2 +- 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java b/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java index c656cfad..08fcabd1 100644 --- a/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java +++ b/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java @@ -15,6 +15,7 @@ import java.util.concurrent.Executors; import javax.xml.bind.JAXBContext; import javax.xml.bind.Marshaller; +import org.apache.log4j.Logger; import org.bench4q.agent.plugin.Plugin; import org.bench4q.agent.plugin.PluginManager; import org.bench4q.agent.storage.StorageHelper; @@ -27,9 +28,19 @@ public class ScenarioEngine { private Map runningTests; private StorageHelper storageHelper; private static int saveThreshold = 10000; + private Logger logger; + + private Logger getLogger() { + return logger; + } + + private void setLogger(Logger logger) { + this.logger = logger; + } public ScenarioEngine() { this.setRunningTests(new HashMap()); + this.setLogger(Logger.getLogger(ScenarioEngine.class)); } private PluginManager getPluginManager() { @@ -104,6 +115,8 @@ public class ScenarioEngine { for (UserBehavior userBehavior : scenario.getUserBehaviors()) { Object plugin = plugins.get(userBehavior.getUse()); String behaviorName = userBehavior.getName(); + this.getLogger().info( + "this step's behaviorName is : " + behaviorName); Map behaviorParameters = prepareBehaviorParameters(userBehavior); Date startDate = new Date(System.currentTimeMillis()); boolean success = (Boolean) this.getPluginManager().doBehavior( diff --git a/src/test/java/org/bench4q/agent/test/TestWithScriptFile.java b/src/test/java/org/bench4q/agent/test/TestWithScriptFile.java index 75ef3042..47a35a35 100644 --- a/src/test/java/org/bench4q/agent/test/TestWithScriptFile.java +++ b/src/test/java/org/bench4q/agent/test/TestWithScriptFile.java @@ -38,7 +38,7 @@ public class TestWithScriptFile { public TestWithScriptFile() { this.setFilePath("scripts" + System.getProperty("file.separator") - + "script.xml"); + + "scriptwithError.xml"); this.setHttpRequester(new HttpRequester()); } From fd39d25dc00b23b2fcd3e08f4bba0ff98a39ab78 Mon Sep 17 00:00:00 2001 From: Tienan Chen Date: Thu, 31 Oct 2013 17:02:42 +0800 Subject: [PATCH 059/196] add gitignore --- .gitignore | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index a8754446..36a59301 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,6 @@ .project .classpath /.settings -/target \ No newline at end of file +/target +/logs +/scripts From 6087ada96c5cb77c5b1c37f40327dbe7b930fdfc Mon Sep 17 00:00:00 2001 From: Tienan Chen Date: Mon, 4 Nov 2013 09:50:58 +0800 Subject: [PATCH 060/196] remove the totalCount member in the RunScenarioMdoel --- .../java/org/bench4q/agent/api/TestController.java | 4 +--- .../org/bench4q/agent/api/model/RunScenarioModel.java | 10 ---------- .../org/bench4q/agent/scenario/ScenarioContext.java | 9 --------- .../org/bench4q/agent/scenario/ScenarioEngine.java | 7 +++---- 4 files changed, 4 insertions(+), 26 deletions(-) diff --git a/src/main/java/org/bench4q/agent/api/TestController.java b/src/main/java/org/bench4q/agent/api/TestController.java index bcdee269..6c96c5c6 100644 --- a/src/main/java/org/bench4q/agent/api/TestController.java +++ b/src/main/java/org/bench4q/agent/api/TestController.java @@ -66,8 +66,7 @@ public class TestController { System.out.println(runScenarioModel.getPoolSize()); this.getLogger().info(marshalRunScenarioModel(runScenarioModel)); this.getScenarioEngine().runScenario(runId, scenario, - runScenarioModel.getPoolSize(), - runScenarioModel.getTotalCount()); + runScenarioModel.getPoolSize()); RunScenarioResultModel runScenarioResultModel = new RunScenarioResultModel(); runScenarioResultModel.setRunId(runId); return runScenarioResultModel; @@ -263,7 +262,6 @@ public class TestController { testBriefStatusModel.setFailCount(failCount); testBriefStatusModel.setSuccessCount(successCount); testBriefStatusModel.setFinishedCount(behaviorResults.size()); - // testBriefStatusModel.setTotalCount(scenarioContext.getTotalCount()); testBriefStatusModel.setScenarioBehaviorCount(scenarioContext .getScenario().getUserBehaviors().length); testBriefStatusModel.setRunningTime(maxDate - minDate); diff --git a/src/main/java/org/bench4q/agent/api/model/RunScenarioModel.java b/src/main/java/org/bench4q/agent/api/model/RunScenarioModel.java index 7d8cf9bd..ba6ecfa2 100644 --- a/src/main/java/org/bench4q/agent/api/model/RunScenarioModel.java +++ b/src/main/java/org/bench4q/agent/api/model/RunScenarioModel.java @@ -9,7 +9,6 @@ import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement(name = "runScenario") public class RunScenarioModel { private int poolSize; - private int totalCount; private List usePlugins; private List userBehaviors; @@ -22,15 +21,6 @@ public class RunScenarioModel { 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 getUsePlugins() { diff --git a/src/main/java/org/bench4q/agent/scenario/ScenarioContext.java b/src/main/java/org/bench4q/agent/scenario/ScenarioContext.java index 3beb80d5..f0427e33 100644 --- a/src/main/java/org/bench4q/agent/scenario/ScenarioContext.java +++ b/src/main/java/org/bench4q/agent/scenario/ScenarioContext.java @@ -6,7 +6,6 @@ import java.util.concurrent.ExecutorService; public class ScenarioContext { private int poolSize; - private int totalCount; private int finishedCount; private Date saveStartDate; private Date saveStopDate; @@ -24,14 +23,6 @@ public class ScenarioContext { this.poolSize = poolSize; } - public int getTotalCount() { - return totalCount; - } - - public void setTotalCount(int totalCount) { - this.totalCount = totalCount; - } - public int getFinishedCount() { return finishedCount; } diff --git a/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java b/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java index 08fcabd1..b1ce1530 100644 --- a/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java +++ b/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java @@ -69,15 +69,14 @@ public class ScenarioEngine { this.runningTests = runningTests; } - public void runScenario(UUID runId, final Scenario scenario, int poolSize, - int totalCount) { + public void runScenario(UUID runId, final Scenario scenario, int poolSize) { try { ExecutorService executorService = Executors .newFixedThreadPool(poolSize); final List ret = Collections .synchronizedList(new ArrayList()); final ScenarioContext scenarioContext = buildScenarioContext( - scenario, poolSize, totalCount, executorService, ret); + scenario, poolSize, executorService, ret); int i; this.getRunningTests().put(runId, scenarioContext); Runnable runnable = new Runnable() { @@ -96,7 +95,7 @@ public class ScenarioEngine { } private ScenarioContext buildScenarioContext(final Scenario scenario, - int poolSize, int totalCount, ExecutorService executorService, + int poolSize, ExecutorService executorService, final List ret) { ScenarioContext scenarioContext = new ScenarioContext(); scenarioContext.setScenario(scenario); From 5ffb3a6f3ef1334f6f54ec526e5768c54e59c0b7 Mon Sep 17 00:00:00 2001 From: Tienan Chen Date: Tue, 12 Nov 2013 15:37:47 +0800 Subject: [PATCH 061/196] let the brief statistics compute correcty, it will only count the behavior result in this time frame beside the cumulative ones like totalSuccesfulCount --- .../org/bench4q/agent/api/TestController.java | 18 +++++++++++++++--- .../bench4q/agent/scenario/BehaviorResult.java | 16 ++++++++++++++++ 2 files changed, 31 insertions(+), 3 deletions(-) diff --git a/src/main/java/org/bench4q/agent/api/TestController.java b/src/main/java/org/bench4q/agent/api/TestController.java index 6c96c5c6..2f462e9d 100644 --- a/src/main/java/org/bench4q/agent/api/TestController.java +++ b/src/main/java/org/bench4q/agent/api/TestController.java @@ -229,6 +229,7 @@ public class TestController { int failCount = 0; int successCount = 0; long totalResponseTime = 0; + long maxResponseTime = 0, minResponseTime = Long.MAX_VALUE; List behaviorResults = new ArrayList( scenarioContext.getResults()); long maxDate = 0, minDate = Long.MAX_VALUE; @@ -245,10 +246,21 @@ public class TestController { } else { failCount++; } - if (!behaviorResult.getPluginName().contains("Timer")) { - totalResponseTime += behaviorResult.getResponseTime(); - validCount++; + if (behaviorResult.getPluginName().contains("Timer")) { + continue; } + if (behaviorResult.isCalculated()) { + continue; + } + if (behaviorResult.getResponseTime() > maxResponseTime) { + maxResponseTime = behaviorResult.getResponseTime(); + } + if (behaviorResult.getResponseTime() < minResponseTime) { + minResponseTime = behaviorResult.getResponseTime(); + } + totalResponseTime += behaviorResult.getResponseTime(); + validCount++; + behaviorResult.setCalculated(true); } if (validCount == 0) { return null; diff --git a/src/main/java/org/bench4q/agent/scenario/BehaviorResult.java b/src/main/java/org/bench4q/agent/scenario/BehaviorResult.java index 6e38cfc1..c9c0bc6f 100644 --- a/src/main/java/org/bench4q/agent/scenario/BehaviorResult.java +++ b/src/main/java/org/bench4q/agent/scenario/BehaviorResult.java @@ -12,6 +12,7 @@ public class BehaviorResult { private Date endDate; private long responseTime; private boolean success; + private boolean calculated; public UUID getId() { return id; @@ -77,4 +78,19 @@ public class BehaviorResult { this.success = success; } + public boolean isCalculated() { + return calculated; + } + + public void setCalculated(boolean calculated) { + this.calculated = calculated; + } + + public BehaviorResult() { + this.setCalculated(false); + } + + public long getExecuteDuration() { + return this.getEndDate().getTime() - this.getStartDate().getTime(); + } } From 0df812dae165d6152c31d86cb7e3ebf51fb829ee Mon Sep 17 00:00:00 2001 From: Tienan Chen Date: Wed, 13 Nov 2013 15:38:56 +0800 Subject: [PATCH 062/196] add DataCollector module to agent,next step i'll all use this module --- .../org/bench4q/agent/api/TestController.java | 40 +--- .../api/model/AgentBriefStatusModel.java | 139 +++++++++++++ .../agent/api/model/SaveTestResultModel.java | 19 -- .../agent/api/model/TestDetailModel.java | 33 +++ .../impl/AbstractDataCollector.java | 52 +++++ .../impl/AgentResultDataCollector.java | 195 ++++++++++++++++++ .../interfaces/DataStatistics.java | 11 + .../agent/scenario/ScenarioContext.java | 62 +++--- .../agent/scenario/ScenarioEngine.java | 140 +------------ .../bench4q/agent/storage/LocalStorage.java | 5 + .../agent/test/DataStatisticsTest.java | 136 ++++++++++++ 11 files changed, 602 insertions(+), 230 deletions(-) create mode 100644 src/main/java/org/bench4q/agent/api/model/AgentBriefStatusModel.java delete mode 100644 src/main/java/org/bench4q/agent/api/model/SaveTestResultModel.java create mode 100644 src/main/java/org/bench4q/agent/datacollector/impl/AbstractDataCollector.java create mode 100644 src/main/java/org/bench4q/agent/datacollector/impl/AgentResultDataCollector.java create mode 100644 src/main/java/org/bench4q/agent/datacollector/interfaces/DataStatistics.java create mode 100644 src/test/java/org/bench4q/agent/test/DataStatisticsTest.java diff --git a/src/main/java/org/bench4q/agent/api/TestController.java b/src/main/java/org/bench4q/agent/api/TestController.java index 2f462e9d..a98443f7 100644 --- a/src/main/java/org/bench4q/agent/api/TestController.java +++ b/src/main/java/org/bench4q/agent/api/TestController.java @@ -15,7 +15,6 @@ import org.bench4q.agent.api.model.CleanTestResultModel; import org.bench4q.agent.api.model.ParameterModel; import org.bench4q.agent.api.model.RunScenarioModel; import org.bench4q.agent.api.model.RunScenarioResultModel; -import org.bench4q.agent.api.model.SaveTestResultModel; import org.bench4q.agent.api.model.StopTestModel; import org.bench4q.agent.api.model.TestBriefStatusModel; import org.bench4q.agent.api.model.TestDetailModel; @@ -183,14 +182,8 @@ public class TestController { long totalResponseTime = 0; int validCount = 0; for (BehaviorResult behaviorResult : behaviorResults) { - TestDetailModel testDetailModel = new TestDetailModel(); - testDetailModel.setBehaviorName(behaviorResult.getBehaviorName()); - testDetailModel.setEndDate(behaviorResult.getEndDate()); - testDetailModel.setPluginId(behaviorResult.getPluginId()); - testDetailModel.setPluginName(behaviorResult.getPluginName()); - testDetailModel.setResponseTime(behaviorResult.getResponseTime()); - testDetailModel.setStartDate(behaviorResult.getStartDate()); - testDetailModel.setSuccess(behaviorResult.isSuccess()); + TestDetailModel testDetailModel = new TestDetailModel( + behaviorResult); testStatusModel.getTestDetailModels().add(testDetailModel); if (testDetailModel.getEndDate().getTime() > maxDate) { maxDate = testDetailModel.getEndDate().getTime(); @@ -314,33 +307,4 @@ public class TestController { cleanTestResultModel.setSuccess(true); return cleanTestResultModel; } - - @RequestMapping(value = "/save/{runId}", method = RequestMethod.GET) - @ResponseBody - public SaveTestResultModel save(@PathVariable UUID runId) { - this.getScenarioEngine().saveTestResults(runId); - SaveTestResultModel saveTestResultModel = new SaveTestResultModel(); - saveTestResultModel.setSuccess(true); - return saveTestResultModel; - } - - @RequestMapping(value = "/startSave/{runId}", method = { RequestMethod.GET, - RequestMethod.POST }) - @ResponseBody - public SaveTestResultModel startSave(@PathVariable UUID runId) { - this.getScenarioEngine().startSaveResultsWithEdit(runId); - SaveTestResultModel saveTestResultModel = new SaveTestResultModel(); - saveTestResultModel.setSuccess(true); - return saveTestResultModel; - } - - @RequestMapping(value = "/stopSave/{runId}", method = { RequestMethod.GET, - RequestMethod.POST }) - @ResponseBody - public SaveTestResultModel stopSave(@PathVariable UUID runId) { - this.getScenarioEngine().stopSaveResultWithEdit(runId); - SaveTestResultModel saveTestResultModel = new SaveTestResultModel(); - saveTestResultModel.setSuccess(true); - return saveTestResultModel; - } } diff --git a/src/main/java/org/bench4q/agent/api/model/AgentBriefStatusModel.java b/src/main/java/org/bench4q/agent/api/model/AgentBriefStatusModel.java new file mode 100644 index 00000000..7159fd0f --- /dev/null +++ b/src/main/java/org/bench4q/agent/api/model/AgentBriefStatusModel.java @@ -0,0 +1,139 @@ +package org.bench4q.agent.api.model; + +import java.lang.reflect.Field; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; + +@XmlRootElement +public class AgentBriefStatusModel { + private long timeFrame; + private long averageResponseTime; + private long minResponseTime; + private long maxResponseTime; + private long totalCountFromBegin; + private long successThroughput; + private long failCountFromBegin; + private long failThroughput; + private long failRate; + private long responseTimeDeviation; + + @XmlElement + public long getTimeFrame() { + return timeFrame; + } + + public void setTimeFrame(long timeFrame) { + this.timeFrame = timeFrame; + } + + @XmlElement + public long getAverageResponseTime() { + return averageResponseTime; + } + + public void setAverageResponseTime(long averageResponseTime) { + this.averageResponseTime = averageResponseTime; + } + + @XmlElement + public long getMinResponseTime() { + return minResponseTime; + } + + public void setMinResponseTime(long minResponseTime) { + this.minResponseTime = minResponseTime; + } + + @XmlElement + public long getMaxResponseTime() { + return maxResponseTime; + } + + public void setMaxResponseTime(long maxResponseTime) { + this.maxResponseTime = maxResponseTime; + } + + @XmlElement + public long getSuccessThroughput() { + return successThroughput; + } + + public void setSuccessThroughput(long behaviorThroughput) { + this.successThroughput = behaviorThroughput; + } + + @XmlElement + public long getTotalCountFromBegin() { + return totalCountFromBegin; + } + + public void setTotalCountFromBegin(long totalCountFromBegin) { + this.totalCountFromBegin = totalCountFromBegin; + } + + @XmlElement + public long getFailCountFromBegin() { + return failCountFromBegin; + } + + public void setFailCountFromBegin(long failCountFromBegin) { + this.failCountFromBegin = failCountFromBegin; + } + + @XmlElement + public long getFailThroughput() { + return failThroughput; + } + + public void setFailThroughput(long failThroughput) { + this.failThroughput = failThroughput; + } + + @XmlElement + public long getFailRate() { + return failRate; + } + + public void setFailRate(long failRate) { + this.failRate = failRate; + } + + @XmlElement + public long getResponseTimeDeviation() { + return responseTimeDeviation; + } + + public void setResponseTimeDeviation(long responseTimeDeviation) { + this.responseTimeDeviation = responseTimeDeviation; + } + + // if the all the fields of target object equals with this's except + // timeFrame, + // We call it equals. + @Override + public boolean equals(Object targetObj) { + if (!(targetObj instanceof AgentBriefStatusModel)) { + return false; + } + boolean result = true; + AgentBriefStatusModel convertedObject = (AgentBriefStatusModel) targetObj; + Field[] fs = this.getClass().getDeclaredFields(); + try { + for (Field field : fs) { + field.setAccessible(true); + if (field.getLong(this) != field.getLong(convertedObject)) { + System.out.println(field.getName() + + " not equals! and the target is " + + field.getLong(convertedObject) + " and this is " + + field.getLong(this)); + result = false; + } + } + } catch (Exception e) { + e.printStackTrace(); + result = false; + } + return result; + } +} diff --git a/src/main/java/org/bench4q/agent/api/model/SaveTestResultModel.java b/src/main/java/org/bench4q/agent/api/model/SaveTestResultModel.java deleted file mode 100644 index 9fdff373..00000000 --- a/src/main/java/org/bench4q/agent/api/model/SaveTestResultModel.java +++ /dev/null @@ -1,19 +0,0 @@ -package org.bench4q.agent.api.model; - -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; - -@XmlRootElement(name = "saveTestResult") -public class SaveTestResultModel { - private boolean success; - - @XmlElement - public boolean isSuccess() { - return success; - } - - public void setSuccess(boolean success) { - this.success = success; - } - -} diff --git a/src/main/java/org/bench4q/agent/api/model/TestDetailModel.java b/src/main/java/org/bench4q/agent/api/model/TestDetailModel.java index 07efb0cc..3ece7270 100644 --- a/src/main/java/org/bench4q/agent/api/model/TestDetailModel.java +++ b/src/main/java/org/bench4q/agent/api/model/TestDetailModel.java @@ -1,10 +1,16 @@ package org.bench4q.agent.api.model; +import java.io.ByteArrayOutputStream; import java.util.Date; +import javax.xml.bind.JAXBContext; +import javax.xml.bind.JAXBException; +import javax.xml.bind.Marshaller; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; +import org.bench4q.agent.scenario.BehaviorResult; + @XmlRootElement(name = "testDetail") public class TestDetailModel { private String pluginId; @@ -77,4 +83,31 @@ public class TestDetailModel { public void setSuccess(boolean success) { this.success = success; } + + public TestDetailModel() { + } + + public TestDetailModel(BehaviorResult behaviorResult) { + this.setBehaviorName(behaviorResult.getBehaviorName()); + this.setEndDate(behaviorResult.getEndDate()); + this.setPluginId(behaviorResult.getPluginId()); + this.setPluginName(behaviorResult.getPluginName()); + this.setResponseTime(behaviorResult.getResponseTime()); + this.setStartDate(behaviorResult.getStartDate()); + this.setSuccess(behaviorResult.isSuccess()); + } + + public String getModelString() { + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + Marshaller marshaller; + try { + marshaller = JAXBContext.newInstance(TestDetailModel.class) + .createMarshaller(); + marshaller.marshal(this, outputStream); + return outputStream.toString(); + } catch (JAXBException e) { + e.printStackTrace(); + return ""; + } + } } diff --git a/src/main/java/org/bench4q/agent/datacollector/impl/AbstractDataCollector.java b/src/main/java/org/bench4q/agent/datacollector/impl/AbstractDataCollector.java new file mode 100644 index 00000000..7f25c431 --- /dev/null +++ b/src/main/java/org/bench4q/agent/datacollector/impl/AbstractDataCollector.java @@ -0,0 +1,52 @@ +package org.bench4q.agent.datacollector.impl; + +import java.net.InetAddress; +import java.net.UnknownHostException; +import java.util.List; + +import org.apache.log4j.Logger; +import org.bench4q.agent.api.model.TestDetailModel; +import org.bench4q.agent.datacollector.interfaces.DataStatistics; +import org.bench4q.agent.scenario.BehaviorResult; +import org.bench4q.agent.storage.StorageHelper; +import org.springframework.beans.factory.annotation.Autowired; + +public abstract class AbstractDataCollector implements DataStatistics { + protected StorageHelper storageHelper; + private Logger logger = Logger.getLogger(AbstractDataCollector.class); + + protected StorageHelper getStorageHelper() { + return storageHelper; + } + + @Autowired + public void setStorageHelper(StorageHelper storageHelper) { + this.storageHelper = storageHelper; + } + + protected String getHostName() { + InetAddress addr; + try { + addr = InetAddress.getLocalHost(); + return addr.getHostAddress().toString(); + } catch (UnknownHostException e) { + this.logger + .error("There is an exception when get hostName of this machine!"); + return null; + } + } + + public void add(List behaviorResults) { + for (BehaviorResult behaviorResult : behaviorResults) { + TestDetailModel testDetailModel = new TestDetailModel( + behaviorResult); + this.getStorageHelper().getLocalStorage() + .writeFile(testDetailModel.getModelString(), getSavePath()); + } + } + + protected abstract String getSavePath(); + + public abstract Object getBriefStatistics(); + +} diff --git a/src/main/java/org/bench4q/agent/datacollector/impl/AgentResultDataCollector.java b/src/main/java/org/bench4q/agent/datacollector/impl/AgentResultDataCollector.java new file mode 100644 index 00000000..0eab580b --- /dev/null +++ b/src/main/java/org/bench4q/agent/datacollector/impl/AgentResultDataCollector.java @@ -0,0 +1,195 @@ +package org.bench4q.agent.datacollector.impl; + +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.List; +import java.util.UUID; + +import org.bench4q.agent.api.model.AgentBriefStatusModel; +import org.bench4q.agent.scenario.BehaviorResult; + +public class AgentResultDataCollector extends AbstractDataCollector { + private long timeOfPreviousCall; + private long failCountOfThisCall; + private long successCountOfThisCall; + private long totalResponseTimeOfThisCall; + private long maxResponseTimeOfThisCall; + private long minResponseTimeOfThisCall; + private long totalSqureResponseTimeOfThisCall; + private long cumulativeSucessfulCount; + private long cumulativeFailCount; + private static long TIME_UNIT = 1000; + private UUID testID; + + private void setTimeOfPreviousCall(long timeOfPreviousCall) { + this.timeOfPreviousCall = timeOfPreviousCall; + } + + private long getFailCountOfThisCall() { + return failCountOfThisCall; + } + + private void setFailCountOfThisCall(long failCountOfThisCall) { + this.failCountOfThisCall = failCountOfThisCall; + } + + private long getSuccessCountOfThisCall() { + return successCountOfThisCall; + } + + private void setSuccessCountOfThisCall(long successCountOfThisCall) { + this.successCountOfThisCall = successCountOfThisCall; + } + + private void setTotalResponseTimeOfThisCall(long totalResponseTimeOfThisCall) { + this.totalResponseTimeOfThisCall = totalResponseTimeOfThisCall; + } + + private long getMaxResponseTimeOfThisCall() { + return maxResponseTimeOfThisCall; + } + + private void setMaxResponseTimeOfThisCall(long maxResponseTimeOfThisCall) { + this.maxResponseTimeOfThisCall = maxResponseTimeOfThisCall; + } + + private long getMinResponseTimeOfThisCall() { + return minResponseTimeOfThisCall; + } + + private void setMinResponseTimeOfThisCall(long minResponseTimeOfThisCall) { + this.minResponseTimeOfThisCall = minResponseTimeOfThisCall; + } + + private void setTotalSqureResponseTimeOfThisCall( + long totalSqureResponseTimeOfThisCall) { + this.totalSqureResponseTimeOfThisCall = totalSqureResponseTimeOfThisCall; + } + + private void setCumulativeSucessfulCount(long cumulativeSucessfulCount) { + this.cumulativeSucessfulCount = cumulativeSucessfulCount; + } + + private void setCumulativeFailCount(long cumulativeFailCount) { + this.cumulativeFailCount = cumulativeFailCount; + } + + private String getTestID() { + return testID == null ? "default" : testID.toString(); + } + + public void setTestID(UUID testID) { + this.testID = testID; + } + + public AgentResultDataCollector() { + init(); + } + + private void init() { + reset(); + this.setCumulativeFailCount(0); + this.setCumulativeSucessfulCount(0); + } + + private void reset() { + this.setTimeOfPreviousCall(System.currentTimeMillis()); + this.setFailCountOfThisCall(0); + this.setMaxResponseTimeOfThisCall(Long.MIN_VALUE); + this.setMinResponseTimeOfThisCall(Long.MAX_VALUE); + this.setSuccessCountOfThisCall(0); + this.setTotalResponseTimeOfThisCall(0); + this.setTotalSqureResponseTimeOfThisCall(0); + } + + // /////////////////////////////// + // DataStatistics Interface start + // /////////////////////////////// + + public void add(List behaviorResults) { + super.add(behaviorResults); + for (BehaviorResult behaviorResult : behaviorResults) { + addItem(behaviorResult); + } + } + + public AgentBriefStatusModel getBriefStatistics() { + AgentBriefStatusModel result = new AgentBriefStatusModel(); + result.setTimeFrame(System.currentTimeMillis() + - this.timeOfPreviousCall); + if (this.getSuccessCountOfThisCall() == 0) { + result.setAverageResponseTime(0); + result.setMaxResponseTime(0); + result.setMinResponseTime(0); + result.setResponseTimeDeviation(0); + if (this.getFailCountOfThisCall() == 0) { + result.setFailRate(0); + } else { + result.setFailRate(100); + } + } else { + result.setAverageResponseTime(this.totalResponseTimeOfThisCall + / this.successCountOfThisCall); + result.setFailRate(this.failCountOfThisCall + / (this.successCountOfThisCall + this.failCountOfThisCall)); + result.setMinResponseTime(this.minResponseTimeOfThisCall); + result.setMaxResponseTime(this.maxResponseTimeOfThisCall); + result.setResponseTimeDeviation(Math.round(Math + .sqrt(this.totalSqureResponseTimeOfThisCall + / this.successCountOfThisCall + - result.getAverageResponseTime() + * result.getAverageResponseTime()))); + + } + this.cumulativeSucessfulCount += this.successCountOfThisCall; + result.setTotalCountFromBegin(this.cumulativeSucessfulCount); + this.cumulativeFailCount += this.failCountOfThisCall; + result.setFailCountFromBegin(this.cumulativeFailCount); + if (result.getTimeFrame() == 0) { + result.setSuccessThroughput(0); + result.setFailThroughput(0); + } else { + result.setSuccessThroughput(this.successCountOfThisCall + * TIME_UNIT / result.getTimeFrame()); + result.setFailThroughput(this.failCountOfThisCall * TIME_UNIT + / result.getTimeFrame()); + } + reset(); + return result; + } + + // /////////////////////////////// + // DataStatistics Interface end + // /////////////////////////////// + + private void addItem(BehaviorResult behaviorResult) { + if (behaviorResult.isSuccess()) { + this.successCountOfThisCall++; + this.totalResponseTimeOfThisCall += behaviorResult + .getResponseTime(); + this.totalSqureResponseTimeOfThisCall += ((long) behaviorResult + .getResponseTime()) * behaviorResult.getResponseTime(); + if (behaviorResult.getResponseTime() > this + .getMaxResponseTimeOfThisCall()) { + this.setMaxResponseTimeOfThisCall(behaviorResult + .getResponseTime()); + } + if (behaviorResult.getResponseTime() < this + .getMinResponseTimeOfThisCall()) { + this.setMinResponseTimeOfThisCall(behaviorResult + .getResponseTime()); + } + } else { + this.failCountOfThisCall++; + } + } + + @Override + protected String getSavePath() { + return "DetailResults" + System.getProperty("file.separator") + + new SimpleDateFormat("yyyyMMdd").format(new Date()) + + System.getProperty("file.separator") + this.getTestID() + + ".txt"; + } + +} diff --git a/src/main/java/org/bench4q/agent/datacollector/interfaces/DataStatistics.java b/src/main/java/org/bench4q/agent/datacollector/interfaces/DataStatistics.java new file mode 100644 index 00000000..1757d98e --- /dev/null +++ b/src/main/java/org/bench4q/agent/datacollector/interfaces/DataStatistics.java @@ -0,0 +1,11 @@ +package org.bench4q.agent.datacollector.interfaces; + +import java.util.List; + +import org.bench4q.agent.scenario.BehaviorResult; + +public interface DataStatistics { + public void add(List behaviorResults); + + public Object getBriefStatistics(); +} diff --git a/src/main/java/org/bench4q/agent/scenario/ScenarioContext.java b/src/main/java/org/bench4q/agent/scenario/ScenarioContext.java index f0427e33..63760cbb 100644 --- a/src/main/java/org/bench4q/agent/scenario/ScenarioContext.java +++ b/src/main/java/org/bench4q/agent/scenario/ScenarioContext.java @@ -4,47 +4,23 @@ import java.util.Date; import java.util.List; import java.util.concurrent.ExecutorService; +import org.bench4q.agent.datacollector.impl.AgentResultDataCollector; +import org.bench4q.agent.datacollector.interfaces.DataStatistics; + public class ScenarioContext { - private int poolSize; - private int finishedCount; - private Date saveStartDate; - private Date saveStopDate; + private Date startDate; private ExecutorService executorService; private Scenario scenario; private List results; private boolean finished; - private boolean toSave; - - public int getPoolSize() { - return poolSize; - } - - public void setPoolSize(int poolSize) { - this.poolSize = poolSize; - } - - public int getFinishedCount() { - return finishedCount; - } - - public void setFinishedCount(int finishedCount) { - this.finishedCount = finishedCount; - } + private DataStatistics dataStatistics; public Date getStartDate() { - return saveStartDate; + return startDate; } - public void setSaveStartDate(Date saveStartDate) { - this.saveStartDate = saveStartDate; - } - - public Date getSaveStopDate() { - return saveStopDate; - } - - public void setStopDate(Date saveStopDate) { - this.saveStopDate = saveStopDate; + public void setStartDate(Date saveStartDate) { + this.startDate = saveStartDate; } public ExecutorService getExecutorService() { @@ -79,12 +55,26 @@ public class ScenarioContext { this.finished = finished; } - public boolean isToSave() { - return toSave; + public DataStatistics getDataStatistics() { + return dataStatistics; } - public void setToSave(boolean startToSave) { - this.toSave = startToSave; + private void setDataStatistics(DataStatistics dataStatistics) { + this.dataStatistics = dataStatistics; } + private ScenarioContext() { + } + + public static ScenarioContext buildScenarioContext(final Scenario scenario, + int poolSize, ExecutorService executorService, + final List ret) { + ScenarioContext scenarioContext = new ScenarioContext(); + scenarioContext.setScenario(scenario); + scenarioContext.setStartDate(new Date(System.currentTimeMillis())); + scenarioContext.setExecutorService(executorService); + scenarioContext.setResults(ret); + scenarioContext.setDataStatistics(new AgentResultDataCollector()); + return scenarioContext; + } } diff --git a/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java b/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java index b1ce1530..9c71419a 100644 --- a/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java +++ b/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java @@ -1,7 +1,6 @@ package org.bench4q.agent.scenario; import java.io.File; -import java.io.StringWriter; import java.util.ArrayList; import java.util.Collections; import java.util.Date; @@ -12,9 +11,6 @@ import java.util.UUID; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; -import javax.xml.bind.JAXBContext; -import javax.xml.bind.Marshaller; - import org.apache.log4j.Logger; import org.bench4q.agent.plugin.Plugin; import org.bench4q.agent.plugin.PluginManager; @@ -27,7 +23,6 @@ public class ScenarioEngine { private PluginManager pluginManager; private Map runningTests; private StorageHelper storageHelper; - private static int saveThreshold = 10000; private Logger logger; private Logger getLogger() { @@ -75,8 +70,9 @@ public class ScenarioEngine { .newFixedThreadPool(poolSize); final List ret = Collections .synchronizedList(new ArrayList()); - final ScenarioContext scenarioContext = buildScenarioContext( - scenario, poolSize, executorService, ret); + final ScenarioContext scenarioContext = ScenarioContext + .buildScenarioContext(scenario, poolSize, executorService, + ret); int i; this.getRunningTests().put(runId, scenarioContext); Runnable runnable = new Runnable() { @@ -94,18 +90,6 @@ public class ScenarioEngine { } } - private ScenarioContext buildScenarioContext(final Scenario scenario, - int poolSize, ExecutorService executorService, - final List ret) { - ScenarioContext scenarioContext = new ScenarioContext(); - scenarioContext.setScenario(scenario); - scenarioContext.setPoolSize(poolSize); - scenarioContext.setSaveStartDate(new Date(System.currentTimeMillis())); - scenarioContext.setExecutorService(executorService); - scenarioContext.setResults(ret); - return scenarioContext; - } - public List doRunScenario(Scenario scenario) { Map plugins = new HashMap(); preparePlugins(scenario, plugins); @@ -190,122 +174,4 @@ public class ScenarioEngine { } return directory; } - - public void startSaveResultsWithEdit(UUID runId) { - ScenarioContext scenarioContext = this.getRunningTests().get(runId); - if (scenarioContext == null) { - return; - } - - scenarioContext.setSaveStartDate(new Date(System.currentTimeMillis())); - scenarioContext.setToSave(true); - - while (scenarioContext.isToSave() - && scenarioContext.getResults().size() >= saveThreshold) { - // saveTestResults(runId); - } - } - - public void stopSaveResultWithEdit(UUID runId) { - ScenarioContext scenarioContext = this.getRunningTests().get(runId); - if (scenarioContext == null) { - return; - } - scenarioContext.setStopDate(new Date(System.currentTimeMillis())); - scenarioContext.setToSave(false); - } - - public void saveTestResults(UUID runId) { - ScenarioContext scenarioContext = this.getRunningTests().get(runId); - if (scenarioContext == null) { - return; - } - List results = new ArrayList(); - List behaviorResults = new ArrayList( - scenarioContext.getResults()); - int failCount = 0; - int successCount = 0; - long totalResponseTime = 0; - long maxDate = 0; - int validCount = 0; - for (BehaviorResult behaviorResult : behaviorResults) { - if (behaviorResult.getEndDate().getTime() > maxDate) { - maxDate = behaviorResult.getEndDate().getTime(); - } - if (behaviorResult.isSuccess()) { - successCount++; - } else { - failCount++; - } - if (!behaviorResult.getPluginName().contains("Timer")) { - totalResponseTime += behaviorResult.getResponseTime(); - validCount++; - } - results.add(buildTestResultItem(behaviorResult)); - } - TestResult testResult = buildTestResult(runId, scenarioContext, - results, behaviorResults, failCount, successCount, - totalResponseTime, maxDate, validCount); - doSaveTestResults(runId, testResult); - } - - private void doSaveTestResults(UUID runId, TestResult testResult) { - StringWriter stringWriter = null; - try { - Marshaller marshaller = JAXBContext.newInstance( - testResult.getClass()).createMarshaller(); - marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); - stringWriter = new StringWriter(); - String fileName = this.getLocalPath() + "/" + runId.toString() - + ".xml"; - marshaller.marshal(testResult, stringWriter); - String content = stringWriter.toString(); - this.getStorageHelper().getLocalStorage() - .writeFile(content, fileName); - } catch (Exception e) { - e.printStackTrace(); - } finally { - if (stringWriter != null) { - try { - stringWriter.close(); - } catch (Exception e) { - e.printStackTrace(); - } - } - } - } - - private TestResult buildTestResult(UUID runId, - ScenarioContext scenarioContext, List results, - List behaviorResults, int failCount, - int successCount, long totalResponseTime, long maxDate, - int validCount) { - TestResult testResult = new TestResult(); - testResult.setResults(results); - testResult.setStartDate(scenarioContext.getStartDate()); - // testResult.setTotalCount(scenarioContext.getTotalCount()); - testResult.setRunId(runId); - testResult.setPoolSize(scenarioContext.getPoolSize()); - testResult.setAverageResponseTime((totalResponseTime + 0.0) - / validCount); - testResult - .setElapsedTime(maxDate - testResult.getStartDate().getTime()); - testResult.setFailCount(failCount); - testResult.setSuccessCount(successCount); - testResult.setFinishedCount(behaviorResults.size()); - return testResult; - } - - private TestResultItem buildTestResultItem(BehaviorResult behaviorResult) { - TestResultItem testResultItem = new TestResultItem(); - testResultItem.setBehaviorName(behaviorResult.getBehaviorName()); - testResultItem.setEndDate(behaviorResult.getEndDate()); - testResultItem.setId(behaviorResult.getId()); - testResultItem.setPluginId(behaviorResult.getPluginId()); - testResultItem.setPluginName(behaviorResult.getPluginName()); - testResultItem.setResponseTime(behaviorResult.getResponseTime()); - testResultItem.setStartDate(behaviorResult.getStartDate()); - testResultItem.setSuccess(behaviorResult.isSuccess()); - return testResultItem; - } } diff --git a/src/main/java/org/bench4q/agent/storage/LocalStorage.java b/src/main/java/org/bench4q/agent/storage/LocalStorage.java index 9f771605..c96f1c94 100644 --- a/src/main/java/org/bench4q/agent/storage/LocalStorage.java +++ b/src/main/java/org/bench4q/agent/storage/LocalStorage.java @@ -30,6 +30,11 @@ public class LocalStorage implements Storage { public boolean writeFile(String content, String path) { try { + File file = new File(path.substring(path.lastIndexOf(System + .getProperty("file.separator")))); + if (!file.exists()) { + file.mkdirs(); + } OutputStreamWriter outputStreamWriter = new OutputStreamWriter( new FileOutputStream(new File(path)), "UTF-8"); outputStreamWriter.write(content); diff --git a/src/test/java/org/bench4q/agent/test/DataStatisticsTest.java b/src/test/java/org/bench4q/agent/test/DataStatisticsTest.java new file mode 100644 index 00000000..92a43579 --- /dev/null +++ b/src/test/java/org/bench4q/agent/test/DataStatisticsTest.java @@ -0,0 +1,136 @@ +package org.bench4q.agent.test; + +import static org.junit.Assert.*; + +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.UUID; + +import org.bench4q.agent.api.model.AgentBriefStatusModel; +import org.bench4q.agent.datacollector.impl.AgentResultDataCollector; +import org.bench4q.agent.datacollector.interfaces.DataStatistics; +import org.bench4q.agent.scenario.BehaviorResult; +import org.bench4q.agent.storage.StorageHelper; +import org.junit.Test; +import org.springframework.context.ApplicationContext; +import org.springframework.context.support.ClassPathXmlApplicationContext; + +public class DataStatisticsTest { + private DataStatistics dataStatistics; + + private DataStatistics getDataStatistics() { + return dataStatistics; + } + + private void setDataStatistics(DataStatistics dataStatistics) { + this.dataStatistics = dataStatistics; + } + + public DataStatisticsTest() { + init(); + } + + public void init() { + @SuppressWarnings("resource") + ApplicationContext context = new ClassPathXmlApplicationContext( + "classpath*:/org/bench4q/agent/config/application-context.xml"); + AgentResultDataCollector agentResultDataCollector = new AgentResultDataCollector(); + agentResultDataCollector.setStorageHelper((StorageHelper) context + .getBean(StorageHelper.class)); + this.setDataStatistics(agentResultDataCollector); + } + + @Test + public void addZeroTest() { + this.getDataStatistics().add(makeBehaviorResultList(0)); + AgentBriefStatusModel model = (AgentBriefStatusModel) this + .getDataStatistics().getBriefStatistics(); + AgentBriefStatusModel modelExpect = makeAllZeroModel(); + modelExpect.setTimeFrame(model.getTimeFrame()); + assertTrue(model.equals(modelExpect)); + } + + @Test + public void addOneTest() { + this.getDataStatistics().add(makeBehaviorResultList(1)); + AgentBriefStatusModel model = (AgentBriefStatusModel) this + .getDataStatistics().getBriefStatistics(); + AgentBriefStatusModel modelExpect = new AgentBriefStatusModel(); + modelExpect.setTimeFrame(model.getTimeFrame()); + makeUpStatusModelForOneBehavior(modelExpect); + assertTrue(model.equals(modelExpect)); + } + + @Test + public void addTwoTest() { + this.getDataStatistics().add(makeBehaviorResultList(2)); + AgentBriefStatusModel model = (AgentBriefStatusModel) this + .getDataStatistics().getBriefStatistics(); + AgentBriefStatusModel modelExpect = new AgentBriefStatusModel(); + modelExpect.setTimeFrame(model.getTimeFrame()); + makeUpStatusModelForTwoBehavior(modelExpect); + } + + private void makeUpStatusModelForTwoBehavior(AgentBriefStatusModel model) { + model.setAverageResponseTime(205); + model.setSuccessThroughput(1 * 1000 / model.getTimeFrame()); + model.setFailCountFromBegin(1); + model.setFailRate(50); + model.setFailThroughput(1 * 1000 / model.getTimeFrame()); + model.setMaxResponseTime(210); + model.setMinResponseTime(200); + model.setResponseTimeDeviation(5); + model.setTotalCountFromBegin(2); + } + + private void makeUpStatusModelForOneBehavior(AgentBriefStatusModel model) { + model.setAverageResponseTime(200); + model.setSuccessThroughput(1 * 1000 / model.getTimeFrame()); + model.setFailCountFromBegin(0); + model.setFailRate(0); + model.setFailThroughput(0); + model.setMaxResponseTime(200); + model.setMinResponseTime(200); + model.setResponseTimeDeviation(0); + model.setTotalCountFromBegin(1); + } + + private AgentBriefStatusModel makeAllZeroModel() { + AgentBriefStatusModel model = new AgentBriefStatusModel(); + model.setAverageResponseTime(0); + model.setSuccessThroughput(0); + model.setFailCountFromBegin(0); + model.setFailRate(0); + model.setFailThroughput(0); + model.setMaxResponseTime(0); + model.setMinResponseTime(0); + model.setResponseTimeDeviation(0); + model.setTimeFrame(0); + model.setTotalCountFromBegin(0); + return model; + } + + private List makeBehaviorResultList(int count) { + List behaviorResults = new ArrayList(); + for (int i = 0; i < count; i++) { + behaviorResults.add(buildBehaviorResult(200 + 10 * i, i / 2 == 0)); + } + return behaviorResults; + } + + private BehaviorResult buildBehaviorResult(long responseTime, + boolean success) { + Date date = new Date(); + BehaviorResult result = new BehaviorResult(); + result.setBehaviorName(""); + result.setEndDate(new Date(date.getTime() + responseTime)); + result.setId(UUID.randomUUID()); + result.setPluginId("Get"); + result.setPluginName("get"); + result.setResponseTime(responseTime); + result.setStartDate(date); + result.setSuccess(success); + return result; + } +} From 9a4daa564b6d6c7cfb3f3922fdd76ca895201b2a Mon Sep 17 00:00:00 2001 From: Tienan Chen Date: Wed, 13 Nov 2013 16:56:31 +0800 Subject: [PATCH 063/196] totally use the new way to calculate brief information of test --- .gitignore | 1 + .../org/bench4q/agent/api/TestController.java | 61 ++----------------- .../impl/AbstractDataCollector.java | 9 ++- .../impl/AgentResultDataCollector.java | 12 ++-- .../helper/ApplicationContextHelper.java | 26 ++++++++ .../agent/scenario/ScenarioContext.java | 10 +-- .../agent/scenario/ScenarioEngine.java | 35 +++-------- .../agent/test/DataStatisticsTest.java | 3 +- .../agent/test/TestWithScriptFile.java | 2 +- 9 files changed, 62 insertions(+), 97 deletions(-) create mode 100644 src/main/java/org/bench4q/agent/helper/ApplicationContextHelper.java diff --git a/.gitignore b/.gitignore index 36a59301..33a60639 100644 --- a/.gitignore +++ b/.gitignore @@ -4,3 +4,4 @@ /target /logs /scripts +/DetailResults diff --git a/src/main/java/org/bench4q/agent/api/TestController.java b/src/main/java/org/bench4q/agent/api/TestController.java index a98443f7..a03164f3 100644 --- a/src/main/java/org/bench4q/agent/api/TestController.java +++ b/src/main/java/org/bench4q/agent/api/TestController.java @@ -11,12 +11,12 @@ import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import org.apache.log4j.Logger; +import org.bench4q.agent.api.model.AgentBriefStatusModel; import org.bench4q.agent.api.model.CleanTestResultModel; import org.bench4q.agent.api.model.ParameterModel; import org.bench4q.agent.api.model.RunScenarioModel; import org.bench4q.agent.api.model.RunScenarioResultModel; import org.bench4q.agent.api.model.StopTestModel; -import org.bench4q.agent.api.model.TestBriefStatusModel; import org.bench4q.agent.api.model.TestDetailModel; import org.bench4q.agent.api.model.TestDetailStatusModel; import org.bench4q.agent.api.model.UsePluginModel; @@ -211,67 +211,14 @@ public class TestController { @RequestMapping(value = "/brief/{runId}", method = RequestMethod.GET) @ResponseBody - public TestBriefStatusModel brief(@PathVariable UUID runId) { + public AgentBriefStatusModel brief(@PathVariable UUID runId) { ScenarioContext scenarioContext = this.getScenarioEngine() .getRunningTests().get(runId); if (scenarioContext == null) { return null; } - TestBriefStatusModel testBriefStatusModel = new TestBriefStatusModel(); - testBriefStatusModel.setStartDate(scenarioContext.getStartDate()); - int failCount = 0; - int successCount = 0; - long totalResponseTime = 0; - long maxResponseTime = 0, minResponseTime = Long.MAX_VALUE; - List behaviorResults = new ArrayList( - scenarioContext.getResults()); - long maxDate = 0, minDate = Long.MAX_VALUE; - int validCount = 0; - for (BehaviorResult behaviorResult : behaviorResults) { - if (behaviorResult.getEndDate().getTime() > maxDate) { - maxDate = behaviorResult.getEndDate().getTime(); - } - if (behaviorResult.getStartDate().getTime() < minDate) { - minDate = behaviorResult.getStartDate().getTime(); - } - if (behaviorResult.isSuccess()) { - successCount++; - } else { - failCount++; - } - if (behaviorResult.getPluginName().contains("Timer")) { - continue; - } - if (behaviorResult.isCalculated()) { - continue; - } - if (behaviorResult.getResponseTime() > maxResponseTime) { - maxResponseTime = behaviorResult.getResponseTime(); - } - if (behaviorResult.getResponseTime() < minResponseTime) { - minResponseTime = behaviorResult.getResponseTime(); - } - totalResponseTime += behaviorResult.getResponseTime(); - validCount++; - behaviorResult.setCalculated(true); - } - if (validCount == 0) { - return null; - } - testBriefStatusModel.setAverageResponseTime((totalResponseTime + 0.0) - / validCount); - testBriefStatusModel.setElapsedTime(maxDate - - testBriefStatusModel.getStartDate().getTime()); - testBriefStatusModel.setRunningTime(maxDate - - scenarioContext.getStartDate().getTime()); - testBriefStatusModel.setFailCount(failCount); - testBriefStatusModel.setSuccessCount(successCount); - testBriefStatusModel.setFinishedCount(behaviorResults.size()); - testBriefStatusModel.setScenarioBehaviorCount(scenarioContext - .getScenario().getUserBehaviors().length); - testBriefStatusModel.setRunningTime(maxDate - minDate); - testBriefStatusModel.setFinished(scenarioContext.isFinished()); - return testBriefStatusModel; + return (AgentBriefStatusModel) scenarioContext.getDataStatistics() + .getBriefStatistics(); } @RequestMapping(value = "/stop/{runId}", method = { RequestMethod.GET, diff --git a/src/main/java/org/bench4q/agent/datacollector/impl/AbstractDataCollector.java b/src/main/java/org/bench4q/agent/datacollector/impl/AbstractDataCollector.java index 7f25c431..913dbe1a 100644 --- a/src/main/java/org/bench4q/agent/datacollector/impl/AbstractDataCollector.java +++ b/src/main/java/org/bench4q/agent/datacollector/impl/AbstractDataCollector.java @@ -7,9 +7,9 @@ import java.util.List; import org.apache.log4j.Logger; import org.bench4q.agent.api.model.TestDetailModel; import org.bench4q.agent.datacollector.interfaces.DataStatistics; +import org.bench4q.agent.helper.ApplicationContextHelper; import org.bench4q.agent.scenario.BehaviorResult; import org.bench4q.agent.storage.StorageHelper; -import org.springframework.beans.factory.annotation.Autowired; public abstract class AbstractDataCollector implements DataStatistics { protected StorageHelper storageHelper; @@ -19,11 +19,16 @@ public abstract class AbstractDataCollector implements DataStatistics { return storageHelper; } - @Autowired public void setStorageHelper(StorageHelper storageHelper) { this.storageHelper = storageHelper; } + // Each sub class should call this in their constructor + protected void mustDoWhenIniti() { + this.setStorageHelper(ApplicationContextHelper.getContext().getBean( + StorageHelper.class)); + } + protected String getHostName() { InetAddress addr; try { diff --git a/src/main/java/org/bench4q/agent/datacollector/impl/AgentResultDataCollector.java b/src/main/java/org/bench4q/agent/datacollector/impl/AgentResultDataCollector.java index 0eab580b..a0a6a538 100644 --- a/src/main/java/org/bench4q/agent/datacollector/impl/AgentResultDataCollector.java +++ b/src/main/java/org/bench4q/agent/datacollector/impl/AgentResultDataCollector.java @@ -82,11 +82,13 @@ public class AgentResultDataCollector extends AbstractDataCollector { this.testID = testID; } - public AgentResultDataCollector() { - init(); + public AgentResultDataCollector(UUID testId) { + super.mustDoWhenIniti(); + this.setTestID(testId); + mustDoWhenIniti(); } - private void init() { + public void mustDoWhenIniti() { reset(); this.setCumulativeFailCount(0); this.setCumulativeSucessfulCount(0); @@ -149,8 +151,8 @@ public class AgentResultDataCollector extends AbstractDataCollector { result.setSuccessThroughput(0); result.setFailThroughput(0); } else { - result.setSuccessThroughput(this.successCountOfThisCall - * TIME_UNIT / result.getTimeFrame()); + result.setSuccessThroughput(this.successCountOfThisCall * TIME_UNIT + / result.getTimeFrame()); result.setFailThroughput(this.failCountOfThisCall * TIME_UNIT / result.getTimeFrame()); } diff --git a/src/main/java/org/bench4q/agent/helper/ApplicationContextHelper.java b/src/main/java/org/bench4q/agent/helper/ApplicationContextHelper.java new file mode 100644 index 00000000..fcfa9dfc --- /dev/null +++ b/src/main/java/org/bench4q/agent/helper/ApplicationContextHelper.java @@ -0,0 +1,26 @@ +package org.bench4q.agent.helper; + +import org.springframework.beans.BeansException; +import org.springframework.context.ApplicationContext; +import org.springframework.context.ApplicationContextAware; +import org.springframework.stereotype.Component; + +@Component +public class ApplicationContextHelper implements ApplicationContextAware { + + private static ApplicationContext context; + + public static ApplicationContext getContext() { + return context; + } + + private void setContext(ApplicationContext context) { + ApplicationContextHelper.context = context; + } + + public void setApplicationContext(ApplicationContext applicationContext) + throws BeansException { + this.setContext(applicationContext); + } + +} diff --git a/src/main/java/org/bench4q/agent/scenario/ScenarioContext.java b/src/main/java/org/bench4q/agent/scenario/ScenarioContext.java index 63760cbb..ca5edfec 100644 --- a/src/main/java/org/bench4q/agent/scenario/ScenarioContext.java +++ b/src/main/java/org/bench4q/agent/scenario/ScenarioContext.java @@ -2,6 +2,7 @@ package org.bench4q.agent.scenario; import java.util.Date; import java.util.List; +import java.util.UUID; import java.util.concurrent.ExecutorService; import org.bench4q.agent.datacollector.impl.AgentResultDataCollector; @@ -66,15 +67,16 @@ public class ScenarioContext { private ScenarioContext() { } - public static ScenarioContext buildScenarioContext(final Scenario scenario, - int poolSize, ExecutorService executorService, - final List ret) { + public static ScenarioContext buildScenarioContext(UUID testId, + final Scenario scenario, int poolSize, + ExecutorService executorService, final List ret) { ScenarioContext scenarioContext = new ScenarioContext(); scenarioContext.setScenario(scenario); scenarioContext.setStartDate(new Date(System.currentTimeMillis())); scenarioContext.setExecutorService(executorService); scenarioContext.setResults(ret); - scenarioContext.setDataStatistics(new AgentResultDataCollector()); + // TODO:remove this direct dependency + scenarioContext.setDataStatistics(new AgentResultDataCollector(testId)); return scenarioContext; } } diff --git a/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java b/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java index 9c71419a..42e02bf0 100644 --- a/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java +++ b/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java @@ -1,6 +1,5 @@ package org.bench4q.agent.scenario; -import java.io.File; import java.util.ArrayList; import java.util.Collections; import java.util.Date; @@ -25,6 +24,7 @@ public class ScenarioEngine { private StorageHelper storageHelper; private Logger logger; + @SuppressWarnings("unused") private Logger getLogger() { return logger; } @@ -71,14 +71,16 @@ public class ScenarioEngine { final List ret = Collections .synchronizedList(new ArrayList()); final ScenarioContext scenarioContext = ScenarioContext - .buildScenarioContext(scenario, poolSize, executorService, - ret); + .buildScenarioContext(runId, scenario, poolSize, + executorService, ret); int i; this.getRunningTests().put(runId, scenarioContext); Runnable runnable = new Runnable() { public void run() { while (!scenarioContext.getExecutorService().isShutdown()) { - ret.addAll(doRunScenario(scenario)); + // ret.addAll(doRunScenario(scenario)); + scenarioContext.getDataStatistics().add( + doRunScenario(scenario)); } } }; @@ -98,8 +100,8 @@ public class ScenarioEngine { for (UserBehavior userBehavior : scenario.getUserBehaviors()) { Object plugin = plugins.get(userBehavior.getUse()); String behaviorName = userBehavior.getName(); - this.getLogger().info( - "this step's behaviorName is : " + behaviorName); + // this.getLogger().info( + // "this step's behaviorName is : " + behaviorName); Map behaviorParameters = prepareBehaviorParameters(userBehavior); Date startDate = new Date(System.currentTimeMillis()); boolean success = (Boolean) this.getPluginManager().doBehavior( @@ -153,25 +155,4 @@ public class ScenarioEngine { } } - public String getHdfsPath() { - return "hdfs://133.133.12.21:9000/home/bench4q/results"; - } - - public String getLocalPath() { - String directory = this.getClass().getProtectionDomain() - .getCodeSource().getLocation().getFile().replace("\\", "/"); - File file = new File(directory); - if (!file.isDirectory()) { - directory = directory.substring(0, directory.lastIndexOf("/")); - } - if (!directory.endsWith("/")) { - directory += "/"; - } - directory += "results"; - File toCreate = new File(directory); - if (!toCreate.exists()) { - toCreate.mkdirs(); - } - return directory; - } } diff --git a/src/test/java/org/bench4q/agent/test/DataStatisticsTest.java b/src/test/java/org/bench4q/agent/test/DataStatisticsTest.java index 92a43579..be5c2fc2 100644 --- a/src/test/java/org/bench4q/agent/test/DataStatisticsTest.java +++ b/src/test/java/org/bench4q/agent/test/DataStatisticsTest.java @@ -35,7 +35,8 @@ public class DataStatisticsTest { @SuppressWarnings("resource") ApplicationContext context = new ClassPathXmlApplicationContext( "classpath*:/org/bench4q/agent/config/application-context.xml"); - AgentResultDataCollector agentResultDataCollector = new AgentResultDataCollector(); + AgentResultDataCollector agentResultDataCollector = new AgentResultDataCollector( + UUID.randomUUID()); agentResultDataCollector.setStorageHelper((StorageHelper) context .getBean(StorageHelper.class)); this.setDataStatistics(agentResultDataCollector); diff --git a/src/test/java/org/bench4q/agent/test/TestWithScriptFile.java b/src/test/java/org/bench4q/agent/test/TestWithScriptFile.java index 47a35a35..75ef3042 100644 --- a/src/test/java/org/bench4q/agent/test/TestWithScriptFile.java +++ b/src/test/java/org/bench4q/agent/test/TestWithScriptFile.java @@ -38,7 +38,7 @@ public class TestWithScriptFile { public TestWithScriptFile() { this.setFilePath("scripts" + System.getProperty("file.separator") - + "scriptwithError.xml"); + + "script.xml"); this.setHttpRequester(new HttpRequester()); } From e2c99604ce9aaf357f43f7e0a92b0f297057e1b9 Mon Sep 17 00:00:00 2001 From: Tienan Chen Date: Wed, 13 Nov 2013 19:05:38 +0800 Subject: [PATCH 064/196] do refactor, and let the property name really describes what it does --- .../bench4q/agent/api/model/AgentBriefStatusModel.java | 10 +++++----- .../datacollector/impl/AgentResultDataCollector.java | 2 +- .../org/bench4q/agent/test/DataStatisticsTest.java | 6 +++--- 3 files changed, 9 insertions(+), 9 deletions(-) diff --git a/src/main/java/org/bench4q/agent/api/model/AgentBriefStatusModel.java b/src/main/java/org/bench4q/agent/api/model/AgentBriefStatusModel.java index 7159fd0f..520c7e92 100644 --- a/src/main/java/org/bench4q/agent/api/model/AgentBriefStatusModel.java +++ b/src/main/java/org/bench4q/agent/api/model/AgentBriefStatusModel.java @@ -11,7 +11,7 @@ public class AgentBriefStatusModel { private long averageResponseTime; private long minResponseTime; private long maxResponseTime; - private long totalCountFromBegin; + private long successCountFromBegin; private long successThroughput; private long failCountFromBegin; private long failThroughput; @@ -64,12 +64,12 @@ public class AgentBriefStatusModel { } @XmlElement - public long getTotalCountFromBegin() { - return totalCountFromBegin; + public long getSuccessCountFromBegin() { + return successCountFromBegin; } - public void setTotalCountFromBegin(long totalCountFromBegin) { - this.totalCountFromBegin = totalCountFromBegin; + public void setSuccessCountFromBegin(long successCountFromBegin) { + this.successCountFromBegin = successCountFromBegin; } @XmlElement diff --git a/src/main/java/org/bench4q/agent/datacollector/impl/AgentResultDataCollector.java b/src/main/java/org/bench4q/agent/datacollector/impl/AgentResultDataCollector.java index a0a6a538..1bf34ec5 100644 --- a/src/main/java/org/bench4q/agent/datacollector/impl/AgentResultDataCollector.java +++ b/src/main/java/org/bench4q/agent/datacollector/impl/AgentResultDataCollector.java @@ -144,7 +144,7 @@ public class AgentResultDataCollector extends AbstractDataCollector { } this.cumulativeSucessfulCount += this.successCountOfThisCall; - result.setTotalCountFromBegin(this.cumulativeSucessfulCount); + result.setSuccessCountFromBegin(this.cumulativeSucessfulCount); this.cumulativeFailCount += this.failCountOfThisCall; result.setFailCountFromBegin(this.cumulativeFailCount); if (result.getTimeFrame() == 0) { diff --git a/src/test/java/org/bench4q/agent/test/DataStatisticsTest.java b/src/test/java/org/bench4q/agent/test/DataStatisticsTest.java index be5c2fc2..05017774 100644 --- a/src/test/java/org/bench4q/agent/test/DataStatisticsTest.java +++ b/src/test/java/org/bench4q/agent/test/DataStatisticsTest.java @@ -82,7 +82,7 @@ public class DataStatisticsTest { model.setMaxResponseTime(210); model.setMinResponseTime(200); model.setResponseTimeDeviation(5); - model.setTotalCountFromBegin(2); + model.setSuccessCountFromBegin(2); } private void makeUpStatusModelForOneBehavior(AgentBriefStatusModel model) { @@ -94,7 +94,7 @@ public class DataStatisticsTest { model.setMaxResponseTime(200); model.setMinResponseTime(200); model.setResponseTimeDeviation(0); - model.setTotalCountFromBegin(1); + model.setSuccessCountFromBegin(1); } private AgentBriefStatusModel makeAllZeroModel() { @@ -108,7 +108,7 @@ public class DataStatisticsTest { model.setMinResponseTime(0); model.setResponseTimeDeviation(0); model.setTimeFrame(0); - model.setTotalCountFromBegin(0); + model.setSuccessCountFromBegin(0); return model; } From 912f5bdf424fd8f3659103077e90e35e47e99405 Mon Sep 17 00:00:00 2001 From: Tienan Chen Date: Wed, 13 Nov 2013 19:43:03 +0800 Subject: [PATCH 065/196] add more data to AgentBriefStatusModel on demand --- .../api/model/AgentBriefStatusModel.java | 49 ++++++++++++++++++- .../impl/AgentResultDataCollector.java | 3 ++ .../agent/test/DataStatisticsTest.java | 9 ++++ 3 files changed, 59 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/bench4q/agent/api/model/AgentBriefStatusModel.java b/src/main/java/org/bench4q/agent/api/model/AgentBriefStatusModel.java index 520c7e92..499d1904 100644 --- a/src/main/java/org/bench4q/agent/api/model/AgentBriefStatusModel.java +++ b/src/main/java/org/bench4q/agent/api/model/AgentBriefStatusModel.java @@ -1,23 +1,33 @@ package org.bench4q.agent.api.model; +import java.io.ByteArrayInputStream; import java.lang.reflect.Field; +import javax.xml.bind.JAXBContext; +import javax.xml.bind.JAXBException; +import javax.xml.bind.Unmarshaller; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; +import org.springframework.beans.factory.annotation.Autowired; + @XmlRootElement public class AgentBriefStatusModel { private long timeFrame; - private long averageResponseTime; + private long averageResponseTime; // ¿É±»¼ÆËãµÄ private long minResponseTime; private long maxResponseTime; private long successCountFromBegin; private long successThroughput; private long failCountFromBegin; private long failThroughput; - private long failRate; + private long failRate; // ¿É±»¼ÆËãµÄ private long responseTimeDeviation; + private long successCountThisTime; + private long failCountThisTime; + private long totalResponseTimeThisTime; + @XmlElement public long getTimeFrame() { return timeFrame; @@ -108,6 +118,33 @@ public class AgentBriefStatusModel { this.responseTimeDeviation = responseTimeDeviation; } + @XmlElement + public long getSuccessCountThisTime() { + return successCountThisTime; + } + + public void setSuccessCountThisTime(long successCountThisTime) { + this.successCountThisTime = successCountThisTime; + } + + @XmlElement + public long getFailCountThisTime() { + return failCountThisTime; + } + + public void setFailCountThisTime(long failCountThisTime) { + this.failCountThisTime = failCountThisTime; + } + + @Autowired + public long getTotalResponseTimeThisTime() { + return totalResponseTimeThisTime; + } + + public void setTotalResponseTimeThisTime(long totalResponseTimeThisTime) { + this.totalResponseTimeThisTime = totalResponseTimeThisTime; + } + // if the all the fields of target object equals with this's except // timeFrame, // We call it equals. @@ -136,4 +173,12 @@ public class AgentBriefStatusModel { } return result; } + + public static AgentBriefStatusModel extractBriefStatusModel(String content) + throws JAXBException { + Unmarshaller unmarshaller = JAXBContext.newInstance( + AgentBriefStatusModel.class).createUnmarshaller(); + return (AgentBriefStatusModel) unmarshaller + .unmarshal(new ByteArrayInputStream(content.getBytes())); + } } diff --git a/src/main/java/org/bench4q/agent/datacollector/impl/AgentResultDataCollector.java b/src/main/java/org/bench4q/agent/datacollector/impl/AgentResultDataCollector.java index 1bf34ec5..395d418b 100644 --- a/src/main/java/org/bench4q/agent/datacollector/impl/AgentResultDataCollector.java +++ b/src/main/java/org/bench4q/agent/datacollector/impl/AgentResultDataCollector.java @@ -156,6 +156,9 @@ public class AgentResultDataCollector extends AbstractDataCollector { result.setFailThroughput(this.failCountOfThisCall * TIME_UNIT / result.getTimeFrame()); } + result.setTotalResponseTimeThisTime(this.totalResponseTimeOfThisCall); + result.setSuccessCountThisTime(this.successCountOfThisCall); + result.setFailCountThisTime(this.failCountOfThisCall); reset(); return result; } diff --git a/src/test/java/org/bench4q/agent/test/DataStatisticsTest.java b/src/test/java/org/bench4q/agent/test/DataStatisticsTest.java index 05017774..cb219713 100644 --- a/src/test/java/org/bench4q/agent/test/DataStatisticsTest.java +++ b/src/test/java/org/bench4q/agent/test/DataStatisticsTest.java @@ -83,6 +83,9 @@ public class DataStatisticsTest { model.setMinResponseTime(200); model.setResponseTimeDeviation(5); model.setSuccessCountFromBegin(2); + model.setSuccessCountThisTime(1); + model.setFailCountThisTime(1); + model.setTotalResponseTimeThisTime(410); } private void makeUpStatusModelForOneBehavior(AgentBriefStatusModel model) { @@ -95,6 +98,9 @@ public class DataStatisticsTest { model.setMinResponseTime(200); model.setResponseTimeDeviation(0); model.setSuccessCountFromBegin(1); + model.setSuccessCountThisTime(1); + model.setFailCountThisTime(0); + model.setTotalResponseTimeThisTime(200); } private AgentBriefStatusModel makeAllZeroModel() { @@ -109,6 +115,9 @@ public class DataStatisticsTest { model.setResponseTimeDeviation(0); model.setTimeFrame(0); model.setSuccessCountFromBegin(0); + model.setTotalResponseTimeThisTime(0); + model.setSuccessCountThisTime(0); + model.setFailCountThisTime(0); return model; } From 8ae6ebe6de0b552d0377288acc81508b9ae3470c Mon Sep 17 00:00:00 2001 From: Tienan Chen Date: Wed, 13 Nov 2013 20:36:48 +0800 Subject: [PATCH 066/196] remove a bug --- .../org/bench4q/agent/api/model/AgentBriefStatusModel.java | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/src/main/java/org/bench4q/agent/api/model/AgentBriefStatusModel.java b/src/main/java/org/bench4q/agent/api/model/AgentBriefStatusModel.java index 499d1904..5345006a 100644 --- a/src/main/java/org/bench4q/agent/api/model/AgentBriefStatusModel.java +++ b/src/main/java/org/bench4q/agent/api/model/AgentBriefStatusModel.java @@ -9,8 +9,6 @@ import javax.xml.bind.Unmarshaller; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; -import org.springframework.beans.factory.annotation.Autowired; - @XmlRootElement public class AgentBriefStatusModel { private long timeFrame; @@ -136,7 +134,7 @@ public class AgentBriefStatusModel { this.failCountThisTime = failCountThisTime; } - @Autowired + @XmlElement public long getTotalResponseTimeThisTime() { return totalResponseTimeThisTime; } From 9fb79bce83db846d9d87032c135f45406969df82 Mon Sep 17 00:00:00 2001 From: Tienan Chen Date: Thu, 14 Nov 2013 09:53:05 +0800 Subject: [PATCH 067/196] refine the brief model to fit the master's need --- .../api/model/AgentBriefStatusModel.java | 61 +++++++------------ .../impl/AgentResultDataCollector.java | 33 +++------- .../bench4q/agent/storage/LocalStorage.java | 5 +- .../agent/test/DataStatisticsTest.java | 24 +++----- 4 files changed, 40 insertions(+), 83 deletions(-) diff --git a/src/main/java/org/bench4q/agent/api/model/AgentBriefStatusModel.java b/src/main/java/org/bench4q/agent/api/model/AgentBriefStatusModel.java index 5345006a..35df6553 100644 --- a/src/main/java/org/bench4q/agent/api/model/AgentBriefStatusModel.java +++ b/src/main/java/org/bench4q/agent/api/model/AgentBriefStatusModel.java @@ -12,19 +12,17 @@ import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement public class AgentBriefStatusModel { private long timeFrame; - private long averageResponseTime; // ¿É±»¼ÆËãµÄ private long minResponseTime; private long maxResponseTime; private long successCountFromBegin; - private long successThroughput; + private long successThroughputThisTime; private long failCountFromBegin; - private long failThroughput; - private long failRate; // ¿É±»¼ÆËãµÄ - private long responseTimeDeviation; + private long failThroughputThisTime; private long successCountThisTime; private long failCountThisTime; private long totalResponseTimeThisTime; + private long totalSqureResponseTimeThisTime; @XmlElement public long getTimeFrame() { @@ -35,15 +33,6 @@ public class AgentBriefStatusModel { this.timeFrame = timeFrame; } - @XmlElement - public long getAverageResponseTime() { - return averageResponseTime; - } - - public void setAverageResponseTime(long averageResponseTime) { - this.averageResponseTime = averageResponseTime; - } - @XmlElement public long getMinResponseTime() { return minResponseTime; @@ -63,12 +52,12 @@ public class AgentBriefStatusModel { } @XmlElement - public long getSuccessThroughput() { - return successThroughput; + public long getSuccessThroughputThisTime() { + return successThroughputThisTime; } - public void setSuccessThroughput(long behaviorThroughput) { - this.successThroughput = behaviorThroughput; + public void setSuccessThroughputThisTime(long successThroughputThisTime) { + this.successThroughputThisTime = successThroughputThisTime; } @XmlElement @@ -90,30 +79,12 @@ public class AgentBriefStatusModel { } @XmlElement - public long getFailThroughput() { - return failThroughput; + public long getFailThroughputThisTime() { + return failThroughputThisTime; } - public void setFailThroughput(long failThroughput) { - this.failThroughput = failThroughput; - } - - @XmlElement - public long getFailRate() { - return failRate; - } - - public void setFailRate(long failRate) { - this.failRate = failRate; - } - - @XmlElement - public long getResponseTimeDeviation() { - return responseTimeDeviation; - } - - public void setResponseTimeDeviation(long responseTimeDeviation) { - this.responseTimeDeviation = responseTimeDeviation; + public void setFailThroughputThisTime(long failThroughputThisTime) { + this.failThroughputThisTime = failThroughputThisTime; } @XmlElement @@ -143,6 +114,16 @@ public class AgentBriefStatusModel { this.totalResponseTimeThisTime = totalResponseTimeThisTime; } + @XmlElement + public long getTotalSqureResponseTimeThisTime() { + return totalSqureResponseTimeThisTime; + } + + public void setTotalSqureResponseTimeThisTime( + long totalSqureResponseTimeThisTime) { + this.totalSqureResponseTimeThisTime = totalSqureResponseTimeThisTime; + } + // if the all the fields of target object equals with this's except // timeFrame, // We call it equals. diff --git a/src/main/java/org/bench4q/agent/datacollector/impl/AgentResultDataCollector.java b/src/main/java/org/bench4q/agent/datacollector/impl/AgentResultDataCollector.java index 395d418b..1dcbb0d2 100644 --- a/src/main/java/org/bench4q/agent/datacollector/impl/AgentResultDataCollector.java +++ b/src/main/java/org/bench4q/agent/datacollector/impl/AgentResultDataCollector.java @@ -25,10 +25,6 @@ public class AgentResultDataCollector extends AbstractDataCollector { this.timeOfPreviousCall = timeOfPreviousCall; } - private long getFailCountOfThisCall() { - return failCountOfThisCall; - } - private void setFailCountOfThisCall(long failCountOfThisCall) { this.failCountOfThisCall = failCountOfThisCall; } @@ -120,27 +116,11 @@ public class AgentResultDataCollector extends AbstractDataCollector { result.setTimeFrame(System.currentTimeMillis() - this.timeOfPreviousCall); if (this.getSuccessCountOfThisCall() == 0) { - result.setAverageResponseTime(0); result.setMaxResponseTime(0); result.setMinResponseTime(0); - result.setResponseTimeDeviation(0); - if (this.getFailCountOfThisCall() == 0) { - result.setFailRate(0); - } else { - result.setFailRate(100); - } } else { - result.setAverageResponseTime(this.totalResponseTimeOfThisCall - / this.successCountOfThisCall); - result.setFailRate(this.failCountOfThisCall - / (this.successCountOfThisCall + this.failCountOfThisCall)); result.setMinResponseTime(this.minResponseTimeOfThisCall); result.setMaxResponseTime(this.maxResponseTimeOfThisCall); - result.setResponseTimeDeviation(Math.round(Math - .sqrt(this.totalSqureResponseTimeOfThisCall - / this.successCountOfThisCall - - result.getAverageResponseTime() - * result.getAverageResponseTime()))); } this.cumulativeSucessfulCount += this.successCountOfThisCall; @@ -148,17 +128,18 @@ public class AgentResultDataCollector extends AbstractDataCollector { this.cumulativeFailCount += this.failCountOfThisCall; result.setFailCountFromBegin(this.cumulativeFailCount); if (result.getTimeFrame() == 0) { - result.setSuccessThroughput(0); - result.setFailThroughput(0); + result.setSuccessThroughputThisTime(0); + result.setFailThroughputThisTime(0); } else { - result.setSuccessThroughput(this.successCountOfThisCall * TIME_UNIT - / result.getTimeFrame()); - result.setFailThroughput(this.failCountOfThisCall * TIME_UNIT - / result.getTimeFrame()); + result.setSuccessThroughputThisTime(this.successCountOfThisCall + * TIME_UNIT / result.getTimeFrame()); + result.setFailThroughputThisTime(this.failCountOfThisCall + * TIME_UNIT / result.getTimeFrame()); } result.setTotalResponseTimeThisTime(this.totalResponseTimeOfThisCall); result.setSuccessCountThisTime(this.successCountOfThisCall); result.setFailCountThisTime(this.failCountOfThisCall); + result.setTotalSqureResponseTimeThisTime(this.totalSqureResponseTimeOfThisCall); reset(); return result; } diff --git a/src/main/java/org/bench4q/agent/storage/LocalStorage.java b/src/main/java/org/bench4q/agent/storage/LocalStorage.java index c96f1c94..9eecafb7 100644 --- a/src/main/java/org/bench4q/agent/storage/LocalStorage.java +++ b/src/main/java/org/bench4q/agent/storage/LocalStorage.java @@ -30,8 +30,9 @@ public class LocalStorage implements Storage { public boolean writeFile(String content, String path) { try { - File file = new File(path.substring(path.lastIndexOf(System - .getProperty("file.separator")))); + String dirPath = path.substring(0, + path.lastIndexOf(System.getProperty("file.separator"))); + File file = new File(dirPath); if (!file.exists()) { file.mkdirs(); } diff --git a/src/test/java/org/bench4q/agent/test/DataStatisticsTest.java b/src/test/java/org/bench4q/agent/test/DataStatisticsTest.java index cb219713..27f61f29 100644 --- a/src/test/java/org/bench4q/agent/test/DataStatisticsTest.java +++ b/src/test/java/org/bench4q/agent/test/DataStatisticsTest.java @@ -74,50 +74,44 @@ public class DataStatisticsTest { } private void makeUpStatusModelForTwoBehavior(AgentBriefStatusModel model) { - model.setAverageResponseTime(205); - model.setSuccessThroughput(1 * 1000 / model.getTimeFrame()); + model.setSuccessThroughputThisTime(1 * 1000 / model.getTimeFrame()); model.setFailCountFromBegin(1); - model.setFailRate(50); - model.setFailThroughput(1 * 1000 / model.getTimeFrame()); + model.setFailThroughputThisTime(1 * 1000 / model.getTimeFrame()); model.setMaxResponseTime(210); model.setMinResponseTime(200); - model.setResponseTimeDeviation(5); model.setSuccessCountFromBegin(2); model.setSuccessCountThisTime(1); model.setFailCountThisTime(1); model.setTotalResponseTimeThisTime(410); + model.setTotalSqureResponseTimeThisTime(84100); } private void makeUpStatusModelForOneBehavior(AgentBriefStatusModel model) { - model.setAverageResponseTime(200); - model.setSuccessThroughput(1 * 1000 / model.getTimeFrame()); + model.setSuccessThroughputThisTime(1 * 1000 / model.getTimeFrame()); model.setFailCountFromBegin(0); - model.setFailRate(0); - model.setFailThroughput(0); + model.setFailThroughputThisTime(0); model.setMaxResponseTime(200); model.setMinResponseTime(200); - model.setResponseTimeDeviation(0); model.setSuccessCountFromBegin(1); model.setSuccessCountThisTime(1); model.setFailCountThisTime(0); model.setTotalResponseTimeThisTime(200); + model.setTotalSqureResponseTimeThisTime(40000); } private AgentBriefStatusModel makeAllZeroModel() { AgentBriefStatusModel model = new AgentBriefStatusModel(); - model.setAverageResponseTime(0); - model.setSuccessThroughput(0); + model.setSuccessThroughputThisTime(0); model.setFailCountFromBegin(0); - model.setFailRate(0); - model.setFailThroughput(0); + model.setFailThroughputThisTime(0); model.setMaxResponseTime(0); model.setMinResponseTime(0); - model.setResponseTimeDeviation(0); model.setTimeFrame(0); model.setSuccessCountFromBegin(0); model.setTotalResponseTimeThisTime(0); model.setSuccessCountThisTime(0); model.setFailCountThisTime(0); + model.setTotalSqureResponseTimeThisTime(0); return model; } From 6f1f88a0b11738f1628355871e72fafdb98745e0 Mon Sep 17 00:00:00 2001 From: Tienan Chen Date: Thu, 14 Nov 2013 14:19:46 +0800 Subject: [PATCH 068/196] make the test really present my idea --- .../agent/test/DataStatisticsTest.java | 25 +++++++++++-------- 1 file changed, 14 insertions(+), 11 deletions(-) diff --git a/src/test/java/org/bench4q/agent/test/DataStatisticsTest.java b/src/test/java/org/bench4q/agent/test/DataStatisticsTest.java index 27f61f29..1a9682b7 100644 --- a/src/test/java/org/bench4q/agent/test/DataStatisticsTest.java +++ b/src/test/java/org/bench4q/agent/test/DataStatisticsTest.java @@ -68,22 +68,25 @@ public class DataStatisticsTest { this.getDataStatistics().add(makeBehaviorResultList(2)); AgentBriefStatusModel model = (AgentBriefStatusModel) this .getDataStatistics().getBriefStatistics(); - AgentBriefStatusModel modelExpect = new AgentBriefStatusModel(); - modelExpect.setTimeFrame(model.getTimeFrame()); - makeUpStatusModelForTwoBehavior(modelExpect); + AgentBriefStatusModel modelExpect = makeUpStatusModelForTwoBehavior(model + .getTimeFrame()); + assertTrue(model.equals(modelExpect)); } - private void makeUpStatusModelForTwoBehavior(AgentBriefStatusModel model) { - model.setSuccessThroughputThisTime(1 * 1000 / model.getTimeFrame()); + private AgentBriefStatusModel makeUpStatusModelForTwoBehavior(long timeFrame) { + AgentBriefStatusModel model = new AgentBriefStatusModel(); + model.setTimeFrame(timeFrame); + model.setSuccessThroughputThisTime(1 * 1000 / timeFrame); model.setFailCountFromBegin(1); - model.setFailThroughputThisTime(1 * 1000 / model.getTimeFrame()); - model.setMaxResponseTime(210); + model.setFailThroughputThisTime(1 * 1000 / timeFrame); + model.setMaxResponseTime(200); model.setMinResponseTime(200); - model.setSuccessCountFromBegin(2); + model.setSuccessCountFromBegin(1); model.setSuccessCountThisTime(1); model.setFailCountThisTime(1); - model.setTotalResponseTimeThisTime(410); - model.setTotalSqureResponseTimeThisTime(84100); + model.setTotalResponseTimeThisTime(200); + model.setTotalSqureResponseTimeThisTime(40000); + return model; } private void makeUpStatusModelForOneBehavior(AgentBriefStatusModel model) { @@ -118,7 +121,7 @@ public class DataStatisticsTest { private List makeBehaviorResultList(int count) { List behaviorResults = new ArrayList(); for (int i = 0; i < count; i++) { - behaviorResults.add(buildBehaviorResult(200 + 10 * i, i / 2 == 0)); + behaviorResults.add(buildBehaviorResult(200 + 10 * i, i % 2 == 0)); } return behaviorResults; } From 077b74537f4bd852e0f8bb0ebc046025182cd7e7 Mon Sep 17 00:00:00 2001 From: Tienan Chen Date: Thu, 14 Nov 2013 14:23:15 +0800 Subject: [PATCH 069/196] add author and some comment --- .../impl/AgentResultDataCollector.java | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/src/main/java/org/bench4q/agent/datacollector/impl/AgentResultDataCollector.java b/src/main/java/org/bench4q/agent/datacollector/impl/AgentResultDataCollector.java index 1dcbb0d2..2a1be5a5 100644 --- a/src/main/java/org/bench4q/agent/datacollector/impl/AgentResultDataCollector.java +++ b/src/main/java/org/bench4q/agent/datacollector/impl/AgentResultDataCollector.java @@ -8,6 +8,12 @@ import java.util.UUID; import org.bench4q.agent.api.model.AgentBriefStatusModel; import org.bench4q.agent.scenario.BehaviorResult; +/** + * This class collect the behavior result and statistic it. + * + * @author coderfengyun + * + */ public class AgentResultDataCollector extends AbstractDataCollector { private long timeOfPreviousCall; private long failCountOfThisCall; @@ -147,7 +153,12 @@ public class AgentResultDataCollector extends AbstractDataCollector { // /////////////////////////////// // DataStatistics Interface end // /////////////////////////////// - + /** + * For the failed one, only the fail count statistics will be added, Others + * of this failed one will be ignored + * + * @param behaviorResult + */ private void addItem(BehaviorResult behaviorResult) { if (behaviorResult.isSuccess()) { this.successCountOfThisCall++; From fc18794b57cbfb449f03f59c6bad330421014f36 Mon Sep 17 00:00:00 2001 From: Tienan Chen Date: Thu, 14 Nov 2013 14:39:35 +0800 Subject: [PATCH 070/196] refactor remove null --- .../java/org/bench4q/agent/api/model/AgentBriefStatusModel.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/org/bench4q/agent/api/model/AgentBriefStatusModel.java b/src/main/java/org/bench4q/agent/api/model/AgentBriefStatusModel.java index 35df6553..e6140f3e 100644 --- a/src/main/java/org/bench4q/agent/api/model/AgentBriefStatusModel.java +++ b/src/main/java/org/bench4q/agent/api/model/AgentBriefStatusModel.java @@ -129,7 +129,7 @@ public class AgentBriefStatusModel { // We call it equals. @Override public boolean equals(Object targetObj) { - if (!(targetObj instanceof AgentBriefStatusModel)) { + if (!(targetObj instanceof AgentBriefStatusModel) || targetObj == null) { return false; } boolean result = true; From e6ecfc86fdac31970e0a39e73bcfcceb5eb3b4f7 Mon Sep 17 00:00:00 2001 From: Tienan Chen Date: Thu, 14 Nov 2013 18:50:44 +0800 Subject: [PATCH 071/196] rename a method --- .../agent/datacollector/impl/AgentResultDataCollector.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/bench4q/agent/datacollector/impl/AgentResultDataCollector.java b/src/main/java/org/bench4q/agent/datacollector/impl/AgentResultDataCollector.java index 2a1be5a5..2d919473 100644 --- a/src/main/java/org/bench4q/agent/datacollector/impl/AgentResultDataCollector.java +++ b/src/main/java/org/bench4q/agent/datacollector/impl/AgentResultDataCollector.java @@ -87,10 +87,10 @@ public class AgentResultDataCollector extends AbstractDataCollector { public AgentResultDataCollector(UUID testId) { super.mustDoWhenIniti(); this.setTestID(testId); - mustDoWhenIniti(); + init(); } - public void mustDoWhenIniti() { + public void init() { reset(); this.setCumulativeFailCount(0); this.setCumulativeSucessfulCount(0); From 6ce886a8a48f1b79a908d6c5f9b28cd406c1e46b Mon Sep 17 00:00:00 2001 From: Tienan Chen Date: Thu, 14 Nov 2013 20:04:07 +0800 Subject: [PATCH 072/196] add timer support --- .../bench4q/agent/api/model/UserBehaviorModel.java | 12 ++++++++++++ .../org/bench4q/agent/test/TestWithScriptFile.java | 2 +- 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/src/main/java/org/bench4q/agent/api/model/UserBehaviorModel.java b/src/main/java/org/bench4q/agent/api/model/UserBehaviorModel.java index c1c3f74f..01beb390 100644 --- a/src/main/java/org/bench4q/agent/api/model/UserBehaviorModel.java +++ b/src/main/java/org/bench4q/agent/api/model/UserBehaviorModel.java @@ -1,7 +1,11 @@ package org.bench4q.agent.api.model; +import java.io.ByteArrayOutputStream; import java.util.List; +import javax.xml.bind.JAXBContext; +import javax.xml.bind.JAXBException; +import javax.xml.bind.Marshaller; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElementWrapper; import javax.xml.bind.annotation.XmlRootElement; @@ -39,4 +43,12 @@ public class UserBehaviorModel { public void setParameters(List parameters) { this.parameters = parameters; } + + public String getModelString() throws JAXBException { + ByteArrayOutputStream os = new ByteArrayOutputStream(); + Marshaller marshaller = JAXBContext.newInstance(this.getClass()) + .createMarshaller(); + marshaller.marshal(this, os); + return os.toString(); + } } diff --git a/src/test/java/org/bench4q/agent/test/TestWithScriptFile.java b/src/test/java/org/bench4q/agent/test/TestWithScriptFile.java index 75ef3042..86bb1606 100644 --- a/src/test/java/org/bench4q/agent/test/TestWithScriptFile.java +++ b/src/test/java/org/bench4q/agent/test/TestWithScriptFile.java @@ -38,7 +38,7 @@ public class TestWithScriptFile { public TestWithScriptFile() { this.setFilePath("scripts" + System.getProperty("file.separator") - + "script.xml"); + + "scriptTimer.xml"); this.setHttpRequester(new HttpRequester()); } From 965b0b5c1f7562ceae537f9f7ccb43140bd0c96f Mon Sep 17 00:00:00 2001 From: Tienan Chen Date: Mon, 18 Nov 2013 10:30:53 +0800 Subject: [PATCH 073/196] add some class and function to avoid count sleep time to response time --- .../org/bench4q/agent/api/TestController.java | 6 +-- .../org/bench4q/agent/scenario/Scenario.java | 12 +++--- .../agent/scenario/ScenarioEngine.java | 43 ++++++------------- .../Behavior.java} | 12 +++++- .../scenario/behavior/TimerBehavior.java | 16 +++++++ .../agent/scenario/behavior/UserBehavior.java | 28 ++++++++++++ .../agent/test/TestWithScriptFile.java | 2 +- 7 files changed, 78 insertions(+), 41 deletions(-) rename src/main/java/org/bench4q/agent/scenario/{UserBehavior.java => behavior/Behavior.java} (55%) create mode 100644 src/main/java/org/bench4q/agent/scenario/behavior/TimerBehavior.java create mode 100644 src/main/java/org/bench4q/agent/scenario/behavior/UserBehavior.java diff --git a/src/main/java/org/bench4q/agent/api/TestController.java b/src/main/java/org/bench4q/agent/api/TestController.java index a03164f3..2d1951ee 100644 --- a/src/main/java/org/bench4q/agent/api/TestController.java +++ b/src/main/java/org/bench4q/agent/api/TestController.java @@ -27,7 +27,7 @@ import org.bench4q.agent.scenario.Scenario; import org.bench4q.agent.scenario.ScenarioContext; import org.bench4q.agent.scenario.ScenarioEngine; import org.bench4q.agent.scenario.UsePlugin; -import org.bench4q.agent.scenario.UserBehavior; +import org.bench4q.agent.scenario.behavior.UserBehavior; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; @@ -89,7 +89,7 @@ public class TestController { Scenario scenario = new Scenario(); scenario.setUsePlugins(new UsePlugin[runScenarioModel.getUsePlugins() .size()]); - scenario.setUserBehaviors(new UserBehavior[runScenarioModel + scenario.setBehaviors(new UserBehavior[runScenarioModel .getUserBehaviors().size()]); extractUsePlugins(runScenarioModel, scenario); extractUserBehaviors(runScenarioModel, scenario); @@ -104,7 +104,7 @@ public class TestController { for (i = 0; i < runScenarioModel.getUserBehaviors().size(); i++) { UserBehaviorModel userBehaviorModel = userBehaviorModels.get(i); UserBehavior userBehavior = extractUserBehavior(userBehaviorModel); - scenario.getUserBehaviors()[i] = userBehavior; + scenario.getBehaviors()[i] = userBehavior; } } diff --git a/src/main/java/org/bench4q/agent/scenario/Scenario.java b/src/main/java/org/bench4q/agent/scenario/Scenario.java index 938ee17b..82e1c0a0 100644 --- a/src/main/java/org/bench4q/agent/scenario/Scenario.java +++ b/src/main/java/org/bench4q/agent/scenario/Scenario.java @@ -1,8 +1,10 @@ package org.bench4q.agent.scenario; +import org.bench4q.agent.scenario.behavior.Behavior; + public class Scenario { private UsePlugin[] usePlugins; - private UserBehavior[] userBehaviors; + private Behavior[] behaviors; public UsePlugin[] getUsePlugins() { return usePlugins; @@ -12,12 +14,12 @@ public class Scenario { this.usePlugins = usePlugins; } - public UserBehavior[] getUserBehaviors() { - return userBehaviors; + public Behavior[] getBehaviors() { + return behaviors; } - public void setUserBehaviors(UserBehavior[] userBehaviors) { - this.userBehaviors = userBehaviors; + public void setBehaviors(Behavior[] behaviors) { + this.behaviors = behaviors; } } diff --git a/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java b/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java index 42e02bf0..200ade9d 100644 --- a/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java +++ b/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java @@ -11,8 +11,8 @@ import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import org.apache.log4j.Logger; -import org.bench4q.agent.plugin.Plugin; import org.bench4q.agent.plugin.PluginManager; +import org.bench4q.agent.scenario.behavior.Behavior; import org.bench4q.agent.storage.StorageHelper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @@ -97,44 +97,27 @@ public class ScenarioEngine { preparePlugins(scenario, plugins); List ret = new ArrayList(); - for (UserBehavior userBehavior : scenario.getUserBehaviors()) { - Object plugin = plugins.get(userBehavior.getUse()); - String behaviorName = userBehavior.getName(); - // this.getLogger().info( - // "this step's behaviorName is : " + behaviorName); - Map behaviorParameters = prepareBehaviorParameters(userBehavior); + for (Behavior behavior : scenario.getBehaviors()) { + Object plugin = plugins.get(behavior.getUse()); + Map behaviorParameters = prepareBehaviorParameters(behavior); Date startDate = new Date(System.currentTimeMillis()); boolean success = (Boolean) this.getPluginManager().doBehavior( - plugin, behaviorName, behaviorParameters); + plugin, behavior.getName(), behaviorParameters); + Date endDate = new Date(System.currentTimeMillis()); - BehaviorResult result = buildBehaviorResult(userBehavior, plugin, - behaviorName, startDate, success, endDate); + BehaviorResult result = behavior.buildBehaviorResult(plugin, + startDate, success, endDate); + if (result == null) { + continue; + } ret.add(result); } return ret; } - private BehaviorResult buildBehaviorResult(UserBehavior userBehavior, - Object plugin, String behaviorName, Date startDate, - boolean success, Date endDate) { - BehaviorResult result = new BehaviorResult(); - result.setId(UUID.randomUUID()); - result.setStartDate(startDate); - result.setEndDate(endDate); - result.setSuccess(success); - result.setResponseTime(result.getEndDate().getTime() - - result.getStartDate().getTime()); - result.setBehaviorName(behaviorName); - result.setPluginId(userBehavior.getUse()); - result.setPluginName(plugin.getClass().getAnnotation(Plugin.class) - .value()); - return result; - } - - private Map prepareBehaviorParameters( - UserBehavior userBehavior) { + private Map prepareBehaviorParameters(Behavior behavior) { Map behaviorParameters = new HashMap(); - for (Parameter parameter : userBehavior.getParameters()) { + for (Parameter parameter : behavior.getParameters()) { behaviorParameters.put(parameter.getKey(), parameter.getValue()); } return behaviorParameters; diff --git a/src/main/java/org/bench4q/agent/scenario/UserBehavior.java b/src/main/java/org/bench4q/agent/scenario/behavior/Behavior.java similarity index 55% rename from src/main/java/org/bench4q/agent/scenario/UserBehavior.java rename to src/main/java/org/bench4q/agent/scenario/behavior/Behavior.java index 37f3577d..16c3bf93 100644 --- a/src/main/java/org/bench4q/agent/scenario/UserBehavior.java +++ b/src/main/java/org/bench4q/agent/scenario/behavior/Behavior.java @@ -1,6 +1,11 @@ -package org.bench4q.agent.scenario; +package org.bench4q.agent.scenario.behavior; -public class UserBehavior { +import java.util.Date; + +import org.bench4q.agent.scenario.BehaviorResult; +import org.bench4q.agent.scenario.Parameter; + +public abstract class Behavior { private String use; private String name; private Parameter[] parameters; @@ -28,4 +33,7 @@ public class UserBehavior { public void setParameters(Parameter[] parameters) { this.parameters = parameters; } + + public abstract BehaviorResult buildBehaviorResult(Object plugin, + Date startDate, boolean success, Date endDate); } diff --git a/src/main/java/org/bench4q/agent/scenario/behavior/TimerBehavior.java b/src/main/java/org/bench4q/agent/scenario/behavior/TimerBehavior.java new file mode 100644 index 00000000..f2f9f502 --- /dev/null +++ b/src/main/java/org/bench4q/agent/scenario/behavior/TimerBehavior.java @@ -0,0 +1,16 @@ +package org.bench4q.agent.scenario.behavior; + +import java.util.Date; + +import org.bench4q.agent.scenario.BehaviorResult; + +public class TimerBehavior extends Behavior { + + @Override + public BehaviorResult buildBehaviorResult(Object plugin, Date startDate, + boolean success, Date endDate) { + // TODO Auto-generated method stub + return null; + } + +} diff --git a/src/main/java/org/bench4q/agent/scenario/behavior/UserBehavior.java b/src/main/java/org/bench4q/agent/scenario/behavior/UserBehavior.java new file mode 100644 index 00000000..399f641f --- /dev/null +++ b/src/main/java/org/bench4q/agent/scenario/behavior/UserBehavior.java @@ -0,0 +1,28 @@ +package org.bench4q.agent.scenario.behavior; + +import java.util.Date; +import java.util.UUID; + +import org.bench4q.agent.plugin.Plugin; +import org.bench4q.agent.scenario.BehaviorResult; + +public class UserBehavior extends Behavior { + + @Override + public BehaviorResult buildBehaviorResult(Object plugin, Date startDate, + boolean success, Date endDate) { + BehaviorResult result = new BehaviorResult(); + result.setId(UUID.randomUUID()); + result.setStartDate(startDate); + result.setEndDate(endDate); + result.setSuccess(success); + result.setResponseTime(result.getEndDate().getTime() + - result.getStartDate().getTime()); + result.setBehaviorName(this.getName()); + result.setPluginId(this.getUse()); + result.setPluginName(plugin.getClass().getAnnotation(Plugin.class) + .value()); + return result; + } + +} diff --git a/src/test/java/org/bench4q/agent/test/TestWithScriptFile.java b/src/test/java/org/bench4q/agent/test/TestWithScriptFile.java index 86bb1606..75ef3042 100644 --- a/src/test/java/org/bench4q/agent/test/TestWithScriptFile.java +++ b/src/test/java/org/bench4q/agent/test/TestWithScriptFile.java @@ -38,7 +38,7 @@ public class TestWithScriptFile { public TestWithScriptFile() { this.setFilePath("scripts" + System.getProperty("file.separator") - + "scriptTimer.xml"); + + "script.xml"); this.setHttpRequester(new HttpRequester()); } From 9785faea8fb5addd24ae8ffd8667a38e397a570a Mon Sep 17 00:00:00 2001 From: Tienan Chen Date: Mon, 18 Nov 2013 11:39:20 +0800 Subject: [PATCH 074/196] judge whether its a timer behavior --- .../agent/api/model/BehaviorBaseModel.java | 5 ++ .../agent/api/model/TimerBehaviorModel.java | 54 +++++++++++++++++++ .../agent/scenario/ScenarioEngine.java | 4 ++ 3 files changed, 63 insertions(+) create mode 100644 src/main/java/org/bench4q/agent/api/model/BehaviorBaseModel.java create mode 100644 src/main/java/org/bench4q/agent/api/model/TimerBehaviorModel.java diff --git a/src/main/java/org/bench4q/agent/api/model/BehaviorBaseModel.java b/src/main/java/org/bench4q/agent/api/model/BehaviorBaseModel.java new file mode 100644 index 00000000..f77ded94 --- /dev/null +++ b/src/main/java/org/bench4q/agent/api/model/BehaviorBaseModel.java @@ -0,0 +1,5 @@ +package org.bench4q.agent.api.model; + +public class BehaviorBaseModel { + +} diff --git a/src/main/java/org/bench4q/agent/api/model/TimerBehaviorModel.java b/src/main/java/org/bench4q/agent/api/model/TimerBehaviorModel.java new file mode 100644 index 00000000..0d31b1ea --- /dev/null +++ b/src/main/java/org/bench4q/agent/api/model/TimerBehaviorModel.java @@ -0,0 +1,54 @@ +package org.bench4q.agent.api.model; + +import java.io.ByteArrayOutputStream; +import java.util.List; + +import javax.xml.bind.JAXBContext; +import javax.xml.bind.JAXBException; +import javax.xml.bind.Marshaller; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlElementWrapper; +import javax.xml.bind.annotation.XmlRootElement; + +@XmlRootElement(name = "timerBehavior") +public class TimerBehaviorModel { + private String use; + private String name; + private List 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 getParameters() { + return parameters; + } + + public void setParameters(List parameters) { + this.parameters = parameters; + } + + public String getModelString() throws JAXBException { + ByteArrayOutputStream os = new ByteArrayOutputStream(); + Marshaller marshaller = JAXBContext.newInstance(this.getClass()) + .createMarshaller(); + marshaller.marshal(this, os); + return os.toString(); + } +} diff --git a/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java b/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java index 200ade9d..8471cfc6 100644 --- a/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java +++ b/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java @@ -98,6 +98,10 @@ public class ScenarioEngine { List ret = new ArrayList(); for (Behavior behavior : scenario.getBehaviors()) { + // TODO: do this by behavior's type + if (behavior.getUse() == "timer") { + continue; + } Object plugin = plugins.get(behavior.getUse()); Map behaviorParameters = prepareBehaviorParameters(behavior); Date startDate = new Date(System.currentTimeMillis()); From a0829c4716f273e517cbe6a448c78f76b610428f Mon Sep 17 00:00:00 2001 From: Tienan Chen Date: Tue, 19 Nov 2013 20:55:16 +0800 Subject: [PATCH 075/196] remove the judgement in doRunScenario, and can do it by a inheritance architecture --- .../org/bench4q/agent/api/TestController.java | 39 +++++++------ .../agent/api/model/BehaviorBaseModel.java | 5 -- .../agent/api/model/RunScenarioModel.java | 23 +++++--- .../agent/api/model/TimerBehaviorModel.java | 54 ----------------- .../BehaviorBaseModel.java} | 21 ++----- .../model/behavior/TimerBehaviorModel.java | 32 ++++++++++ .../api/model/behavior/UserBehaviorModel.java | 28 +++++++++ .../impl/AbstractDataCollector.java | 13 ++--- .../agent/plugin/basic/HttpPlugin.java | 4 +- .../agent/scenario/ScenarioEngine.java | 17 ++---- .../agent/scenario/behavior/Behavior.java | 6 +- .../scenario/behavior/TimerBehavior.java | 7 +-- .../agent/scenario/behavior/UserBehavior.java | 7 ++- .../agent/test/TestWithScriptFile.java | 4 +- .../bench4q/agent/test/model/ModelTest.java | 58 +++++++++++++++++++ .../test/model/UserBehaviorModelTest.java | 38 ++++++++++++ 16 files changed, 225 insertions(+), 131 deletions(-) delete mode 100644 src/main/java/org/bench4q/agent/api/model/BehaviorBaseModel.java delete mode 100644 src/main/java/org/bench4q/agent/api/model/TimerBehaviorModel.java rename src/main/java/org/bench4q/agent/api/model/{UserBehaviorModel.java => behavior/BehaviorBaseModel.java} (52%) create mode 100644 src/main/java/org/bench4q/agent/api/model/behavior/TimerBehaviorModel.java create mode 100644 src/main/java/org/bench4q/agent/api/model/behavior/UserBehaviorModel.java create mode 100644 src/test/java/org/bench4q/agent/test/model/ModelTest.java create mode 100644 src/test/java/org/bench4q/agent/test/model/UserBehaviorModelTest.java diff --git a/src/main/java/org/bench4q/agent/api/TestController.java b/src/main/java/org/bench4q/agent/api/TestController.java index 2d1951ee..2d37dc4c 100644 --- a/src/main/java/org/bench4q/agent/api/TestController.java +++ b/src/main/java/org/bench4q/agent/api/TestController.java @@ -20,14 +20,14 @@ import org.bench4q.agent.api.model.StopTestModel; import org.bench4q.agent.api.model.TestDetailModel; import org.bench4q.agent.api.model.TestDetailStatusModel; import org.bench4q.agent.api.model.UsePluginModel; -import org.bench4q.agent.api.model.UserBehaviorModel; +import org.bench4q.agent.api.model.behavior.BehaviorBaseModel; import org.bench4q.agent.scenario.BehaviorResult; import org.bench4q.agent.scenario.Parameter; import org.bench4q.agent.scenario.Scenario; import org.bench4q.agent.scenario.ScenarioContext; import org.bench4q.agent.scenario.ScenarioEngine; import org.bench4q.agent.scenario.UsePlugin; -import org.bench4q.agent.scenario.behavior.UserBehavior; +import org.bench4q.agent.scenario.behavior.Behavior; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; @@ -89,8 +89,8 @@ public class TestController { Scenario scenario = new Scenario(); scenario.setUsePlugins(new UsePlugin[runScenarioModel.getUsePlugins() .size()]); - scenario.setBehaviors(new UserBehavior[runScenarioModel - .getUserBehaviors().size()]); + scenario.setBehaviors(new Behavior[runScenarioModel.getBehaviors() + .size()]); extractUsePlugins(runScenarioModel, scenario); extractUserBehaviors(runScenarioModel, scenario); return scenario; @@ -99,11 +99,12 @@ public class TestController { private void extractUserBehaviors(RunScenarioModel runScenarioModel, Scenario scenario) { int i; - List userBehaviorModels = runScenarioModel - .getUserBehaviors(); - for (i = 0; i < runScenarioModel.getUserBehaviors().size(); i++) { - UserBehaviorModel userBehaviorModel = userBehaviorModels.get(i); - UserBehavior userBehavior = extractUserBehavior(userBehaviorModel); + @SuppressWarnings("unchecked") + List behaviorBaseModels = runScenarioModel + .getBehaviors(); + for (i = 0; i < runScenarioModel.getBehaviors().size(); i++) { + BehaviorBaseModel behaviorModel = behaviorBaseModels.get(i); + Behavior userBehavior = extractBehavior(behaviorModel); scenario.getBehaviors()[i] = userBehavior; } } @@ -119,20 +120,20 @@ public class TestController { } } - private UserBehavior extractUserBehavior(UserBehaviorModel userBehaviorModel) { - UserBehavior userBehavior = new UserBehavior(); - userBehavior.setName(userBehaviorModel.getName()); - userBehavior.setUse(userBehaviorModel.getUse()); - userBehavior.setParameters(new Parameter[userBehaviorModel - .getParameters().size()]); + private Behavior extractBehavior(BehaviorBaseModel behaviorModel) { + Behavior behavior = behaviorModel.getBuisinessInstance(); + behavior.setName(behaviorModel.getName()); + behavior.setUse(behaviorModel.getUse()); + behavior.setParameters(new Parameter[behaviorModel.getParameters() + .size()]); int k = 0; - for (k = 0; k < userBehaviorModel.getParameters().size(); k++) { - ParameterModel parameterModel = userBehaviorModel.getParameters() + for (k = 0; k < behaviorModel.getParameters().size(); k++) { + ParameterModel parameterModel = behaviorModel.getParameters() .get(k); Parameter parameter = extractParameter(parameterModel); - userBehavior.getParameters()[k] = parameter; + behavior.getParameters()[k] = parameter; } - return userBehavior; + return behavior; } private UsePlugin extractUsePlugin(UsePluginModel usePluginModel) { diff --git a/src/main/java/org/bench4q/agent/api/model/BehaviorBaseModel.java b/src/main/java/org/bench4q/agent/api/model/BehaviorBaseModel.java deleted file mode 100644 index f77ded94..00000000 --- a/src/main/java/org/bench4q/agent/api/model/BehaviorBaseModel.java +++ /dev/null @@ -1,5 +0,0 @@ -package org.bench4q.agent.api.model; - -public class BehaviorBaseModel { - -} diff --git a/src/main/java/org/bench4q/agent/api/model/RunScenarioModel.java b/src/main/java/org/bench4q/agent/api/model/RunScenarioModel.java index ba6ecfa2..e933481a 100644 --- a/src/main/java/org/bench4q/agent/api/model/RunScenarioModel.java +++ b/src/main/java/org/bench4q/agent/api/model/RunScenarioModel.java @@ -4,13 +4,18 @@ import java.util.List; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElementWrapper; +import javax.xml.bind.annotation.XmlElements; import javax.xml.bind.annotation.XmlRootElement; +import org.bench4q.agent.api.model.behavior.TimerBehaviorModel; +import org.bench4q.agent.api.model.behavior.UserBehaviorModel; + @XmlRootElement(name = "runScenario") public class RunScenarioModel { private int poolSize; private List usePlugins; - private List userBehaviors; + @SuppressWarnings("rawtypes") + private List behaviors; @XmlElement public int getPoolSize() { @@ -31,13 +36,17 @@ public class RunScenarioModel { this.usePlugins = usePlugins; } - @XmlElementWrapper(name = "userBehaviors") - @XmlElement(name = "userBehavior") - public List getUserBehaviors() { - return userBehaviors; + @SuppressWarnings("rawtypes") + @XmlElementWrapper(name = "behaviors") + @XmlElements(value = { + @XmlElement(name = "userBehavior", type = UserBehaviorModel.class), + @XmlElement(name = "timerBehavior", type = TimerBehaviorModel.class) }) + public List getBehaviors() { + return behaviors; } - public void setUserBehaviors(List userBehaviors) { - this.userBehaviors = userBehaviors; + public void setBehaviors(@SuppressWarnings("rawtypes") List behaviors) { + this.behaviors = behaviors; } + } diff --git a/src/main/java/org/bench4q/agent/api/model/TimerBehaviorModel.java b/src/main/java/org/bench4q/agent/api/model/TimerBehaviorModel.java deleted file mode 100644 index 0d31b1ea..00000000 --- a/src/main/java/org/bench4q/agent/api/model/TimerBehaviorModel.java +++ /dev/null @@ -1,54 +0,0 @@ -package org.bench4q.agent.api.model; - -import java.io.ByteArrayOutputStream; -import java.util.List; - -import javax.xml.bind.JAXBContext; -import javax.xml.bind.JAXBException; -import javax.xml.bind.Marshaller; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlElementWrapper; -import javax.xml.bind.annotation.XmlRootElement; - -@XmlRootElement(name = "timerBehavior") -public class TimerBehaviorModel { - private String use; - private String name; - private List 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 getParameters() { - return parameters; - } - - public void setParameters(List parameters) { - this.parameters = parameters; - } - - public String getModelString() throws JAXBException { - ByteArrayOutputStream os = new ByteArrayOutputStream(); - Marshaller marshaller = JAXBContext.newInstance(this.getClass()) - .createMarshaller(); - marshaller.marshal(this, os); - return os.toString(); - } -} diff --git a/src/main/java/org/bench4q/agent/api/model/UserBehaviorModel.java b/src/main/java/org/bench4q/agent/api/model/behavior/BehaviorBaseModel.java similarity index 52% rename from src/main/java/org/bench4q/agent/api/model/UserBehaviorModel.java rename to src/main/java/org/bench4q/agent/api/model/behavior/BehaviorBaseModel.java index 01beb390..19bf9a46 100644 --- a/src/main/java/org/bench4q/agent/api/model/UserBehaviorModel.java +++ b/src/main/java/org/bench4q/agent/api/model/behavior/BehaviorBaseModel.java @@ -1,17 +1,14 @@ -package org.bench4q.agent.api.model; +package org.bench4q.agent.api.model.behavior; -import java.io.ByteArrayOutputStream; import java.util.List; -import javax.xml.bind.JAXBContext; -import javax.xml.bind.JAXBException; -import javax.xml.bind.Marshaller; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElementWrapper; -import javax.xml.bind.annotation.XmlRootElement; -@XmlRootElement(name = "userBehavior") -public class UserBehaviorModel { +import org.bench4q.agent.api.model.ParameterModel; +import org.bench4q.agent.scenario.behavior.Behavior; + +public abstract class BehaviorBaseModel { private String use; private String name; private List parameters; @@ -44,11 +41,5 @@ public class UserBehaviorModel { this.parameters = parameters; } - public String getModelString() throws JAXBException { - ByteArrayOutputStream os = new ByteArrayOutputStream(); - Marshaller marshaller = JAXBContext.newInstance(this.getClass()) - .createMarshaller(); - marshaller.marshal(this, os); - return os.toString(); - } + public abstract Behavior getBuisinessInstance(); } diff --git a/src/main/java/org/bench4q/agent/api/model/behavior/TimerBehaviorModel.java b/src/main/java/org/bench4q/agent/api/model/behavior/TimerBehaviorModel.java new file mode 100644 index 00000000..f3665f36 --- /dev/null +++ b/src/main/java/org/bench4q/agent/api/model/behavior/TimerBehaviorModel.java @@ -0,0 +1,32 @@ +package org.bench4q.agent.api.model.behavior; + +import java.io.ByteArrayOutputStream; + +import javax.xml.bind.JAXBContext; +import javax.xml.bind.Marshaller; +import javax.xml.bind.annotation.XmlRootElement; + +import org.bench4q.agent.scenario.behavior.Behavior; +import org.bench4q.agent.scenario.behavior.TimerBehavior; + +@XmlRootElement(name = "timerBehavior") +public class TimerBehaviorModel extends BehaviorBaseModel { + + public String getModelString() { + ByteArrayOutputStream os = new ByteArrayOutputStream(); + try { + Marshaller marshaller = JAXBContext.newInstance(this.getClass()) + .createMarshaller(); + marshaller.marshal(this, os); + } catch (Exception e) { + e.printStackTrace(); + } + return os.toString(); + } + + @Override + public Behavior getBuisinessInstance() { + return new TimerBehavior(); + } + +} diff --git a/src/main/java/org/bench4q/agent/api/model/behavior/UserBehaviorModel.java b/src/main/java/org/bench4q/agent/api/model/behavior/UserBehaviorModel.java new file mode 100644 index 00000000..66c8da11 --- /dev/null +++ b/src/main/java/org/bench4q/agent/api/model/behavior/UserBehaviorModel.java @@ -0,0 +1,28 @@ +package org.bench4q.agent.api.model.behavior; + +import java.io.ByteArrayOutputStream; + +import javax.xml.bind.JAXBContext; +import javax.xml.bind.JAXBException; +import javax.xml.bind.Marshaller; +import javax.xml.bind.annotation.XmlRootElement; + +import org.bench4q.agent.scenario.behavior.Behavior; +import org.bench4q.agent.scenario.behavior.UserBehavior; + +@XmlRootElement(name = "userBehavior") +public class UserBehaviorModel extends BehaviorBaseModel { + public String getModelString() throws JAXBException { + ByteArrayOutputStream os = new ByteArrayOutputStream(); + Marshaller marshaller = JAXBContext.newInstance(this.getClass()) + .createMarshaller(); + marshaller.marshal(this, os); + return os.toString(); + } + + @Override + public Behavior getBuisinessInstance() { + return new UserBehavior(); + } + +} diff --git a/src/main/java/org/bench4q/agent/datacollector/impl/AbstractDataCollector.java b/src/main/java/org/bench4q/agent/datacollector/impl/AbstractDataCollector.java index 913dbe1a..1611d6b3 100644 --- a/src/main/java/org/bench4q/agent/datacollector/impl/AbstractDataCollector.java +++ b/src/main/java/org/bench4q/agent/datacollector/impl/AbstractDataCollector.java @@ -5,7 +5,6 @@ import java.net.UnknownHostException; import java.util.List; import org.apache.log4j.Logger; -import org.bench4q.agent.api.model.TestDetailModel; import org.bench4q.agent.datacollector.interfaces.DataStatistics; import org.bench4q.agent.helper.ApplicationContextHelper; import org.bench4q.agent.scenario.BehaviorResult; @@ -42,12 +41,12 @@ public abstract class AbstractDataCollector implements DataStatistics { } public void add(List behaviorResults) { - for (BehaviorResult behaviorResult : behaviorResults) { - TestDetailModel testDetailModel = new TestDetailModel( - behaviorResult); - this.getStorageHelper().getLocalStorage() - .writeFile(testDetailModel.getModelString(), getSavePath()); - } + // for (BehaviorResult behaviorResult : behaviorResults) { + // TestDetailModel testDetailModel = new TestDetailModel( + // behaviorResult); + // this.getStorageHelper().getLocalStorage() + // .writeFile(testDetailModel.getModelString(), getSavePath()); + // } } protected abstract String getSavePath(); diff --git a/src/main/java/org/bench4q/agent/plugin/basic/HttpPlugin.java b/src/main/java/org/bench4q/agent/plugin/basic/HttpPlugin.java index bff89256..99a4dc95 100644 --- a/src/main/java/org/bench4q/agent/plugin/basic/HttpPlugin.java +++ b/src/main/java/org/bench4q/agent/plugin/basic/HttpPlugin.java @@ -6,12 +6,14 @@ import java.io.OutputStreamWriter; import java.net.HttpURLConnection; import java.net.URL; +import org.apache.log4j.Logger; import org.bench4q.agent.plugin.Behavior; import org.bench4q.agent.plugin.Parameter; import org.bench4q.agent.plugin.Plugin; @Plugin("Http") public class HttpPlugin { + private Logger logger = Logger.getLogger(HttpPlugin.class); public HttpPlugin() { @@ -37,7 +39,7 @@ public class HttpPlugin { bufferedReader.close(); return true; } catch (Exception e) { - e.printStackTrace(); + this.logger.error(e.toString() + " when url is " + url); return false; } } diff --git a/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java b/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java index 8471cfc6..5d1723bd 100644 --- a/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java +++ b/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java @@ -78,9 +78,9 @@ public class ScenarioEngine { Runnable runnable = new Runnable() { public void run() { while (!scenarioContext.getExecutorService().isShutdown()) { - // ret.addAll(doRunScenario(scenario)); scenarioContext.getDataStatistics().add( doRunScenario(scenario)); + System.out.println("End for once"); } } }; @@ -98,23 +98,16 @@ public class ScenarioEngine { List ret = new ArrayList(); for (Behavior behavior : scenario.getBehaviors()) { - // TODO: do this by behavior's type - if (behavior.getUse() == "timer") { - continue; - } + Object plugin = plugins.get(behavior.getUse()); Map behaviorParameters = prepareBehaviorParameters(behavior); Date startDate = new Date(System.currentTimeMillis()); boolean success = (Boolean) this.getPluginManager().doBehavior( plugin, behavior.getName(), behaviorParameters); - Date endDate = new Date(System.currentTimeMillis()); - BehaviorResult result = behavior.buildBehaviorResult(plugin, - startDate, success, endDate); - if (result == null) { - continue; - } - ret.add(result); + behavior.buildBehaviorResultAndAdd(plugin, startDate, success, + endDate, ret); + } return ret; } diff --git a/src/main/java/org/bench4q/agent/scenario/behavior/Behavior.java b/src/main/java/org/bench4q/agent/scenario/behavior/Behavior.java index 16c3bf93..1487d4c9 100644 --- a/src/main/java/org/bench4q/agent/scenario/behavior/Behavior.java +++ b/src/main/java/org/bench4q/agent/scenario/behavior/Behavior.java @@ -1,6 +1,7 @@ package org.bench4q.agent.scenario.behavior; import java.util.Date; +import java.util.List; import org.bench4q.agent.scenario.BehaviorResult; import org.bench4q.agent.scenario.Parameter; @@ -34,6 +35,7 @@ public abstract class Behavior { this.parameters = parameters; } - public abstract BehaviorResult buildBehaviorResult(Object plugin, - Date startDate, boolean success, Date endDate); + public abstract void buildBehaviorResultAndAdd(Object plugin, + Date startDate, boolean success, Date endDate, + List behaviorResults); } diff --git a/src/main/java/org/bench4q/agent/scenario/behavior/TimerBehavior.java b/src/main/java/org/bench4q/agent/scenario/behavior/TimerBehavior.java index f2f9f502..026cdb46 100644 --- a/src/main/java/org/bench4q/agent/scenario/behavior/TimerBehavior.java +++ b/src/main/java/org/bench4q/agent/scenario/behavior/TimerBehavior.java @@ -1,16 +1,15 @@ package org.bench4q.agent.scenario.behavior; import java.util.Date; +import java.util.List; import org.bench4q.agent.scenario.BehaviorResult; public class TimerBehavior extends Behavior { @Override - public BehaviorResult buildBehaviorResult(Object plugin, Date startDate, - boolean success, Date endDate) { - // TODO Auto-generated method stub - return null; + public void buildBehaviorResultAndAdd(Object plugin, Date startDate, + boolean success, Date endDate, List behaviorResults) { } } diff --git a/src/main/java/org/bench4q/agent/scenario/behavior/UserBehavior.java b/src/main/java/org/bench4q/agent/scenario/behavior/UserBehavior.java index 399f641f..61556752 100644 --- a/src/main/java/org/bench4q/agent/scenario/behavior/UserBehavior.java +++ b/src/main/java/org/bench4q/agent/scenario/behavior/UserBehavior.java @@ -1,6 +1,7 @@ package org.bench4q.agent.scenario.behavior; import java.util.Date; +import java.util.List; import java.util.UUID; import org.bench4q.agent.plugin.Plugin; @@ -9,8 +10,8 @@ import org.bench4q.agent.scenario.BehaviorResult; public class UserBehavior extends Behavior { @Override - public BehaviorResult buildBehaviorResult(Object plugin, Date startDate, - boolean success, Date endDate) { + public void buildBehaviorResultAndAdd(Object plugin, Date startDate, + boolean success, Date endDate, List behaviorResults) { BehaviorResult result = new BehaviorResult(); result.setId(UUID.randomUUID()); result.setStartDate(startDate); @@ -22,7 +23,7 @@ public class UserBehavior extends Behavior { result.setPluginId(this.getUse()); result.setPluginName(plugin.getClass().getAnnotation(Plugin.class) .value()); - return result; + behaviorResults.add(result); } } diff --git a/src/test/java/org/bench4q/agent/test/TestWithScriptFile.java b/src/test/java/org/bench4q/agent/test/TestWithScriptFile.java index 75ef3042..e181424b 100644 --- a/src/test/java/org/bench4q/agent/test/TestWithScriptFile.java +++ b/src/test/java/org/bench4q/agent/test/TestWithScriptFile.java @@ -18,7 +18,7 @@ public class TestWithScriptFile { private HttpRequester httpRequester; private String url = "http://localhost:6565/test/run"; private String filePath; - private static int load = 300; + private static int load = 100; public String getFilePath() { return filePath; @@ -38,7 +38,7 @@ public class TestWithScriptFile { public TestWithScriptFile() { this.setFilePath("scripts" + System.getProperty("file.separator") - + "script.xml"); + + "scriptTimer.xml"); this.setHttpRequester(new HttpRequester()); } diff --git a/src/test/java/org/bench4q/agent/test/model/ModelTest.java b/src/test/java/org/bench4q/agent/test/model/ModelTest.java new file mode 100644 index 00000000..be86a990 --- /dev/null +++ b/src/test/java/org/bench4q/agent/test/model/ModelTest.java @@ -0,0 +1,58 @@ +package org.bench4q.agent.test.model; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.IOException; + +import javax.xml.bind.JAXBContext; +import javax.xml.bind.JAXBException; +import javax.xml.bind.annotation.XmlRootElement; + +import org.bench4q.agent.api.model.behavior.BehaviorBaseModel; +import org.bench4q.agent.scenario.behavior.Behavior; +import org.junit.Test; + +import static org.junit.Assert.*; + +@XmlRootElement(name = "modelTest") +public class ModelTest extends BehaviorBaseModel { + public String getModelString() { + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + try { + JAXBContext.newInstance(this.getClass()).createMarshaller() + .marshal(this, outputStream); + } catch (JAXBException e) { + e.printStackTrace(); + + } + System.out.println(outputStream.toString()); + return outputStream.toString(); + } + + @Test + public void modelVerify() { + this.setName("test"); + this.setUse("xml"); + this.setParameters(null); + this.getModelString(); + } + + @Test + public void unmarshalVerify() throws IOException, JAXBException { + Object object = JAXBContext + .newInstance(this.getClass()) + .createUnmarshaller() + .unmarshal( + new File("Scripts" + + System.getProperty("file.separator") + + "behaviorModel.txt")); + + assertTrue(object instanceof ModelTest); + } + + @Override + public Behavior getBuisinessInstance() { + // TODO Auto-generated method stub + return null; + } +} diff --git a/src/test/java/org/bench4q/agent/test/model/UserBehaviorModelTest.java b/src/test/java/org/bench4q/agent/test/model/UserBehaviorModelTest.java new file mode 100644 index 00000000..601416f4 --- /dev/null +++ b/src/test/java/org/bench4q/agent/test/model/UserBehaviorModelTest.java @@ -0,0 +1,38 @@ +package org.bench4q.agent.test.model; + +import static org.junit.Assert.*; + +import java.io.File; + +import javax.xml.bind.JAXBContext; +import javax.xml.bind.JAXBException; +import javax.xml.bind.Unmarshaller; + +import org.bench4q.agent.api.model.behavior.BehaviorBaseModel; +import org.bench4q.agent.api.model.behavior.UserBehaviorModel; +import org.junit.Test; + +public class UserBehaviorModelTest { + + @Test + public void testMarshal() throws JAXBException { + UserBehaviorModel ub = new UserBehaviorModel(); + ub.setUse("xml"); + ub.setName("test"); + ub.setParameters(null); + System.out.println(ub.getModelString()); + } + + @Test + public void testUnmarshal() throws JAXBException { + Unmarshaller unmarshaller = JAXBContext.newInstance( + UserBehaviorModel.class).createUnmarshaller(); + Object object = unmarshaller.unmarshal(new File("Scripts" + + System.getProperty("file.separator") + + "UserBehaviorModel.txt")); + UserBehaviorModel userBehaviorModel = (UserBehaviorModel) object; + System.out.println(userBehaviorModel.getUse()); + assertTrue(object instanceof UserBehaviorModel); + assertTrue(object instanceof BehaviorBaseModel); + } +} From 68c7aaa311f105d87db98ad42e29ebb89be067de Mon Sep 17 00:00:00 2001 From: Tienan Chen Date: Tue, 19 Nov 2013 21:11:08 +0800 Subject: [PATCH 076/196] remove raw type list --- src/main/java/org/bench4q/agent/api/TestController.java | 9 ++++----- .../org/bench4q/agent/api/model/RunScenarioModel.java | 9 +++------ .../agent/api/model/behavior/BehaviorBaseModel.java | 3 +-- .../agent/api/model/behavior/TimerBehaviorModel.java | 3 +-- .../agent/api/model/behavior/UserBehaviorModel.java | 3 +-- 5 files changed, 10 insertions(+), 17 deletions(-) diff --git a/src/main/java/org/bench4q/agent/api/TestController.java b/src/main/java/org/bench4q/agent/api/TestController.java index 2d37dc4c..83997316 100644 --- a/src/main/java/org/bench4q/agent/api/TestController.java +++ b/src/main/java/org/bench4q/agent/api/TestController.java @@ -99,11 +99,10 @@ public class TestController { private void extractUserBehaviors(RunScenarioModel runScenarioModel, Scenario scenario) { int i; - @SuppressWarnings("unchecked") - List behaviorBaseModels = runScenarioModel - .getBehaviors(); + List behaviorBaseModels = runScenarioModel.getBehaviors(); for (i = 0; i < runScenarioModel.getBehaviors().size(); i++) { - BehaviorBaseModel behaviorModel = behaviorBaseModels.get(i); + BehaviorBaseModel behaviorModel = (BehaviorBaseModel) behaviorBaseModels + .get(i); Behavior userBehavior = extractBehavior(behaviorModel); scenario.getBehaviors()[i] = userBehavior; } @@ -121,7 +120,7 @@ public class TestController { } private Behavior extractBehavior(BehaviorBaseModel behaviorModel) { - Behavior behavior = behaviorModel.getBuisinessInstance(); + Behavior behavior = (Behavior) behaviorModel.getBuisinessInstance(); behavior.setName(behaviorModel.getName()); behavior.setUse(behaviorModel.getUse()); behavior.setParameters(new Parameter[behaviorModel.getParameters() diff --git a/src/main/java/org/bench4q/agent/api/model/RunScenarioModel.java b/src/main/java/org/bench4q/agent/api/model/RunScenarioModel.java index e933481a..5be0a0f7 100644 --- a/src/main/java/org/bench4q/agent/api/model/RunScenarioModel.java +++ b/src/main/java/org/bench4q/agent/api/model/RunScenarioModel.java @@ -14,8 +14,7 @@ import org.bench4q.agent.api.model.behavior.UserBehaviorModel; public class RunScenarioModel { private int poolSize; private List usePlugins; - @SuppressWarnings("rawtypes") - private List behaviors; + private List behaviors; @XmlElement public int getPoolSize() { @@ -36,17 +35,15 @@ public class RunScenarioModel { this.usePlugins = usePlugins; } - @SuppressWarnings("rawtypes") @XmlElementWrapper(name = "behaviors") @XmlElements(value = { @XmlElement(name = "userBehavior", type = UserBehaviorModel.class), @XmlElement(name = "timerBehavior", type = TimerBehaviorModel.class) }) - public List getBehaviors() { + public List getBehaviors() { return behaviors; } - public void setBehaviors(@SuppressWarnings("rawtypes") List behaviors) { + public void setBehaviors(List behaviors) { this.behaviors = behaviors; } - } diff --git a/src/main/java/org/bench4q/agent/api/model/behavior/BehaviorBaseModel.java b/src/main/java/org/bench4q/agent/api/model/behavior/BehaviorBaseModel.java index 19bf9a46..07950fd0 100644 --- a/src/main/java/org/bench4q/agent/api/model/behavior/BehaviorBaseModel.java +++ b/src/main/java/org/bench4q/agent/api/model/behavior/BehaviorBaseModel.java @@ -6,7 +6,6 @@ import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElementWrapper; import org.bench4q.agent.api.model.ParameterModel; -import org.bench4q.agent.scenario.behavior.Behavior; public abstract class BehaviorBaseModel { private String use; @@ -41,5 +40,5 @@ public abstract class BehaviorBaseModel { this.parameters = parameters; } - public abstract Behavior getBuisinessInstance(); + public abstract Object getBuisinessInstance(); } diff --git a/src/main/java/org/bench4q/agent/api/model/behavior/TimerBehaviorModel.java b/src/main/java/org/bench4q/agent/api/model/behavior/TimerBehaviorModel.java index f3665f36..851f2d7e 100644 --- a/src/main/java/org/bench4q/agent/api/model/behavior/TimerBehaviorModel.java +++ b/src/main/java/org/bench4q/agent/api/model/behavior/TimerBehaviorModel.java @@ -6,7 +6,6 @@ import javax.xml.bind.JAXBContext; import javax.xml.bind.Marshaller; import javax.xml.bind.annotation.XmlRootElement; -import org.bench4q.agent.scenario.behavior.Behavior; import org.bench4q.agent.scenario.behavior.TimerBehavior; @XmlRootElement(name = "timerBehavior") @@ -25,7 +24,7 @@ public class TimerBehaviorModel extends BehaviorBaseModel { } @Override - public Behavior getBuisinessInstance() { + public Object getBuisinessInstance() { return new TimerBehavior(); } diff --git a/src/main/java/org/bench4q/agent/api/model/behavior/UserBehaviorModel.java b/src/main/java/org/bench4q/agent/api/model/behavior/UserBehaviorModel.java index 66c8da11..08b9c9e6 100644 --- a/src/main/java/org/bench4q/agent/api/model/behavior/UserBehaviorModel.java +++ b/src/main/java/org/bench4q/agent/api/model/behavior/UserBehaviorModel.java @@ -7,7 +7,6 @@ import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import javax.xml.bind.annotation.XmlRootElement; -import org.bench4q.agent.scenario.behavior.Behavior; import org.bench4q.agent.scenario.behavior.UserBehavior; @XmlRootElement(name = "userBehavior") @@ -21,7 +20,7 @@ public class UserBehaviorModel extends BehaviorBaseModel { } @Override - public Behavior getBuisinessInstance() { + public Object getBuisinessInstance() { return new UserBehavior(); } From 8f5e5aa8b52934221cb089357e00e03596d2e60f Mon Sep 17 00:00:00 2001 From: Tienan Chen Date: Wed, 20 Nov 2013 08:58:17 +0800 Subject: [PATCH 077/196] remove those Unnecessary dependency, and do as a factory --- .../org/bench4q/agent/api/TestController.java | 3 ++- .../api/model/behavior/BehaviorBaseModel.java | 1 - .../api/model/behavior/TimerBehaviorModel.java | 7 ------- .../api/model/behavior/UserBehaviorModel.java | 7 ------- .../bench4q/agent/scenario/ScenarioContext.java | 3 +-- .../bench4q/agent/scenario/ScenarioEngine.java | 10 +++++----- .../agent/scenario/behavior/BehaviorFactory.java | 16 ++++++++++++++++ .../bench4q/agent/test/DataStatisticsTest.java | 6 ++++-- .../org/bench4q/agent/test/model/ModelTest.java | 6 ------ 9 files changed, 28 insertions(+), 31 deletions(-) create mode 100644 src/main/java/org/bench4q/agent/scenario/behavior/BehaviorFactory.java diff --git a/src/main/java/org/bench4q/agent/api/TestController.java b/src/main/java/org/bench4q/agent/api/TestController.java index 83997316..d735a8f0 100644 --- a/src/main/java/org/bench4q/agent/api/TestController.java +++ b/src/main/java/org/bench4q/agent/api/TestController.java @@ -28,6 +28,7 @@ import org.bench4q.agent.scenario.ScenarioContext; import org.bench4q.agent.scenario.ScenarioEngine; import org.bench4q.agent.scenario.UsePlugin; import org.bench4q.agent.scenario.behavior.Behavior; +import org.bench4q.agent.scenario.behavior.BehaviorFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; @@ -120,7 +121,7 @@ public class TestController { } private Behavior extractBehavior(BehaviorBaseModel behaviorModel) { - Behavior behavior = (Behavior) behaviorModel.getBuisinessInstance(); + Behavior behavior = BehaviorFactory.getBuisinessObject(behaviorModel); behavior.setName(behaviorModel.getName()); behavior.setUse(behaviorModel.getUse()); behavior.setParameters(new Parameter[behaviorModel.getParameters() diff --git a/src/main/java/org/bench4q/agent/api/model/behavior/BehaviorBaseModel.java b/src/main/java/org/bench4q/agent/api/model/behavior/BehaviorBaseModel.java index 07950fd0..8cce4fd0 100644 --- a/src/main/java/org/bench4q/agent/api/model/behavior/BehaviorBaseModel.java +++ b/src/main/java/org/bench4q/agent/api/model/behavior/BehaviorBaseModel.java @@ -40,5 +40,4 @@ public abstract class BehaviorBaseModel { this.parameters = parameters; } - public abstract Object getBuisinessInstance(); } diff --git a/src/main/java/org/bench4q/agent/api/model/behavior/TimerBehaviorModel.java b/src/main/java/org/bench4q/agent/api/model/behavior/TimerBehaviorModel.java index 851f2d7e..5204fdb7 100644 --- a/src/main/java/org/bench4q/agent/api/model/behavior/TimerBehaviorModel.java +++ b/src/main/java/org/bench4q/agent/api/model/behavior/TimerBehaviorModel.java @@ -6,8 +6,6 @@ import javax.xml.bind.JAXBContext; import javax.xml.bind.Marshaller; import javax.xml.bind.annotation.XmlRootElement; -import org.bench4q.agent.scenario.behavior.TimerBehavior; - @XmlRootElement(name = "timerBehavior") public class TimerBehaviorModel extends BehaviorBaseModel { @@ -23,9 +21,4 @@ public class TimerBehaviorModel extends BehaviorBaseModel { return os.toString(); } - @Override - public Object getBuisinessInstance() { - return new TimerBehavior(); - } - } diff --git a/src/main/java/org/bench4q/agent/api/model/behavior/UserBehaviorModel.java b/src/main/java/org/bench4q/agent/api/model/behavior/UserBehaviorModel.java index 08b9c9e6..0d94308d 100644 --- a/src/main/java/org/bench4q/agent/api/model/behavior/UserBehaviorModel.java +++ b/src/main/java/org/bench4q/agent/api/model/behavior/UserBehaviorModel.java @@ -7,8 +7,6 @@ import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import javax.xml.bind.annotation.XmlRootElement; -import org.bench4q.agent.scenario.behavior.UserBehavior; - @XmlRootElement(name = "userBehavior") public class UserBehaviorModel extends BehaviorBaseModel { public String getModelString() throws JAXBException { @@ -19,9 +17,4 @@ public class UserBehaviorModel extends BehaviorBaseModel { return os.toString(); } - @Override - public Object getBuisinessInstance() { - return new UserBehavior(); - } - } diff --git a/src/main/java/org/bench4q/agent/scenario/ScenarioContext.java b/src/main/java/org/bench4q/agent/scenario/ScenarioContext.java index ca5edfec..1cf8a2b2 100644 --- a/src/main/java/org/bench4q/agent/scenario/ScenarioContext.java +++ b/src/main/java/org/bench4q/agent/scenario/ScenarioContext.java @@ -69,12 +69,11 @@ public class ScenarioContext { public static ScenarioContext buildScenarioContext(UUID testId, final Scenario scenario, int poolSize, - ExecutorService executorService, final List ret) { + ExecutorService executorService) { ScenarioContext scenarioContext = new ScenarioContext(); scenarioContext.setScenario(scenario); scenarioContext.setStartDate(new Date(System.currentTimeMillis())); scenarioContext.setExecutorService(executorService); - scenarioContext.setResults(ret); // TODO:remove this direct dependency scenarioContext.setDataStatistics(new AgentResultDataCollector(testId)); return scenarioContext; diff --git a/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java b/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java index 5d1723bd..9155a7eb 100644 --- a/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java +++ b/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java @@ -1,7 +1,6 @@ package org.bench4q.agent.scenario; import java.util.ArrayList; -import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.List; @@ -68,11 +67,9 @@ public class ScenarioEngine { try { ExecutorService executorService = Executors .newFixedThreadPool(poolSize); - final List ret = Collections - .synchronizedList(new ArrayList()); final ScenarioContext scenarioContext = ScenarioContext .buildScenarioContext(runId, scenario, poolSize, - executorService, ret); + executorService); int i; this.getRunningTests().put(runId, scenarioContext); Runnable runnable = new Runnable() { @@ -105,9 +102,12 @@ public class ScenarioEngine { boolean success = (Boolean) this.getPluginManager().doBehavior( plugin, behavior.getName(), behaviorParameters); Date endDate = new Date(System.currentTimeMillis()); + // TODO: refactor, collect result here, and judge if to calculate + // that + // behavior's result,because it may be a userBehavior or + // timerBehavior behavior.buildBehaviorResultAndAdd(plugin, startDate, success, endDate, ret); - } return ret; } diff --git a/src/main/java/org/bench4q/agent/scenario/behavior/BehaviorFactory.java b/src/main/java/org/bench4q/agent/scenario/behavior/BehaviorFactory.java new file mode 100644 index 00000000..f8d37fd3 --- /dev/null +++ b/src/main/java/org/bench4q/agent/scenario/behavior/BehaviorFactory.java @@ -0,0 +1,16 @@ +package org.bench4q.agent.scenario.behavior; + +import org.bench4q.agent.api.model.behavior.BehaviorBaseModel; +import org.bench4q.agent.api.model.behavior.TimerBehaviorModel; +import org.bench4q.agent.api.model.behavior.UserBehaviorModel; + +public class BehaviorFactory { + public static Behavior getBuisinessObject(BehaviorBaseModel modelInput) { + if (modelInput instanceof TimerBehaviorModel) { + return new TimerBehavior(); + } else if (modelInput instanceof UserBehaviorModel) { + return new UserBehavior(); + } + return null; + } +} diff --git a/src/test/java/org/bench4q/agent/test/DataStatisticsTest.java b/src/test/java/org/bench4q/agent/test/DataStatisticsTest.java index 1a9682b7..38e3be1f 100644 --- a/src/test/java/org/bench4q/agent/test/DataStatisticsTest.java +++ b/src/test/java/org/bench4q/agent/test/DataStatisticsTest.java @@ -53,10 +53,11 @@ public class DataStatisticsTest { } @Test - public void addOneTest() { + public void addOneTest() throws InterruptedException { this.getDataStatistics().add(makeBehaviorResultList(1)); AgentBriefStatusModel model = (AgentBriefStatusModel) this .getDataStatistics().getBriefStatistics(); + Thread.sleep(100); AgentBriefStatusModel modelExpect = new AgentBriefStatusModel(); modelExpect.setTimeFrame(model.getTimeFrame()); makeUpStatusModelForOneBehavior(modelExpect); @@ -64,8 +65,9 @@ public class DataStatisticsTest { } @Test - public void addTwoTest() { + public void addTwoTest() throws InterruptedException { this.getDataStatistics().add(makeBehaviorResultList(2)); + Thread.sleep(100); AgentBriefStatusModel model = (AgentBriefStatusModel) this .getDataStatistics().getBriefStatistics(); AgentBriefStatusModel modelExpect = makeUpStatusModelForTwoBehavior(model diff --git a/src/test/java/org/bench4q/agent/test/model/ModelTest.java b/src/test/java/org/bench4q/agent/test/model/ModelTest.java index be86a990..5428ef66 100644 --- a/src/test/java/org/bench4q/agent/test/model/ModelTest.java +++ b/src/test/java/org/bench4q/agent/test/model/ModelTest.java @@ -9,7 +9,6 @@ import javax.xml.bind.JAXBException; import javax.xml.bind.annotation.XmlRootElement; import org.bench4q.agent.api.model.behavior.BehaviorBaseModel; -import org.bench4q.agent.scenario.behavior.Behavior; import org.junit.Test; import static org.junit.Assert.*; @@ -50,9 +49,4 @@ public class ModelTest extends BehaviorBaseModel { assertTrue(object instanceof ModelTest); } - @Override - public Behavior getBuisinessInstance() { - // TODO Auto-generated method stub - return null; - } } From 74d82f5661e18ab52d4098d9e45eec6360e719fa Mon Sep 17 00:00:00 2001 From: Tienan Chen Date: Wed, 20 Nov 2013 09:30:46 +0800 Subject: [PATCH 078/196] let the class be apart with the function that it should not to affect. It's just don't let the behavior add the result to list. This function should be the Engine's responsibility. --- .../impl/AgentResultDataCollector.java | 6 ++++- .../agent/plugin/ShouldCountResponseTime.java | 12 ++++++++++ .../agent/scenario/BehaviorResult.java | 17 ++++---------- .../agent/scenario/ScenarioEngine.java | 20 +++++++++++++--- .../agent/scenario/behavior/Behavior.java | 8 +------ .../scenario/behavior/TimerBehavior.java | 9 ++------ .../agent/scenario/behavior/UserBehavior.java | 23 ++----------------- .../agent/test/DataStatisticsTest.java | 3 ++- 8 files changed, 46 insertions(+), 52 deletions(-) create mode 100644 src/main/java/org/bench4q/agent/plugin/ShouldCountResponseTime.java diff --git a/src/main/java/org/bench4q/agent/datacollector/impl/AgentResultDataCollector.java b/src/main/java/org/bench4q/agent/datacollector/impl/AgentResultDataCollector.java index 2d919473..4553e9f0 100644 --- a/src/main/java/org/bench4q/agent/datacollector/impl/AgentResultDataCollector.java +++ b/src/main/java/org/bench4q/agent/datacollector/impl/AgentResultDataCollector.java @@ -155,11 +155,15 @@ public class AgentResultDataCollector extends AbstractDataCollector { // /////////////////////////////// /** * For the failed one, only the fail count statistics will be added, Others - * of this failed one will be ignored + * of this failed one will be ignored. And the shouldBeCountResponseTime is + * to identify if the result is from UserBehavior * * @param behaviorResult */ private void addItem(BehaviorResult behaviorResult) { + if (!behaviorResult.isShouldBeCountResponseTime()) { + return; + } if (behaviorResult.isSuccess()) { this.successCountOfThisCall++; this.totalResponseTimeOfThisCall += behaviorResult diff --git a/src/main/java/org/bench4q/agent/plugin/ShouldCountResponseTime.java b/src/main/java/org/bench4q/agent/plugin/ShouldCountResponseTime.java new file mode 100644 index 00000000..a62844f8 --- /dev/null +++ b/src/main/java/org/bench4q/agent/plugin/ShouldCountResponseTime.java @@ -0,0 +1,12 @@ +package org.bench4q.agent.plugin; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Target(ElementType.METHOD) +@Retention(RetentionPolicy.RUNTIME) +public @interface ShouldCountResponseTime { + String value(); +} diff --git a/src/main/java/org/bench4q/agent/scenario/BehaviorResult.java b/src/main/java/org/bench4q/agent/scenario/BehaviorResult.java index c9c0bc6f..e940f20b 100644 --- a/src/main/java/org/bench4q/agent/scenario/BehaviorResult.java +++ b/src/main/java/org/bench4q/agent/scenario/BehaviorResult.java @@ -12,7 +12,7 @@ public class BehaviorResult { private Date endDate; private long responseTime; private boolean success; - private boolean calculated; + private boolean shouldBeCountResponseTime; public UUID getId() { return id; @@ -78,19 +78,12 @@ public class BehaviorResult { this.success = success; } - public boolean isCalculated() { - return calculated; + public boolean isShouldBeCountResponseTime() { + return shouldBeCountResponseTime; } - public void setCalculated(boolean calculated) { - this.calculated = calculated; + public void setShouldBeCountResponseTime(boolean shouldBeCountResponseTime) { + this.shouldBeCountResponseTime = shouldBeCountResponseTime; } - public BehaviorResult() { - this.setCalculated(false); - } - - public long getExecuteDuration() { - return this.getEndDate().getTime() - this.getStartDate().getTime(); - } } diff --git a/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java b/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java index 9155a7eb..08a126c8 100644 --- a/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java +++ b/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java @@ -10,6 +10,7 @@ import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import org.apache.log4j.Logger; +import org.bench4q.agent.plugin.Plugin; import org.bench4q.agent.plugin.PluginManager; import org.bench4q.agent.scenario.behavior.Behavior; import org.bench4q.agent.storage.StorageHelper; @@ -95,19 +96,32 @@ public class ScenarioEngine { List ret = new ArrayList(); for (Behavior behavior : scenario.getBehaviors()) { - Object plugin = plugins.get(behavior.getUse()); Map behaviorParameters = prepareBehaviorParameters(behavior); Date startDate = new Date(System.currentTimeMillis()); boolean success = (Boolean) this.getPluginManager().doBehavior( plugin, behavior.getName(), behaviorParameters); Date endDate = new Date(System.currentTimeMillis()); + + BehaviorResult result = new BehaviorResult(); + result.setId(UUID.randomUUID()); + result.setStartDate(startDate); + result.setEndDate(endDate); + result.setSuccess(success); + result.setResponseTime(endDate.getTime() - startDate.getTime()); + result.setBehaviorName(behavior.getName()); + result.setPluginId(behavior.getUse()); + result.setPluginName(plugin.getClass().getAnnotation(Plugin.class) + .value()); + result.setShouldBeCountResponseTime(behavior + .shouldBeCountResponseTime()); + ret.add(result); // TODO: refactor, collect result here, and judge if to calculate // that // behavior's result,because it may be a userBehavior or // timerBehavior - behavior.buildBehaviorResultAndAdd(plugin, startDate, success, - endDate, ret); + // behavior.buildBehaviorResultAndAdd(plugin, startDate, success, + // endDate, ret); } return ret; } diff --git a/src/main/java/org/bench4q/agent/scenario/behavior/Behavior.java b/src/main/java/org/bench4q/agent/scenario/behavior/Behavior.java index 1487d4c9..8e9a2120 100644 --- a/src/main/java/org/bench4q/agent/scenario/behavior/Behavior.java +++ b/src/main/java/org/bench4q/agent/scenario/behavior/Behavior.java @@ -1,9 +1,5 @@ package org.bench4q.agent.scenario.behavior; -import java.util.Date; -import java.util.List; - -import org.bench4q.agent.scenario.BehaviorResult; import org.bench4q.agent.scenario.Parameter; public abstract class Behavior { @@ -35,7 +31,5 @@ public abstract class Behavior { this.parameters = parameters; } - public abstract void buildBehaviorResultAndAdd(Object plugin, - Date startDate, boolean success, Date endDate, - List behaviorResults); + public abstract boolean shouldBeCountResponseTime(); } diff --git a/src/main/java/org/bench4q/agent/scenario/behavior/TimerBehavior.java b/src/main/java/org/bench4q/agent/scenario/behavior/TimerBehavior.java index 026cdb46..645f904f 100644 --- a/src/main/java/org/bench4q/agent/scenario/behavior/TimerBehavior.java +++ b/src/main/java/org/bench4q/agent/scenario/behavior/TimerBehavior.java @@ -1,15 +1,10 @@ package org.bench4q.agent.scenario.behavior; -import java.util.Date; -import java.util.List; - -import org.bench4q.agent.scenario.BehaviorResult; - public class TimerBehavior extends Behavior { @Override - public void buildBehaviorResultAndAdd(Object plugin, Date startDate, - boolean success, Date endDate, List behaviorResults) { + public boolean shouldBeCountResponseTime() { + return false; } } diff --git a/src/main/java/org/bench4q/agent/scenario/behavior/UserBehavior.java b/src/main/java/org/bench4q/agent/scenario/behavior/UserBehavior.java index 61556752..63d43623 100644 --- a/src/main/java/org/bench4q/agent/scenario/behavior/UserBehavior.java +++ b/src/main/java/org/bench4q/agent/scenario/behavior/UserBehavior.java @@ -1,29 +1,10 @@ package org.bench4q.agent.scenario.behavior; -import java.util.Date; -import java.util.List; -import java.util.UUID; - -import org.bench4q.agent.plugin.Plugin; -import org.bench4q.agent.scenario.BehaviorResult; - public class UserBehavior extends Behavior { @Override - public void buildBehaviorResultAndAdd(Object plugin, Date startDate, - boolean success, Date endDate, List behaviorResults) { - BehaviorResult result = new BehaviorResult(); - result.setId(UUID.randomUUID()); - result.setStartDate(startDate); - result.setEndDate(endDate); - result.setSuccess(success); - result.setResponseTime(result.getEndDate().getTime() - - result.getStartDate().getTime()); - result.setBehaviorName(this.getName()); - result.setPluginId(this.getUse()); - result.setPluginName(plugin.getClass().getAnnotation(Plugin.class) - .value()); - behaviorResults.add(result); + public boolean shouldBeCountResponseTime() { + return true; } } diff --git a/src/test/java/org/bench4q/agent/test/DataStatisticsTest.java b/src/test/java/org/bench4q/agent/test/DataStatisticsTest.java index 38e3be1f..daf9a23c 100644 --- a/src/test/java/org/bench4q/agent/test/DataStatisticsTest.java +++ b/src/test/java/org/bench4q/agent/test/DataStatisticsTest.java @@ -55,9 +55,9 @@ public class DataStatisticsTest { @Test public void addOneTest() throws InterruptedException { this.getDataStatistics().add(makeBehaviorResultList(1)); + Thread.sleep(100); AgentBriefStatusModel model = (AgentBriefStatusModel) this .getDataStatistics().getBriefStatistics(); - Thread.sleep(100); AgentBriefStatusModel modelExpect = new AgentBriefStatusModel(); modelExpect.setTimeFrame(model.getTimeFrame()); makeUpStatusModelForOneBehavior(modelExpect); @@ -140,6 +140,7 @@ public class DataStatisticsTest { result.setResponseTime(responseTime); result.setStartDate(date); result.setSuccess(success); + result.setShouldBeCountResponseTime(true); return result; } } From b4fa507e8c9776eda2a95941e7692f501483720b Mon Sep 17 00:00:00 2001 From: Tienan Chen Date: Wed, 20 Nov 2013 10:24:52 +0800 Subject: [PATCH 079/196] refactor, add identifier to user behavior --- .../agent/api/model/behavior/UserBehaviorModel.java | 12 ++++++++++++ .../agent/scenario/behavior/UserBehavior.java | 2 -- 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/bench4q/agent/api/model/behavior/UserBehaviorModel.java b/src/main/java/org/bench4q/agent/api/model/behavior/UserBehaviorModel.java index 0d94308d..20ee1d1d 100644 --- a/src/main/java/org/bench4q/agent/api/model/behavior/UserBehaviorModel.java +++ b/src/main/java/org/bench4q/agent/api/model/behavior/UserBehaviorModel.java @@ -5,10 +5,22 @@ import java.io.ByteArrayOutputStream; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; +import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement(name = "userBehavior") public class UserBehaviorModel extends BehaviorBaseModel { + private int id; + + @XmlElement + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + public String getModelString() throws JAXBException { ByteArrayOutputStream os = new ByteArrayOutputStream(); Marshaller marshaller = JAXBContext.newInstance(this.getClass()) diff --git a/src/main/java/org/bench4q/agent/scenario/behavior/UserBehavior.java b/src/main/java/org/bench4q/agent/scenario/behavior/UserBehavior.java index 63d43623..4100bceb 100644 --- a/src/main/java/org/bench4q/agent/scenario/behavior/UserBehavior.java +++ b/src/main/java/org/bench4q/agent/scenario/behavior/UserBehavior.java @@ -1,10 +1,8 @@ package org.bench4q.agent.scenario.behavior; public class UserBehavior extends Behavior { - @Override public boolean shouldBeCountResponseTime() { return true; } - } From 6df80916c461a9cb7146484944e5e13b6b696083 Mon Sep 17 00:00:00 2001 From: Tienan Chen Date: Wed, 20 Nov 2013 14:20:47 +0800 Subject: [PATCH 080/196] add an inheritance hierarchy to let the plugin give back a plugin return, not boolean any more. It's importance especially for http plugin. --- .../impl/AgentResultDataCollector.java | 6 +- .../agent/plugin/ShouldCountResponseTime.java | 12 - .../plugin/basic/ConstantTimerPlugin.java | 7 +- .../agent/plugin/basic/HttpPlugin.java | 210 ++++++++++-------- .../agent/plugin/result/HttpReturn.java | 55 +++++ .../agent/plugin/result/PluginReturn.java | 13 ++ .../agent/plugin/result/TimerReturn.java | 12 + .../agent/scenario/BehaviorResult.java | 36 +++ .../agent/scenario/ScenarioEngine.java | 16 +- .../agent/test/TestWithScriptFile.java | 2 +- 10 files changed, 246 insertions(+), 123 deletions(-) delete mode 100644 src/main/java/org/bench4q/agent/plugin/ShouldCountResponseTime.java create mode 100644 src/main/java/org/bench4q/agent/plugin/result/HttpReturn.java create mode 100644 src/main/java/org/bench4q/agent/plugin/result/PluginReturn.java create mode 100644 src/main/java/org/bench4q/agent/plugin/result/TimerReturn.java diff --git a/src/main/java/org/bench4q/agent/datacollector/impl/AgentResultDataCollector.java b/src/main/java/org/bench4q/agent/datacollector/impl/AgentResultDataCollector.java index 4553e9f0..1ba67ed4 100644 --- a/src/main/java/org/bench4q/agent/datacollector/impl/AgentResultDataCollector.java +++ b/src/main/java/org/bench4q/agent/datacollector/impl/AgentResultDataCollector.java @@ -155,15 +155,11 @@ public class AgentResultDataCollector extends AbstractDataCollector { // /////////////////////////////// /** * For the failed one, only the fail count statistics will be added, Others - * of this failed one will be ignored. And the shouldBeCountResponseTime is - * to identify if the result is from UserBehavior + * of this failed one will be ignored. * * @param behaviorResult */ private void addItem(BehaviorResult behaviorResult) { - if (!behaviorResult.isShouldBeCountResponseTime()) { - return; - } if (behaviorResult.isSuccess()) { this.successCountOfThisCall++; this.totalResponseTimeOfThisCall += behaviorResult diff --git a/src/main/java/org/bench4q/agent/plugin/ShouldCountResponseTime.java b/src/main/java/org/bench4q/agent/plugin/ShouldCountResponseTime.java deleted file mode 100644 index a62844f8..00000000 --- a/src/main/java/org/bench4q/agent/plugin/ShouldCountResponseTime.java +++ /dev/null @@ -1,12 +0,0 @@ -package org.bench4q.agent.plugin; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -@Target(ElementType.METHOD) -@Retention(RetentionPolicy.RUNTIME) -public @interface ShouldCountResponseTime { - String value(); -} diff --git a/src/main/java/org/bench4q/agent/plugin/basic/ConstantTimerPlugin.java b/src/main/java/org/bench4q/agent/plugin/basic/ConstantTimerPlugin.java index 1e041d7a..091f4086 100644 --- a/src/main/java/org/bench4q/agent/plugin/basic/ConstantTimerPlugin.java +++ b/src/main/java/org/bench4q/agent/plugin/basic/ConstantTimerPlugin.java @@ -3,6 +3,7 @@ package org.bench4q.agent.plugin.basic; import org.bench4q.agent.plugin.Behavior; import org.bench4q.agent.plugin.Parameter; import org.bench4q.agent.plugin.Plugin; +import org.bench4q.agent.plugin.result.TimerReturn; @Plugin("ConstantTimer") public class ConstantTimerPlugin { @@ -11,13 +12,13 @@ public class ConstantTimerPlugin { } @Behavior("Sleep") - public boolean sleep(@Parameter("time") int time) { + public TimerReturn sleep(@Parameter("time") int time) { try { Thread.sleep(time); - return true; + return new TimerReturn(true); } catch (Exception e) { e.printStackTrace(); - return false; + return new TimerReturn(false); } } } diff --git a/src/main/java/org/bench4q/agent/plugin/basic/HttpPlugin.java b/src/main/java/org/bench4q/agent/plugin/basic/HttpPlugin.java index 99a4dc95..ca868e25 100644 --- a/src/main/java/org/bench4q/agent/plugin/basic/HttpPlugin.java +++ b/src/main/java/org/bench4q/agent/plugin/basic/HttpPlugin.java @@ -1,15 +1,18 @@ package org.bench4q.agent.plugin.basic; import java.io.BufferedReader; +import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.HttpURLConnection; +import java.net.MalformedURLException; import java.net.URL; import org.apache.log4j.Logger; import org.bench4q.agent.plugin.Behavior; import org.bench4q.agent.plugin.Parameter; import org.bench4q.agent.plugin.Plugin; +import org.bench4q.agent.plugin.result.HttpReturn; @Plugin("Http") public class HttpPlugin { @@ -20,42 +23,79 @@ public class HttpPlugin { } @Behavior("Get") - public boolean get(@Parameter("url") String url) { + public HttpReturn get(@Parameter("url") String url) { + HttpURLConnection httpURLConnection = null; + StringBuffer stringBuffer = null; + String requestMethod = "GET"; + try { - URL target = new URL(url); - HttpURLConnection httpURLConnection = (HttpURLConnection) target - .openConnection(); - httpURLConnection.setDoOutput(false); - httpURLConnection.setDoInput(true); - httpURLConnection.setUseCaches(false); - httpURLConnection.setRequestMethod("GET"); - BufferedReader bufferedReader = new BufferedReader( - new InputStreamReader(httpURLConnection.getInputStream())); - int temp = -1; - StringBuffer stringBuffer = new StringBuffer(); - while ((temp = bufferedReader.read()) != -1) { - stringBuffer.append((char) temp); - } - bufferedReader.close(); - return true; - } catch (Exception e) { - this.logger.error(e.toString() + " when url is " + url); - return false; + httpURLConnection = getRequestURLConnection(url, requestMethod); + stringBuffer = readConnectionInputStreamToBuffer(httpURLConnection); + + return new HttpReturn(true, requestMethod, + httpURLConnection.getResponseCode(), + stringBuffer.length() * 2, + httpURLConnection.getContentType()); + } catch (MalformedURLException e) { + logger.info(e.getStackTrace()); + return new HttpReturn(false, requestMethod, 400, -1, ""); + } catch (IOException e) { + logger.info(e.getStackTrace()); + return new HttpReturn(false, requestMethod, 404, -1, ""); } + + } + + private HttpURLConnection getRequestURLConnection(String url, String method) + throws MalformedURLException, IOException { + HttpURLConnection httpURLConnection; + URL target = new URL(url); + httpURLConnection = (HttpURLConnection) target.openConnection(); + if (method.equals("GET")) { + httpURLConnection.setDoOutput(false); + } else { + httpURLConnection.setDoOutput(true); + } + httpURLConnection.setDoOutput(true); + httpURLConnection.setDoInput(true); + httpURLConnection.setUseCaches(false); + httpURLConnection.setRequestMethod(method); + return httpURLConnection; + } + + private StringBuffer readConnectionInputStreamToBuffer( + HttpURLConnection httpURLConnection) throws IOException { + StringBuffer stringBuffer; + BufferedReader bufferedReader = new BufferedReader( + new InputStreamReader(httpURLConnection.getInputStream())); + int temp = -1; + stringBuffer = new StringBuffer(); + while ((temp = bufferedReader.read()) != -1) { + stringBuffer.append((char) temp); + } + bufferedReader.close(); + return stringBuffer; + } + + private void writeContentToConnectOutputSteam(String content, + HttpURLConnection httpURLConnection) throws IOException { + OutputStreamWriter outputStreamWriter = new OutputStreamWriter( + httpURLConnection.getOutputStream()); + outputStreamWriter.write(content); + outputStreamWriter.flush(); + outputStreamWriter.close(); } @Behavior("Post") - public boolean post(@Parameter("url") String url, + public HttpReturn post(@Parameter("url") String url, @Parameter("content") String content, @Parameter("contentType") String contentType, @Parameter("accept") String accept) { + HttpURLConnection httpURLConnection = null; + String requestMethod = "POST"; + StringBuffer stringBuffer = null; try { - URL target = new URL(url); - HttpURLConnection httpURLConnection = (HttpURLConnection) target - .openConnection(); - httpURLConnection.setDoOutput(true); - httpURLConnection.setDoInput(true); - httpURLConnection.setUseCaches(false); + httpURLConnection = getRequestURLConnection(url, requestMethod); httpURLConnection.setRequestMethod("POST"); if (contentType != null && contentType.length() > 0) { httpURLConnection.setRequestProperty("Content-Type", @@ -64,85 +104,69 @@ public class HttpPlugin { if (accept != null && accept.length() > 0) { httpURLConnection.setRequestProperty("Accept", accept); } - OutputStreamWriter outputStreamWriter = new OutputStreamWriter( - httpURLConnection.getOutputStream()); - outputStreamWriter.write(content); - outputStreamWriter.flush(); - outputStreamWriter.close(); - BufferedReader bufferedReader = new BufferedReader( - new InputStreamReader(httpURLConnection.getInputStream())); - int temp = -1; - StringBuffer stringBuffer = new StringBuffer(); - while ((temp = bufferedReader.read()) != -1) { - stringBuffer.append((char) temp); - } - bufferedReader.close(); - return true; - } catch (Exception e) { - e.printStackTrace(); - return false; + writeContentToConnectOutputSteam(content, httpURLConnection); + stringBuffer = readConnectionInputStreamToBuffer(httpURLConnection); + return new HttpReturn(true, requestMethod, + httpURLConnection.getResponseCode(), + stringBuffer.length() * 2, + httpURLConnection.getContentType()); + } catch (MalformedURLException e) { + logger.info(e.getStackTrace()); + return new HttpReturn(false, requestMethod, 400, -1, ""); + } catch (IOException e) { + logger.info(e.getStackTrace()); + return new HttpReturn(false, requestMethod, 404, -1, ""); } + } @Behavior("Put") - public boolean put(@Parameter("url") String url, + public HttpReturn put(@Parameter("url") String url, @Parameter("content") String content) { + StringBuffer stringBuffer = null; + String requestMethod = "PUT"; try { - URL target = new URL(url); - HttpURLConnection httpURLConnection = (HttpURLConnection) target - .openConnection(); - httpURLConnection.setDoOutput(true); - httpURLConnection.setDoInput(true); - httpURLConnection.setUseCaches(false); - httpURLConnection.setRequestMethod("PUT"); - OutputStreamWriter outputStreamWriter = new OutputStreamWriter( - httpURLConnection.getOutputStream()); - outputStreamWriter.write(content); - outputStreamWriter.flush(); - outputStreamWriter.close(); - BufferedReader bufferedReader = new BufferedReader( - new InputStreamReader(httpURLConnection.getInputStream())); - int temp = -1; - StringBuffer stringBuffer = new StringBuffer(); - while ((temp = bufferedReader.read()) != -1) { - stringBuffer.append((char) temp); - } - bufferedReader.close(); - return true; - } catch (Exception e) { - e.printStackTrace(); - return false; + HttpURLConnection httpURLConnection = this.getRequestURLConnection( + url, requestMethod); + writeContentToConnectOutputSteam(content, httpURLConnection); + stringBuffer = readConnectionInputStreamToBuffer(httpURLConnection); + return new HttpReturn(true, requestMethod, + httpURLConnection.getResponseCode(), + stringBuffer.length() * 2, + httpURLConnection.getContentType()); + } catch (MalformedURLException e) { + logger.info(e.getStackTrace()); + return new HttpReturn(false, requestMethod, 400, -1, ""); + } catch (IOException e) { + logger.info(e.getStackTrace()); + return new HttpReturn(false, requestMethod, 404, -1, ""); } } @Behavior("Delete") - public boolean delete(@Parameter("url") String url, + public HttpReturn delete(@Parameter("url") String url, @Parameter("content") String content) { + StringBuffer stringBuffer = null; + String requestMethod = "DELETE"; + int responseCode = -1; + long responseContentLength = 0; + String responseContentType = ""; try { - URL target = new URL(url); - HttpURLConnection httpURLConnection = (HttpURLConnection) target - .openConnection(); - httpURLConnection.setDoOutput(true); - httpURLConnection.setDoInput(true); - httpURLConnection.setUseCaches(false); - httpURLConnection.setRequestMethod("DELETE"); - OutputStreamWriter outputStreamWriter = new OutputStreamWriter( - httpURLConnection.getOutputStream()); - outputStreamWriter.write(content); - outputStreamWriter.flush(); - outputStreamWriter.close(); - BufferedReader bufferedReader = new BufferedReader( - new InputStreamReader(httpURLConnection.getInputStream())); - int temp = -1; - StringBuffer stringBuffer = new StringBuffer(); - while ((temp = bufferedReader.read()) != -1) { - stringBuffer.append((char) temp); - } - bufferedReader.close(); - return true; + HttpURLConnection httpURLConnection = getRequestURLConnection(url, + requestMethod); + writeContentToConnectOutputSteam(content, httpURLConnection); + stringBuffer = readConnectionInputStreamToBuffer(httpURLConnection); + responseCode = httpURLConnection.getResponseCode(); + responseContentLength = stringBuffer.length() * 2; + responseContentType = httpURLConnection.getContentType(); + return new HttpReturn(true, requestMethod, + httpURLConnection.getResponseCode(), + stringBuffer.length() * 2, + httpURLConnection.getContentType()); } catch (Exception e) { - e.printStackTrace(); - return false; + logger.info(e); + return new HttpReturn(false, requestMethod, responseCode, + responseContentLength, responseContentType); } } } diff --git a/src/main/java/org/bench4q/agent/plugin/result/HttpReturn.java b/src/main/java/org/bench4q/agent/plugin/result/HttpReturn.java new file mode 100644 index 00000000..04e055a7 --- /dev/null +++ b/src/main/java/org/bench4q/agent/plugin/result/HttpReturn.java @@ -0,0 +1,55 @@ +package org.bench4q.agent.plugin.result; + +/*** + * the contentLength's unit is Byte + * + * @author coderfengyun + * + */ +public class HttpReturn extends PluginReturn { + private String method; + private int statusCode; + private long contentLength; + private String contentType; + + public String getMethod() { + return method; + } + + private void setMethod(String method) { + this.method = method; + } + + public int getStatusCode() { + return statusCode; + } + + private void setStatusCode(int statusCode) { + this.statusCode = statusCode; + } + + public long getContentLength() { + return contentLength; + } + + private void setContentLength(long contentLength) { + this.contentLength = contentLength; + } + + public String getContentType() { + return contentType; + } + + private void setContentType(String contentType) { + this.contentType = contentType; + } + + public HttpReturn(boolean success, String method, int statusCode, + long contentLength, String contentType) { + this.setSuccess(success); + this.setMethod(method); + this.setStatusCode(statusCode); + this.setContentLength(contentLength); + this.setContentType(contentType); + } +} diff --git a/src/main/java/org/bench4q/agent/plugin/result/PluginReturn.java b/src/main/java/org/bench4q/agent/plugin/result/PluginReturn.java new file mode 100644 index 00000000..a0b84163 --- /dev/null +++ b/src/main/java/org/bench4q/agent/plugin/result/PluginReturn.java @@ -0,0 +1,13 @@ +package org.bench4q.agent.plugin.result; + +public abstract class PluginReturn { + private boolean success; + + public boolean isSuccess() { + return success; + } + + public void setSuccess(boolean success) { + this.success = success; + } +} diff --git a/src/main/java/org/bench4q/agent/plugin/result/TimerReturn.java b/src/main/java/org/bench4q/agent/plugin/result/TimerReturn.java new file mode 100644 index 00000000..97b7b183 --- /dev/null +++ b/src/main/java/org/bench4q/agent/plugin/result/TimerReturn.java @@ -0,0 +1,12 @@ +package org.bench4q.agent.plugin.result; + +/** + * + * @author coderfengyun + * + */ +public class TimerReturn extends PluginReturn { + public TimerReturn(boolean success) { + this.setSuccess(success); + } +} diff --git a/src/main/java/org/bench4q/agent/scenario/BehaviorResult.java b/src/main/java/org/bench4q/agent/scenario/BehaviorResult.java index e940f20b..9f9ebb5a 100644 --- a/src/main/java/org/bench4q/agent/scenario/BehaviorResult.java +++ b/src/main/java/org/bench4q/agent/scenario/BehaviorResult.java @@ -12,6 +12,10 @@ public class BehaviorResult { private Date endDate; private long responseTime; private boolean success; + private long contentLength; + private int statusCode; + private String method; + private String contentType; private boolean shouldBeCountResponseTime; public UUID getId() { @@ -78,6 +82,38 @@ public class BehaviorResult { this.success = success; } + public long getContentLength() { + return contentLength; + } + + public void setContentLength(long contentLength) { + this.contentLength = contentLength; + } + + public int getStatusCode() { + return statusCode; + } + + public void setStatusCode(int statusCode) { + this.statusCode = statusCode; + } + + public String getMethod() { + return method; + } + + public void setMethod(String method) { + this.method = method; + } + + public String getContentType() { + return contentType; + } + + public void setContentType(String contentType) { + this.contentType = contentType; + } + public boolean isShouldBeCountResponseTime() { return shouldBeCountResponseTime; } diff --git a/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java b/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java index 08a126c8..c3e4b359 100644 --- a/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java +++ b/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java @@ -12,6 +12,7 @@ import java.util.concurrent.Executors; import org.apache.log4j.Logger; import org.bench4q.agent.plugin.Plugin; import org.bench4q.agent.plugin.PluginManager; +import org.bench4q.agent.plugin.result.PluginReturn; import org.bench4q.agent.scenario.behavior.Behavior; import org.bench4q.agent.storage.StorageHelper; import org.springframework.beans.factory.annotation.Autowired; @@ -99,15 +100,18 @@ public class ScenarioEngine { Object plugin = plugins.get(behavior.getUse()); Map behaviorParameters = prepareBehaviorParameters(behavior); Date startDate = new Date(System.currentTimeMillis()); - boolean success = (Boolean) this.getPluginManager().doBehavior( - plugin, behavior.getName(), behaviorParameters); + PluginReturn pluginReturn = (PluginReturn) this.getPluginManager() + .doBehavior(plugin, behavior.getName(), behaviorParameters); Date endDate = new Date(System.currentTimeMillis()); + if (!behavior.shouldBeCountResponseTime()) { + continue; + } BehaviorResult result = new BehaviorResult(); result.setId(UUID.randomUUID()); result.setStartDate(startDate); result.setEndDate(endDate); - result.setSuccess(success); + result.setSuccess(pluginReturn.isSuccess()); result.setResponseTime(endDate.getTime() - startDate.getTime()); result.setBehaviorName(behavior.getName()); result.setPluginId(behavior.getUse()); @@ -116,12 +120,6 @@ public class ScenarioEngine { result.setShouldBeCountResponseTime(behavior .shouldBeCountResponseTime()); ret.add(result); - // TODO: refactor, collect result here, and judge if to calculate - // that - // behavior's result,because it may be a userBehavior or - // timerBehavior - // behavior.buildBehaviorResultAndAdd(plugin, startDate, success, - // endDate, ret); } return ret; } diff --git a/src/test/java/org/bench4q/agent/test/TestWithScriptFile.java b/src/test/java/org/bench4q/agent/test/TestWithScriptFile.java index e181424b..53584c60 100644 --- a/src/test/java/org/bench4q/agent/test/TestWithScriptFile.java +++ b/src/test/java/org/bench4q/agent/test/TestWithScriptFile.java @@ -18,7 +18,7 @@ public class TestWithScriptFile { private HttpRequester httpRequester; private String url = "http://localhost:6565/test/run"; private String filePath; - private static int load = 100; + private static int load = 1; public String getFilePath() { return filePath; From 85c4f4a0e1c59a5ac768e50fd5d3dfacc493afbd Mon Sep 17 00:00:00 2001 From: Tienan Chen Date: Wed, 20 Nov 2013 17:19:08 +0800 Subject: [PATCH 081/196] add the detail statistics of a user behavior, and it need to be unit test. --- .../org/bench4q/agent/api/TestController.java | 2 + .../api/model/behavior/BehaviorBaseModel.java | 10 +++ .../api/model/behavior/UserBehaviorModel.java | 12 ---- .../impl/AbstractDataCollector.java | 2 + .../impl/AgentResultDataCollector.java | 64 +++++++++++++++++++ .../interfaces/DataStatistics.java | 2 + .../agent/plugin/basic/CommandLinePlugin.java | 7 +- .../agent/plugin/basic/HttpPlugin.java | 40 +++++------- .../bench4q/agent/plugin/basic/LogPlugin.java | 5 +- .../plugin/result/CommandLineReturn.java | 7 ++ .../agent/plugin/result/HttpReturn.java | 14 +--- .../agent/plugin/result/LogReturn.java | 7 ++ .../agent/scenario/BehaviorResult.java | 18 +++--- .../agent/scenario/ScenarioEngine.java | 41 ++++++++---- .../agent/scenario/behavior/Behavior.java | 9 +++ 15 files changed, 165 insertions(+), 75 deletions(-) create mode 100644 src/main/java/org/bench4q/agent/plugin/result/CommandLineReturn.java create mode 100644 src/main/java/org/bench4q/agent/plugin/result/LogReturn.java diff --git a/src/main/java/org/bench4q/agent/api/TestController.java b/src/main/java/org/bench4q/agent/api/TestController.java index d735a8f0..cfc775d7 100644 --- a/src/main/java/org/bench4q/agent/api/TestController.java +++ b/src/main/java/org/bench4q/agent/api/TestController.java @@ -124,8 +124,10 @@ public class TestController { Behavior behavior = BehaviorFactory.getBuisinessObject(behaviorModel); behavior.setName(behaviorModel.getName()); behavior.setUse(behaviorModel.getUse()); + behavior.setId(behaviorModel.getId()); behavior.setParameters(new Parameter[behaviorModel.getParameters() .size()]); + int k = 0; for (k = 0; k < behaviorModel.getParameters().size(); k++) { ParameterModel parameterModel = behaviorModel.getParameters() diff --git a/src/main/java/org/bench4q/agent/api/model/behavior/BehaviorBaseModel.java b/src/main/java/org/bench4q/agent/api/model/behavior/BehaviorBaseModel.java index 8cce4fd0..57e05c5b 100644 --- a/src/main/java/org/bench4q/agent/api/model/behavior/BehaviorBaseModel.java +++ b/src/main/java/org/bench4q/agent/api/model/behavior/BehaviorBaseModel.java @@ -8,10 +8,20 @@ import javax.xml.bind.annotation.XmlElementWrapper; import org.bench4q.agent.api.model.ParameterModel; public abstract class BehaviorBaseModel { + private int id; private String use; private String name; private List parameters; + @XmlElement + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + @XmlElement public String getUse() { return use; diff --git a/src/main/java/org/bench4q/agent/api/model/behavior/UserBehaviorModel.java b/src/main/java/org/bench4q/agent/api/model/behavior/UserBehaviorModel.java index 20ee1d1d..0d94308d 100644 --- a/src/main/java/org/bench4q/agent/api/model/behavior/UserBehaviorModel.java +++ b/src/main/java/org/bench4q/agent/api/model/behavior/UserBehaviorModel.java @@ -5,22 +5,10 @@ import java.io.ByteArrayOutputStream; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; -import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement(name = "userBehavior") public class UserBehaviorModel extends BehaviorBaseModel { - private int id; - - @XmlElement - public int getId() { - return id; - } - - public void setId(int id) { - this.id = id; - } - public String getModelString() throws JAXBException { ByteArrayOutputStream os = new ByteArrayOutputStream(); Marshaller marshaller = JAXBContext.newInstance(this.getClass()) diff --git a/src/main/java/org/bench4q/agent/datacollector/impl/AbstractDataCollector.java b/src/main/java/org/bench4q/agent/datacollector/impl/AbstractDataCollector.java index 1611d6b3..37afc8ca 100644 --- a/src/main/java/org/bench4q/agent/datacollector/impl/AbstractDataCollector.java +++ b/src/main/java/org/bench4q/agent/datacollector/impl/AbstractDataCollector.java @@ -53,4 +53,6 @@ public abstract class AbstractDataCollector implements DataStatistics { public abstract Object getBriefStatistics(); + public abstract Object getDetailStatistics(int id); + } diff --git a/src/main/java/org/bench4q/agent/datacollector/impl/AgentResultDataCollector.java b/src/main/java/org/bench4q/agent/datacollector/impl/AgentResultDataCollector.java index 1ba67ed4..38d268db 100644 --- a/src/main/java/org/bench4q/agent/datacollector/impl/AgentResultDataCollector.java +++ b/src/main/java/org/bench4q/agent/datacollector/impl/AgentResultDataCollector.java @@ -2,7 +2,9 @@ package org.bench4q.agent.datacollector.impl; import java.text.SimpleDateFormat; import java.util.Date; +import java.util.HashMap; import java.util.List; +import java.util.Map; import java.util.UUID; import org.bench4q.agent.api.model.AgentBriefStatusModel; @@ -26,6 +28,9 @@ public class AgentResultDataCollector extends AbstractDataCollector { private long cumulativeFailCount; private static long TIME_UNIT = 1000; private UUID testID; + // The first integer is the behavior's id, and the second integer is + // the StatusCode of this behaviorResult. + private Map> detailMap; private void setTimeOfPreviousCall(long timeOfPreviousCall) { this.timeOfPreviousCall = timeOfPreviousCall; @@ -84,6 +89,14 @@ public class AgentResultDataCollector extends AbstractDataCollector { this.testID = testID; } + public Map> getDetailMap() { + return detailMap; + } + + private void setDetailMap(Map> detailMap) { + this.detailMap = detailMap; + } + public AgentResultDataCollector(UUID testId) { super.mustDoWhenIniti(); this.setTestID(testId); @@ -94,6 +107,7 @@ public class AgentResultDataCollector extends AbstractDataCollector { reset(); this.setCumulativeFailCount(0); this.setCumulativeSucessfulCount(0); + this.setDetailMap(new HashMap>()); } private void reset() { @@ -179,6 +193,34 @@ public class AgentResultDataCollector extends AbstractDataCollector { } else { this.failCountOfThisCall++; } + + dealWithDetailResult(behaviorResult); + } + + private void dealWithDetailResult(BehaviorResult behaviorResult) { + if (!this.detailMap.containsKey(new Integer(behaviorResult + .getBehaviorId()))) { + this.detailMap.put(new Integer(behaviorResult.getBehaviorId()), + new HashMap()); + } + Map detailStatusMap = this.detailMap + .get(new Integer(behaviorResult.getBehaviorId())); + if (!detailStatusMap.containsKey(new Integer(behaviorResult + .getStatusCode()))) { + detailStatusMap.put(new Integer(behaviorResult.getStatusCode()), + new DetailResult()); + } + + DetailResult detailResult = detailStatusMap.get(new Integer( + behaviorResult.getStatusCode())); + detailResult.contentLength += behaviorResult.getContentLength(); + detailResult.count++; + if (behaviorResult.getResponseTime() > detailResult.maxResponseTime) { + detailResult.maxResponseTime = behaviorResult.getResponseTime(); + } + if (behaviorResult.getResponseTime() < detailResult.minResponseTime) { + detailResult.minResponseTime = behaviorResult.getResponseTime(); + } } @Override @@ -189,4 +231,26 @@ public class AgentResultDataCollector extends AbstractDataCollector { + ".txt"; } + @Override + public Object getDetailStatistics(int id) { + if (!this.detailMap.containsKey(new Integer(id))) { + return null; + } + return this.detailMap.get(new Integer(id)); + } + } + +class DetailResult { + public long count; + public long contentLength; + public long minResponseTime; + public long maxResponseTime; + + public DetailResult() { + this.count = 0; + this.contentLength = 0; + this.minResponseTime = Long.MAX_VALUE; + this.maxResponseTime = Long.MIN_VALUE; + } +} \ No newline at end of file diff --git a/src/main/java/org/bench4q/agent/datacollector/interfaces/DataStatistics.java b/src/main/java/org/bench4q/agent/datacollector/interfaces/DataStatistics.java index 1757d98e..53bc3301 100644 --- a/src/main/java/org/bench4q/agent/datacollector/interfaces/DataStatistics.java +++ b/src/main/java/org/bench4q/agent/datacollector/interfaces/DataStatistics.java @@ -8,4 +8,6 @@ public interface DataStatistics { public void add(List behaviorResults); public Object getBriefStatistics(); + + public Object getDetailStatistics(int id); } diff --git a/src/main/java/org/bench4q/agent/plugin/basic/CommandLinePlugin.java b/src/main/java/org/bench4q/agent/plugin/basic/CommandLinePlugin.java index 255caa9e..1ab199af 100644 --- a/src/main/java/org/bench4q/agent/plugin/basic/CommandLinePlugin.java +++ b/src/main/java/org/bench4q/agent/plugin/basic/CommandLinePlugin.java @@ -6,6 +6,7 @@ import java.io.InputStreamReader; import org.bench4q.agent.plugin.Behavior; import org.bench4q.agent.plugin.Parameter; import org.bench4q.agent.plugin.Plugin; +import org.bench4q.agent.plugin.result.CommandLineReturn; @Plugin("CommandLine") public class CommandLinePlugin { @@ -33,7 +34,7 @@ public class CommandLinePlugin { } @Behavior("Command") - public boolean command(@Parameter("command") String command) { + public CommandLineReturn command(@Parameter("command") String command) { try { final Process process = Runtime.getRuntime().exec(command); new Thread() { @@ -79,10 +80,10 @@ public class CommandLinePlugin { } }.start(); process.waitFor(); - return true; + return new CommandLineReturn(true); } catch (Exception e) { e.printStackTrace(); - return false; + return new CommandLineReturn(false); } } } diff --git a/src/main/java/org/bench4q/agent/plugin/basic/HttpPlugin.java b/src/main/java/org/bench4q/agent/plugin/basic/HttpPlugin.java index ca868e25..2ba87249 100644 --- a/src/main/java/org/bench4q/agent/plugin/basic/HttpPlugin.java +++ b/src/main/java/org/bench4q/agent/plugin/basic/HttpPlugin.java @@ -32,16 +32,15 @@ public class HttpPlugin { httpURLConnection = getRequestURLConnection(url, requestMethod); stringBuffer = readConnectionInputStreamToBuffer(httpURLConnection); - return new HttpReturn(true, requestMethod, - httpURLConnection.getResponseCode(), + return new HttpReturn(true, httpURLConnection.getResponseCode(), stringBuffer.length() * 2, httpURLConnection.getContentType()); } catch (MalformedURLException e) { logger.info(e.getStackTrace()); - return new HttpReturn(false, requestMethod, 400, -1, ""); + return new HttpReturn(false, 400, -1, ""); } catch (IOException e) { logger.info(e.getStackTrace()); - return new HttpReturn(false, requestMethod, 404, -1, ""); + return new HttpReturn(false, 404, -1, ""); } } @@ -106,16 +105,15 @@ public class HttpPlugin { } writeContentToConnectOutputSteam(content, httpURLConnection); stringBuffer = readConnectionInputStreamToBuffer(httpURLConnection); - return new HttpReturn(true, requestMethod, - httpURLConnection.getResponseCode(), + return new HttpReturn(true, httpURLConnection.getResponseCode(), stringBuffer.length() * 2, httpURLConnection.getContentType()); } catch (MalformedURLException e) { logger.info(e.getStackTrace()); - return new HttpReturn(false, requestMethod, 400, -1, ""); + return new HttpReturn(false, 400, -1, ""); } catch (IOException e) { logger.info(e.getStackTrace()); - return new HttpReturn(false, requestMethod, 404, -1, ""); + return new HttpReturn(false, 404, -1, ""); } } @@ -130,16 +128,15 @@ public class HttpPlugin { url, requestMethod); writeContentToConnectOutputSteam(content, httpURLConnection); stringBuffer = readConnectionInputStreamToBuffer(httpURLConnection); - return new HttpReturn(true, requestMethod, - httpURLConnection.getResponseCode(), + return new HttpReturn(true, httpURLConnection.getResponseCode(), stringBuffer.length() * 2, httpURLConnection.getContentType()); } catch (MalformedURLException e) { logger.info(e.getStackTrace()); - return new HttpReturn(false, requestMethod, 400, -1, ""); + return new HttpReturn(false, 400, -1, ""); } catch (IOException e) { logger.info(e.getStackTrace()); - return new HttpReturn(false, requestMethod, 404, -1, ""); + return new HttpReturn(false, 404, -1, ""); } } @@ -148,25 +145,20 @@ public class HttpPlugin { @Parameter("content") String content) { StringBuffer stringBuffer = null; String requestMethod = "DELETE"; - int responseCode = -1; - long responseContentLength = 0; - String responseContentType = ""; try { HttpURLConnection httpURLConnection = getRequestURLConnection(url, requestMethod); writeContentToConnectOutputSteam(content, httpURLConnection); stringBuffer = readConnectionInputStreamToBuffer(httpURLConnection); - responseCode = httpURLConnection.getResponseCode(); - responseContentLength = stringBuffer.length() * 2; - responseContentType = httpURLConnection.getContentType(); - return new HttpReturn(true, requestMethod, - httpURLConnection.getResponseCode(), + return new HttpReturn(true, httpURLConnection.getResponseCode(), stringBuffer.length() * 2, httpURLConnection.getContentType()); - } catch (Exception e) { - logger.info(e); - return new HttpReturn(false, requestMethod, responseCode, - responseContentLength, responseContentType); + } catch (MalformedURLException e) { + logger.info(e.getStackTrace()); + return new HttpReturn(false, 400, -1, ""); + } catch (IOException e) { + logger.info(e.getStackTrace()); + return new HttpReturn(false, 404, -1, ""); } } } diff --git a/src/main/java/org/bench4q/agent/plugin/basic/LogPlugin.java b/src/main/java/org/bench4q/agent/plugin/basic/LogPlugin.java index bf128e32..01ed60e2 100644 --- a/src/main/java/org/bench4q/agent/plugin/basic/LogPlugin.java +++ b/src/main/java/org/bench4q/agent/plugin/basic/LogPlugin.java @@ -3,6 +3,7 @@ package org.bench4q.agent.plugin.basic; import org.bench4q.agent.plugin.Behavior; import org.bench4q.agent.plugin.Parameter; import org.bench4q.agent.plugin.Plugin; +import org.bench4q.agent.plugin.result.LogReturn; @Plugin("Log") public class LogPlugin { @@ -11,8 +12,8 @@ public class LogPlugin { } @Behavior("Log") - public boolean log(@Parameter("message") String message) { + public LogReturn log(@Parameter("message") String message) { System.out.println(message); - return true; + return new LogReturn(true); } } diff --git a/src/main/java/org/bench4q/agent/plugin/result/CommandLineReturn.java b/src/main/java/org/bench4q/agent/plugin/result/CommandLineReturn.java new file mode 100644 index 00000000..4e682097 --- /dev/null +++ b/src/main/java/org/bench4q/agent/plugin/result/CommandLineReturn.java @@ -0,0 +1,7 @@ +package org.bench4q.agent.plugin.result; + +public class CommandLineReturn extends PluginReturn { + public CommandLineReturn(boolean success) { + this.setSuccess(success); + } +} diff --git a/src/main/java/org/bench4q/agent/plugin/result/HttpReturn.java b/src/main/java/org/bench4q/agent/plugin/result/HttpReturn.java index 04e055a7..0821fd86 100644 --- a/src/main/java/org/bench4q/agent/plugin/result/HttpReturn.java +++ b/src/main/java/org/bench4q/agent/plugin/result/HttpReturn.java @@ -7,19 +7,10 @@ package org.bench4q.agent.plugin.result; * */ public class HttpReturn extends PluginReturn { - private String method; private int statusCode; private long contentLength; private String contentType; - public String getMethod() { - return method; - } - - private void setMethod(String method) { - this.method = method; - } - public int getStatusCode() { return statusCode; } @@ -44,10 +35,9 @@ public class HttpReturn extends PluginReturn { this.contentType = contentType; } - public HttpReturn(boolean success, String method, int statusCode, - long contentLength, String contentType) { + public HttpReturn(boolean success, int statusCode, long contentLength, + String contentType) { this.setSuccess(success); - this.setMethod(method); this.setStatusCode(statusCode); this.setContentLength(contentLength); this.setContentType(contentType); diff --git a/src/main/java/org/bench4q/agent/plugin/result/LogReturn.java b/src/main/java/org/bench4q/agent/plugin/result/LogReturn.java new file mode 100644 index 00000000..3fdfaa05 --- /dev/null +++ b/src/main/java/org/bench4q/agent/plugin/result/LogReturn.java @@ -0,0 +1,7 @@ +package org.bench4q.agent.plugin.result; + +public class LogReturn extends PluginReturn { + public LogReturn(boolean success) { + this.setSuccess(success); + } +} diff --git a/src/main/java/org/bench4q/agent/scenario/BehaviorResult.java b/src/main/java/org/bench4q/agent/scenario/BehaviorResult.java index 9f9ebb5a..6522c1cf 100644 --- a/src/main/java/org/bench4q/agent/scenario/BehaviorResult.java +++ b/src/main/java/org/bench4q/agent/scenario/BehaviorResult.java @@ -12,9 +12,9 @@ public class BehaviorResult { private Date endDate; private long responseTime; private boolean success; + private int behaviorId; private long contentLength; private int statusCode; - private String method; private String contentType; private boolean shouldBeCountResponseTime; @@ -82,6 +82,14 @@ public class BehaviorResult { this.success = success; } + public int getBehaviorId() { + return behaviorId; + } + + public void setBehaviorId(int behaviorId) { + this.behaviorId = behaviorId; + } + public long getContentLength() { return contentLength; } @@ -98,14 +106,6 @@ public class BehaviorResult { this.statusCode = statusCode; } - public String getMethod() { - return method; - } - - public void setMethod(String method) { - this.method = method; - } - public String getContentType() { return contentType; } diff --git a/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java b/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java index c3e4b359..3a4f1ff7 100644 --- a/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java +++ b/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java @@ -12,6 +12,7 @@ import java.util.concurrent.Executors; import org.apache.log4j.Logger; import org.bench4q.agent.plugin.Plugin; import org.bench4q.agent.plugin.PluginManager; +import org.bench4q.agent.plugin.result.HttpReturn; import org.bench4q.agent.plugin.result.PluginReturn; import org.bench4q.agent.scenario.behavior.Behavior; import org.bench4q.agent.storage.StorageHelper; @@ -107,23 +108,37 @@ public class ScenarioEngine { continue; } - BehaviorResult result = new BehaviorResult(); - result.setId(UUID.randomUUID()); - result.setStartDate(startDate); - result.setEndDate(endDate); - result.setSuccess(pluginReturn.isSuccess()); - result.setResponseTime(endDate.getTime() - startDate.getTime()); - result.setBehaviorName(behavior.getName()); - result.setPluginId(behavior.getUse()); - result.setPluginName(plugin.getClass().getAnnotation(Plugin.class) - .value()); - result.setShouldBeCountResponseTime(behavior - .shouldBeCountResponseTime()); - ret.add(result); + ret.add(buildBehaviorResult(behavior, plugin, startDate, + pluginReturn, endDate)); } return ret; } + private BehaviorResult buildBehaviorResult(Behavior behavior, + Object plugin, Date startDate, PluginReturn pluginReturn, + Date endDate) { + BehaviorResult result = new BehaviorResult(); + result.setId(UUID.randomUUID()); + result.setStartDate(startDate); + result.setEndDate(endDate); + result.setSuccess(pluginReturn.isSuccess()); + result.setResponseTime(endDate.getTime() - startDate.getTime()); + result.setBehaviorName(behavior.getName()); + result.setPluginId(behavior.getUse()); + result.setPluginName(plugin.getClass().getAnnotation(Plugin.class) + .value()); + result.setShouldBeCountResponseTime(behavior + .shouldBeCountResponseTime()); + if (pluginReturn instanceof HttpReturn) { + HttpReturn httpReturn = (HttpReturn) pluginReturn; + result.setBehaviorId(behavior.getId()); + result.setContentLength(httpReturn.getContentLength()); + result.setContentType(httpReturn.getContentType()); + result.setStatusCode(httpReturn.getStatusCode()); + } + return result; + } + private Map prepareBehaviorParameters(Behavior behavior) { Map behaviorParameters = new HashMap(); for (Parameter parameter : behavior.getParameters()) { diff --git a/src/main/java/org/bench4q/agent/scenario/behavior/Behavior.java b/src/main/java/org/bench4q/agent/scenario/behavior/Behavior.java index 8e9a2120..bd1c06cf 100644 --- a/src/main/java/org/bench4q/agent/scenario/behavior/Behavior.java +++ b/src/main/java/org/bench4q/agent/scenario/behavior/Behavior.java @@ -3,10 +3,19 @@ package org.bench4q.agent.scenario.behavior; import org.bench4q.agent.scenario.Parameter; public abstract class Behavior { + private int id; private String use; private String name; private Parameter[] parameters; + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + public String getUse() { return use; } From af79a93ae7cfb6c2396678a79bee7348bf6a9799 Mon Sep 17 00:00:00 2001 From: Tienan Chen Date: Wed, 20 Nov 2013 22:22:23 +0800 Subject: [PATCH 082/196] add a test to verify the detail statistics --- .../impl/AbstractDataCollector.java | 3 +- .../impl/AgentResultDataCollector.java | 16 +---- .../datacollector/impl/DetailResult.java | 41 +++++++++++ .../interfaces/DataStatistics.java | 4 +- .../agent/test/DataStatisticsTest.java | 29 +++++--- .../agent/test/DetailStatisticsTest.java | 70 +++++++++++++++++++ 6 files changed, 136 insertions(+), 27 deletions(-) create mode 100644 src/main/java/org/bench4q/agent/datacollector/impl/DetailResult.java create mode 100644 src/test/java/org/bench4q/agent/test/DetailStatisticsTest.java diff --git a/src/main/java/org/bench4q/agent/datacollector/impl/AbstractDataCollector.java b/src/main/java/org/bench4q/agent/datacollector/impl/AbstractDataCollector.java index 37afc8ca..7e10fd5c 100644 --- a/src/main/java/org/bench4q/agent/datacollector/impl/AbstractDataCollector.java +++ b/src/main/java/org/bench4q/agent/datacollector/impl/AbstractDataCollector.java @@ -3,6 +3,7 @@ package org.bench4q.agent.datacollector.impl; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.List; +import java.util.Map; import org.apache.log4j.Logger; import org.bench4q.agent.datacollector.interfaces.DataStatistics; @@ -53,6 +54,6 @@ public abstract class AbstractDataCollector implements DataStatistics { public abstract Object getBriefStatistics(); - public abstract Object getDetailStatistics(int id); + public abstract Map getDetailStatistics(int id); } diff --git a/src/main/java/org/bench4q/agent/datacollector/impl/AgentResultDataCollector.java b/src/main/java/org/bench4q/agent/datacollector/impl/AgentResultDataCollector.java index 38d268db..d19a6cc2 100644 --- a/src/main/java/org/bench4q/agent/datacollector/impl/AgentResultDataCollector.java +++ b/src/main/java/org/bench4q/agent/datacollector/impl/AgentResultDataCollector.java @@ -232,7 +232,7 @@ public class AgentResultDataCollector extends AbstractDataCollector { } @Override - public Object getDetailStatistics(int id) { + public Map getDetailStatistics(int id) { if (!this.detailMap.containsKey(new Integer(id))) { return null; } @@ -240,17 +240,3 @@ public class AgentResultDataCollector extends AbstractDataCollector { } } - -class DetailResult { - public long count; - public long contentLength; - public long minResponseTime; - public long maxResponseTime; - - public DetailResult() { - this.count = 0; - this.contentLength = 0; - this.minResponseTime = Long.MAX_VALUE; - this.maxResponseTime = Long.MIN_VALUE; - } -} \ No newline at end of file diff --git a/src/main/java/org/bench4q/agent/datacollector/impl/DetailResult.java b/src/main/java/org/bench4q/agent/datacollector/impl/DetailResult.java new file mode 100644 index 00000000..5af8721f --- /dev/null +++ b/src/main/java/org/bench4q/agent/datacollector/impl/DetailResult.java @@ -0,0 +1,41 @@ +package org.bench4q.agent.datacollector.impl; + +import java.lang.reflect.Field; + +public class DetailResult { + public long count; + public long contentLength; + public long minResponseTime; + public long maxResponseTime; + + public DetailResult() { + this.count = 0; + this.contentLength = 0; + this.minResponseTime = Long.MAX_VALUE; + this.maxResponseTime = Long.MIN_VALUE; + } + + public boolean equals(Object expectedObj) { + Field[] fields = this.getClass().getDeclaredFields(); + boolean equal = true; + try { + for (Field field : fields) { + field.setAccessible(true); + + if (field.getLong(this) != field.getLong(expectedObj)) { + System.out.println(field.getName() + + " is diferent, this is " + field.getLong(this) + + ", and the expected is " + + field.getLong(expectedObj)); + equal = false; + } + + } + } catch (Exception e) { + e.printStackTrace(); + equal = false; + + } + return equal; + } +} \ No newline at end of file diff --git a/src/main/java/org/bench4q/agent/datacollector/interfaces/DataStatistics.java b/src/main/java/org/bench4q/agent/datacollector/interfaces/DataStatistics.java index 53bc3301..9eced652 100644 --- a/src/main/java/org/bench4q/agent/datacollector/interfaces/DataStatistics.java +++ b/src/main/java/org/bench4q/agent/datacollector/interfaces/DataStatistics.java @@ -1,7 +1,9 @@ package org.bench4q.agent.datacollector.interfaces; import java.util.List; +import java.util.Map; +import org.bench4q.agent.datacollector.impl.DetailResult; import org.bench4q.agent.scenario.BehaviorResult; public interface DataStatistics { @@ -9,5 +11,5 @@ public interface DataStatistics { public Object getBriefStatistics(); - public Object getDetailStatistics(int id); + public Map getDetailStatistics(int id); } diff --git a/src/test/java/org/bench4q/agent/test/DataStatisticsTest.java b/src/test/java/org/bench4q/agent/test/DataStatisticsTest.java index daf9a23c..e0eeadc2 100644 --- a/src/test/java/org/bench4q/agent/test/DataStatisticsTest.java +++ b/src/test/java/org/bench4q/agent/test/DataStatisticsTest.java @@ -43,7 +43,7 @@ public class DataStatisticsTest { } @Test - public void addZeroTest() { + public void addZeroBriefTest() { this.getDataStatistics().add(makeBehaviorResultList(0)); AgentBriefStatusModel model = (AgentBriefStatusModel) this .getDataStatistics().getBriefStatistics(); @@ -53,7 +53,7 @@ public class DataStatisticsTest { } @Test - public void addOneTest() throws InterruptedException { + public void addOneBriefTest() throws InterruptedException { this.getDataStatistics().add(makeBehaviorResultList(1)); Thread.sleep(100); AgentBriefStatusModel model = (AgentBriefStatusModel) this @@ -65,7 +65,7 @@ public class DataStatisticsTest { } @Test - public void addTwoTest() throws InterruptedException { + public void addTwoBriefTest() throws InterruptedException { this.getDataStatistics().add(makeBehaviorResultList(2)); Thread.sleep(100); AgentBriefStatusModel model = (AgentBriefStatusModel) this @@ -75,7 +75,8 @@ public class DataStatisticsTest { assertTrue(model.equals(modelExpect)); } - private AgentBriefStatusModel makeUpStatusModelForTwoBehavior(long timeFrame) { + public static AgentBriefStatusModel makeUpStatusModelForTwoBehavior( + long timeFrame) { AgentBriefStatusModel model = new AgentBriefStatusModel(); model.setTimeFrame(timeFrame); model.setSuccessThroughputThisTime(1 * 1000 / timeFrame); @@ -91,7 +92,8 @@ public class DataStatisticsTest { return model; } - private void makeUpStatusModelForOneBehavior(AgentBriefStatusModel model) { + public static void makeUpStatusModelForOneBehavior( + AgentBriefStatusModel model) { model.setSuccessThroughputThisTime(1 * 1000 / model.getTimeFrame()); model.setFailCountFromBegin(0); model.setFailThroughputThisTime(0); @@ -104,7 +106,7 @@ public class DataStatisticsTest { model.setTotalSqureResponseTimeThisTime(40000); } - private AgentBriefStatusModel makeAllZeroModel() { + public static AgentBriefStatusModel makeAllZeroModel() { AgentBriefStatusModel model = new AgentBriefStatusModel(); model.setSuccessThroughputThisTime(0); model.setFailCountFromBegin(0); @@ -120,16 +122,17 @@ public class DataStatisticsTest { return model; } - private List makeBehaviorResultList(int count) { + public static List makeBehaviorResultList(int count) { List behaviorResults = new ArrayList(); for (int i = 0; i < count; i++) { - behaviorResults.add(buildBehaviorResult(200 + 10 * i, i % 2 == 0)); + behaviorResults.add(buildBehaviorResult(200 + 10 * i, i % 2 == 0, + 200 * (i + 1), 1)); } return behaviorResults; } - private BehaviorResult buildBehaviorResult(long responseTime, - boolean success) { + public static BehaviorResult buildBehaviorResult(long responseTime, + boolean success, int statusCode, int behaviorId) { Date date = new Date(); BehaviorResult result = new BehaviorResult(); result.setBehaviorName(""); @@ -141,6 +144,12 @@ public class DataStatisticsTest { result.setStartDate(date); result.setSuccess(success); result.setShouldBeCountResponseTime(true); + + result.setBehaviorId(behaviorId); + result.setContentLength(20); + result.setContentType("image"); + result.setStatusCode(statusCode); return result; } + } diff --git a/src/test/java/org/bench4q/agent/test/DetailStatisticsTest.java b/src/test/java/org/bench4q/agent/test/DetailStatisticsTest.java new file mode 100644 index 00000000..6cb18d23 --- /dev/null +++ b/src/test/java/org/bench4q/agent/test/DetailStatisticsTest.java @@ -0,0 +1,70 @@ +package org.bench4q.agent.test; + +import static org.junit.Assert.*; + +import java.util.Map; +import java.util.UUID; + +import org.bench4q.agent.datacollector.impl.AgentResultDataCollector; +import org.bench4q.agent.datacollector.impl.DetailResult; +import org.bench4q.agent.datacollector.interfaces.DataStatistics; +import org.bench4q.agent.storage.StorageHelper; +import org.junit.Test; +import org.springframework.context.ApplicationContext; +import org.springframework.context.support.ClassPathXmlApplicationContext; + +public class DetailStatisticsTest { + private DataStatistics detailStatistics; + + private DataStatistics getDetailStatistics() { + return detailStatistics; + } + + private void setDetailStatistics(DataStatistics detailStatistics) { + this.detailStatistics = detailStatistics; + } + + public DetailStatisticsTest() { + init(); + } + + private void init() { + @SuppressWarnings("resource") + ApplicationContext context = new ClassPathXmlApplicationContext( + "classpath*:/org/bench4q/agent/config/application-context.xml"); + AgentResultDataCollector agentResultDataCollector = new AgentResultDataCollector( + UUID.randomUUID()); + agentResultDataCollector.setStorageHelper((StorageHelper) context + .getBean(StorageHelper.class)); + this.setDetailStatistics(agentResultDataCollector); + } + + @Test + public void addZeroTest() { + this.getDetailStatistics().add( + DataStatisticsTest.makeBehaviorResultList(0)); + Object object = this.detailStatistics.getDetailStatistics(0); + assertEquals(null, object); + } + + @Test + public void addOneDetailTest() { + this.getDetailStatistics().add( + DataStatisticsTest.makeBehaviorResultList(1)); + + Map map = this.detailStatistics + .getDetailStatistics(1); + + DetailResult actualResult = map.get(200); + actualResult.equals(makeExpectedResultForOne()); + } + + private DetailResult makeExpectedResultForOne() { + DetailResult ret = new DetailResult(); + ret.contentLength = 20; + ret.count = 1; + ret.maxResponseTime = 200; + ret.minResponseTime = 200; + return ret; + } +} From e20390a40784501c39e11f7c78725135f717d9eb Mon Sep 17 00:00:00 2001 From: Tienan Chen Date: Thu, 21 Nov 2013 14:16:11 +0800 Subject: [PATCH 083/196] finish the unit test for detailStatistics of behavior --- .../impl/AbstractDataCollector.java | 2 +- .../impl/AgentResultDataCollector.java | 38 ++++++----- ...esult.java => DetailStatusCodeResult.java} | 8 ++- .../interfaces/DataStatistics.java | 4 +- .../agent/plugin/basic/HttpPlugin.java | 16 ++--- .../agent/test/DataStatisticsTest.java | 12 +++- .../agent/test/DetailStatisticsTest.java | 68 +++++++++++++++++-- 7 files changed, 111 insertions(+), 37 deletions(-) rename src/main/java/org/bench4q/agent/datacollector/impl/{DetailResult.java => DetailStatusCodeResult.java} (81%) diff --git a/src/main/java/org/bench4q/agent/datacollector/impl/AbstractDataCollector.java b/src/main/java/org/bench4q/agent/datacollector/impl/AbstractDataCollector.java index 7e10fd5c..ee7213a3 100644 --- a/src/main/java/org/bench4q/agent/datacollector/impl/AbstractDataCollector.java +++ b/src/main/java/org/bench4q/agent/datacollector/impl/AbstractDataCollector.java @@ -54,6 +54,6 @@ public abstract class AbstractDataCollector implements DataStatistics { public abstract Object getBriefStatistics(); - public abstract Map getDetailStatistics(int id); + public abstract Map getDetailStatistics(int id); } diff --git a/src/main/java/org/bench4q/agent/datacollector/impl/AgentResultDataCollector.java b/src/main/java/org/bench4q/agent/datacollector/impl/AgentResultDataCollector.java index d19a6cc2..1045808e 100644 --- a/src/main/java/org/bench4q/agent/datacollector/impl/AgentResultDataCollector.java +++ b/src/main/java/org/bench4q/agent/datacollector/impl/AgentResultDataCollector.java @@ -30,7 +30,7 @@ public class AgentResultDataCollector extends AbstractDataCollector { private UUID testID; // The first integer is the behavior's id, and the second integer is // the StatusCode of this behaviorResult. - private Map> detailMap; + private Map> detailMap; private void setTimeOfPreviousCall(long timeOfPreviousCall) { this.timeOfPreviousCall = timeOfPreviousCall; @@ -89,11 +89,12 @@ public class AgentResultDataCollector extends AbstractDataCollector { this.testID = testID; } - public Map> getDetailMap() { + public Map> getDetailMap() { return detailMap; } - private void setDetailMap(Map> detailMap) { + private void setDetailMap( + Map> detailMap) { this.detailMap = detailMap; } @@ -107,7 +108,7 @@ public class AgentResultDataCollector extends AbstractDataCollector { reset(); this.setCumulativeFailCount(0); this.setCumulativeSucessfulCount(0); - this.setDetailMap(new HashMap>()); + this.setDetailMap(new HashMap>()); } private void reset() { @@ -198,23 +199,28 @@ public class AgentResultDataCollector extends AbstractDataCollector { } private void dealWithDetailResult(BehaviorResult behaviorResult) { - if (!this.detailMap.containsKey(new Integer(behaviorResult - .getBehaviorId()))) { + if (!this.detailMap.containsKey(behaviorResult.getBehaviorId())) { this.detailMap.put(new Integer(behaviorResult.getBehaviorId()), - new HashMap()); + new HashMap()); } - Map detailStatusMap = this.detailMap - .get(new Integer(behaviorResult.getBehaviorId())); - if (!detailStatusMap.containsKey(new Integer(behaviorResult - .getStatusCode()))) { + Map detailStatusMap = this.detailMap + .get(behaviorResult.getBehaviorId()); + + if (!detailStatusMap.containsKey(behaviorResult.getStatusCode())) { detailStatusMap.put(new Integer(behaviorResult.getStatusCode()), - new DetailResult()); + new DetailStatusCodeResult()); } - DetailResult detailResult = detailStatusMap.get(new Integer( - behaviorResult.getStatusCode())); - detailResult.contentLength += behaviorResult.getContentLength(); + DetailStatusCodeResult detailResult = detailStatusMap + .get(behaviorResult.getStatusCode()); detailResult.count++; + if (!behaviorResult.isSuccess()) { + detailResult.maxResponseTime = 0; + detailResult.minResponseTime = 0; + detailResult.contentLength = 0; + return; + } + detailResult.contentLength += behaviorResult.getContentLength(); if (behaviorResult.getResponseTime() > detailResult.maxResponseTime) { detailResult.maxResponseTime = behaviorResult.getResponseTime(); } @@ -232,7 +238,7 @@ public class AgentResultDataCollector extends AbstractDataCollector { } @Override - public Map getDetailStatistics(int id) { + public Map getDetailStatistics(int id) { if (!this.detailMap.containsKey(new Integer(id))) { return null; } diff --git a/src/main/java/org/bench4q/agent/datacollector/impl/DetailResult.java b/src/main/java/org/bench4q/agent/datacollector/impl/DetailStatusCodeResult.java similarity index 81% rename from src/main/java/org/bench4q/agent/datacollector/impl/DetailResult.java rename to src/main/java/org/bench4q/agent/datacollector/impl/DetailStatusCodeResult.java index 5af8721f..0f11679a 100644 --- a/src/main/java/org/bench4q/agent/datacollector/impl/DetailResult.java +++ b/src/main/java/org/bench4q/agent/datacollector/impl/DetailStatusCodeResult.java @@ -2,19 +2,23 @@ package org.bench4q.agent.datacollector.impl; import java.lang.reflect.Field; -public class DetailResult { +public class DetailStatusCodeResult { public long count; public long contentLength; public long minResponseTime; public long maxResponseTime; - public DetailResult() { + public DetailStatusCodeResult() { this.count = 0; this.contentLength = 0; this.minResponseTime = Long.MAX_VALUE; this.maxResponseTime = Long.MIN_VALUE; } + public static boolean isSuccess(int statusCode) { + return statusCode == 200; + } + public boolean equals(Object expectedObj) { Field[] fields = this.getClass().getDeclaredFields(); boolean equal = true; diff --git a/src/main/java/org/bench4q/agent/datacollector/interfaces/DataStatistics.java b/src/main/java/org/bench4q/agent/datacollector/interfaces/DataStatistics.java index 9eced652..6afad32d 100644 --- a/src/main/java/org/bench4q/agent/datacollector/interfaces/DataStatistics.java +++ b/src/main/java/org/bench4q/agent/datacollector/interfaces/DataStatistics.java @@ -3,7 +3,7 @@ package org.bench4q.agent.datacollector.interfaces; import java.util.List; import java.util.Map; -import org.bench4q.agent.datacollector.impl.DetailResult; +import org.bench4q.agent.datacollector.impl.DetailStatusCodeResult; import org.bench4q.agent.scenario.BehaviorResult; public interface DataStatistics { @@ -11,5 +11,5 @@ public interface DataStatistics { public Object getBriefStatistics(); - public Map getDetailStatistics(int id); + public Map getDetailStatistics(int id); } diff --git a/src/main/java/org/bench4q/agent/plugin/basic/HttpPlugin.java b/src/main/java/org/bench4q/agent/plugin/basic/HttpPlugin.java index 2ba87249..800ab17c 100644 --- a/src/main/java/org/bench4q/agent/plugin/basic/HttpPlugin.java +++ b/src/main/java/org/bench4q/agent/plugin/basic/HttpPlugin.java @@ -37,10 +37,10 @@ public class HttpPlugin { httpURLConnection.getContentType()); } catch (MalformedURLException e) { logger.info(e.getStackTrace()); - return new HttpReturn(false, 400, -1, ""); + return new HttpReturn(false, 400, 0, ""); } catch (IOException e) { logger.info(e.getStackTrace()); - return new HttpReturn(false, 404, -1, ""); + return new HttpReturn(false, 404, 0, ""); } } @@ -110,10 +110,10 @@ public class HttpPlugin { httpURLConnection.getContentType()); } catch (MalformedURLException e) { logger.info(e.getStackTrace()); - return new HttpReturn(false, 400, -1, ""); + return new HttpReturn(false, 400, 0, ""); } catch (IOException e) { logger.info(e.getStackTrace()); - return new HttpReturn(false, 404, -1, ""); + return new HttpReturn(false, 404, 0, ""); } } @@ -133,10 +133,10 @@ public class HttpPlugin { httpURLConnection.getContentType()); } catch (MalformedURLException e) { logger.info(e.getStackTrace()); - return new HttpReturn(false, 400, -1, ""); + return new HttpReturn(false, 400, 0, ""); } catch (IOException e) { logger.info(e.getStackTrace()); - return new HttpReturn(false, 404, -1, ""); + return new HttpReturn(false, 404, 0, ""); } } @@ -155,10 +155,10 @@ public class HttpPlugin { httpURLConnection.getContentType()); } catch (MalformedURLException e) { logger.info(e.getStackTrace()); - return new HttpReturn(false, 400, -1, ""); + return new HttpReturn(false, 400, 0, ""); } catch (IOException e) { logger.info(e.getStackTrace()); - return new HttpReturn(false, 404, -1, ""); + return new HttpReturn(false, 404, 0, ""); } } } diff --git a/src/test/java/org/bench4q/agent/test/DataStatisticsTest.java b/src/test/java/org/bench4q/agent/test/DataStatisticsTest.java index e0eeadc2..9eec2422 100644 --- a/src/test/java/org/bench4q/agent/test/DataStatisticsTest.java +++ b/src/test/java/org/bench4q/agent/test/DataStatisticsTest.java @@ -125,8 +125,9 @@ public class DataStatisticsTest { public static List makeBehaviorResultList(int count) { List behaviorResults = new ArrayList(); for (int i = 0; i < count; i++) { + int statusCode = i % 2 == 0 ? 200 : 400; behaviorResults.add(buildBehaviorResult(200 + 10 * i, i % 2 == 0, - 200 * (i + 1), 1)); + statusCode, 1)); } return behaviorResults; } @@ -146,8 +147,13 @@ public class DataStatisticsTest { result.setShouldBeCountResponseTime(true); result.setBehaviorId(behaviorId); - result.setContentLength(20); - result.setContentType("image"); + if (result.isSuccess()) { + result.setContentLength(20); + result.setContentType("image"); + } else { + result.setContentLength(0); + result.setContentType(""); + } result.setStatusCode(statusCode); return result; } diff --git a/src/test/java/org/bench4q/agent/test/DetailStatisticsTest.java b/src/test/java/org/bench4q/agent/test/DetailStatisticsTest.java index 6cb18d23..ca020854 100644 --- a/src/test/java/org/bench4q/agent/test/DetailStatisticsTest.java +++ b/src/test/java/org/bench4q/agent/test/DetailStatisticsTest.java @@ -2,11 +2,12 @@ package org.bench4q.agent.test; import static org.junit.Assert.*; +import java.util.HashMap; import java.util.Map; import java.util.UUID; import org.bench4q.agent.datacollector.impl.AgentResultDataCollector; -import org.bench4q.agent.datacollector.impl.DetailResult; +import org.bench4q.agent.datacollector.impl.DetailStatusCodeResult; import org.bench4q.agent.datacollector.interfaces.DataStatistics; import org.bench4q.agent.storage.StorageHelper; import org.junit.Test; @@ -52,19 +53,76 @@ public class DetailStatisticsTest { this.getDetailStatistics().add( DataStatisticsTest.makeBehaviorResultList(1)); - Map map = this.detailStatistics + Map map = this.detailStatistics .getDetailStatistics(1); - DetailResult actualResult = map.get(200); + DetailStatusCodeResult actualResult = map.get(200); actualResult.equals(makeExpectedResultForOne()); } - private DetailResult makeExpectedResultForOne() { - DetailResult ret = new DetailResult(); + private DetailStatusCodeResult makeExpectedResultForOne() { + DetailStatusCodeResult ret = new DetailStatusCodeResult(); ret.contentLength = 20; ret.count = 1; ret.maxResponseTime = 200; ret.minResponseTime = 200; return ret; } + + @Test + public void addTwoDetailTest() { + this.getDetailStatistics().add( + DataStatisticsTest.makeBehaviorResultList(2)); + Map map = this.detailStatistics + .getDetailStatistics(1); + assertTrue(mapEquals(map, makeExpectedMapForTwo())); + // DetailResult ex + } + + private Map makeExpectedMapForTwo() { + Map ret = new HashMap(); + ret.put(new Integer(200), buildCodeResult(20, 1, 200, 200)); + ret.put(new Integer(400), buildCodeResult(0, 1, 0, 0)); + return ret; + } + + private DetailStatusCodeResult buildCodeResult(long contentLength, + long count, long maxResponseTime, long minResponseTime) { + DetailStatusCodeResult ret = new DetailStatusCodeResult(); + ret.contentLength = contentLength; + ret.count = count; + ret.maxResponseTime = maxResponseTime; + ret.minResponseTime = minResponseTime; + return ret; + } + + private boolean mapEquals(Map mapActual, + Map mapExpected) { + boolean equal = true; + if (mapActual.size() != mapExpected.size()) { + return false; + } + for (int i : mapActual.keySet()) { + if (!mapActual.get(i).equals(mapExpected.get(i))) { + equal = false; + } + } + return equal; + } + + @Test + public void addThreeTest() { + this.getDetailStatistics().add( + DataStatisticsTest.makeBehaviorResultList(3)); + Map mapActual = this + .getDetailStatistics().getDetailStatistics(1); + assertTrue(mapEquals(mapActual, makeExpectedMapForThree())); + } + + private Map makeExpectedMapForThree() { + Map retMap = new HashMap(); + retMap.put(200, buildCodeResult(40, 2, 220, 200)); + retMap.put(400, buildCodeResult(0, 1, 0, 0)); + return retMap; + } } From cbdfede570bab3a9296c590be668bfd9da8fc90c Mon Sep 17 00:00:00 2001 From: Tienan Chen Date: Thu, 21 Nov 2013 14:30:38 +0800 Subject: [PATCH 084/196] remove a redundant class, and add detailResultmodel for behavior --- .../api/model/BehaviorDetailResultModel.java | 16 +++ .../api/model/StatusCodeResultModel.java | 50 +++++++++ .../agent/api/model/TestBriefStatusModel.java | 101 ------------------ 3 files changed, 66 insertions(+), 101 deletions(-) create mode 100644 src/main/java/org/bench4q/agent/api/model/BehaviorDetailResultModel.java create mode 100644 src/main/java/org/bench4q/agent/api/model/StatusCodeResultModel.java delete mode 100644 src/main/java/org/bench4q/agent/api/model/TestBriefStatusModel.java diff --git a/src/main/java/org/bench4q/agent/api/model/BehaviorDetailResultModel.java b/src/main/java/org/bench4q/agent/api/model/BehaviorDetailResultModel.java new file mode 100644 index 00000000..4ab90b18 --- /dev/null +++ b/src/main/java/org/bench4q/agent/api/model/BehaviorDetailResultModel.java @@ -0,0 +1,16 @@ +package org.bench4q.agent.api.model; + +public class BehaviorDetailResultModel { + private int behaviorId; + + // private List<> + + public int getBehaviorId() { + return behaviorId; + } + + public void setBehaviorId(int behaviorId) { + this.behaviorId = behaviorId; + } + +} diff --git a/src/main/java/org/bench4q/agent/api/model/StatusCodeResultModel.java b/src/main/java/org/bench4q/agent/api/model/StatusCodeResultModel.java new file mode 100644 index 00000000..0ce87028 --- /dev/null +++ b/src/main/java/org/bench4q/agent/api/model/StatusCodeResultModel.java @@ -0,0 +1,50 @@ +package org.bench4q.agent.api.model; + +public class StatusCodeResultModel { + private int statusCode; + private long count; + private long contentLength; + private long maxResponseTime; + private long minResponseTime; + + public int getStatusCode() { + return statusCode; + } + + public void setStatusCode(int statusCode) { + this.statusCode = statusCode; + } + + public long getCount() { + return count; + } + + public void setCount(long count) { + this.count = count; + } + + public long getContentLength() { + return contentLength; + } + + public void setContentLength(long contentLength) { + this.contentLength = contentLength; + } + + public long getMaxResponseTime() { + return maxResponseTime; + } + + public void setMaxResponseTime(long maxResponseTime) { + this.maxResponseTime = maxResponseTime; + } + + public long getMinResponseTime() { + return minResponseTime; + } + + public void setMinResponseTime(long minResponseTime) { + this.minResponseTime = minResponseTime; + } + +} diff --git a/src/main/java/org/bench4q/agent/api/model/TestBriefStatusModel.java b/src/main/java/org/bench4q/agent/api/model/TestBriefStatusModel.java deleted file mode 100644 index 71cf96d3..00000000 --- a/src/main/java/org/bench4q/agent/api/model/TestBriefStatusModel.java +++ /dev/null @@ -1,101 +0,0 @@ -package org.bench4q.agent.api.model; - -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 long runningTime; - private int successCount; - private int failCount; - private int finishedCount; - private int scenarioBehaviorCount; - private double averageResponseTime; - private boolean finished; - - @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 long getRunningTime() { - return runningTime; - } - - public void setRunningTime(long runningTime) { - this.runningTime = runningTime; - } - - @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 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; - } - - @XmlElement - public boolean isFinished() { - return finished; - } - - public void setFinished(boolean finished) { - this.finished = finished; - } - -} From e7ab8f8027ea531784bcc5b15cee870e96a577b6 Mon Sep 17 00:00:00 2001 From: Tienan Chen Date: Fri, 22 Nov 2013 11:16:06 +0800 Subject: [PATCH 085/196] let the ContantTimer not throw exception when it's interrupted. --- .../org/bench4q/agent/plugin/basic/ConstantTimerPlugin.java | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/main/java/org/bench4q/agent/plugin/basic/ConstantTimerPlugin.java b/src/main/java/org/bench4q/agent/plugin/basic/ConstantTimerPlugin.java index 091f4086..12af61e7 100644 --- a/src/main/java/org/bench4q/agent/plugin/basic/ConstantTimerPlugin.java +++ b/src/main/java/org/bench4q/agent/plugin/basic/ConstantTimerPlugin.java @@ -1,5 +1,6 @@ package org.bench4q.agent.plugin.basic; +import org.apache.log4j.Logger; import org.bench4q.agent.plugin.Behavior; import org.bench4q.agent.plugin.Parameter; import org.bench4q.agent.plugin.Plugin; @@ -7,6 +8,8 @@ import org.bench4q.agent.plugin.result.TimerReturn; @Plugin("ConstantTimer") public class ConstantTimerPlugin { + private Logger logger = Logger.getLogger(ConstantTimerPlugin.class); + public ConstantTimerPlugin() { } @@ -17,7 +20,7 @@ public class ConstantTimerPlugin { Thread.sleep(time); return new TimerReturn(true); } catch (Exception e) { - e.printStackTrace(); + logger.info("sleep interrupted!"); return new TimerReturn(false); } } From d66f1ac6964ac0764f8738cbb96ffa4d0e32a632 Mon Sep 17 00:00:00 2001 From: Tienan Chen Date: Mon, 25 Nov 2013 09:04:09 +0800 Subject: [PATCH 086/196] refact --- .../org/bench4q/agent/plugin/basic/HttpPlugin.java | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/src/main/java/org/bench4q/agent/plugin/basic/HttpPlugin.java b/src/main/java/org/bench4q/agent/plugin/basic/HttpPlugin.java index 800ab17c..b363a721 100644 --- a/src/main/java/org/bench4q/agent/plugin/basic/HttpPlugin.java +++ b/src/main/java/org/bench4q/agent/plugin/basic/HttpPlugin.java @@ -30,7 +30,7 @@ public class HttpPlugin { try { httpURLConnection = getRequestURLConnection(url, requestMethod); - stringBuffer = readConnectionInputStreamToBuffer(httpURLConnection); + stringBuffer = readConnectionInputStream(httpURLConnection); return new HttpReturn(true, httpURLConnection.getResponseCode(), stringBuffer.length() * 2, @@ -62,13 +62,12 @@ public class HttpPlugin { return httpURLConnection; } - private StringBuffer readConnectionInputStreamToBuffer( + private StringBuffer readConnectionInputStream( HttpURLConnection httpURLConnection) throws IOException { - StringBuffer stringBuffer; + StringBuffer stringBuffer = new StringBuffer(); BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(httpURLConnection.getInputStream())); int temp = -1; - stringBuffer = new StringBuffer(); while ((temp = bufferedReader.read()) != -1) { stringBuffer.append((char) temp); } @@ -104,7 +103,7 @@ public class HttpPlugin { httpURLConnection.setRequestProperty("Accept", accept); } writeContentToConnectOutputSteam(content, httpURLConnection); - stringBuffer = readConnectionInputStreamToBuffer(httpURLConnection); + stringBuffer = readConnectionInputStream(httpURLConnection); return new HttpReturn(true, httpURLConnection.getResponseCode(), stringBuffer.length() * 2, httpURLConnection.getContentType()); @@ -127,7 +126,7 @@ public class HttpPlugin { HttpURLConnection httpURLConnection = this.getRequestURLConnection( url, requestMethod); writeContentToConnectOutputSteam(content, httpURLConnection); - stringBuffer = readConnectionInputStreamToBuffer(httpURLConnection); + stringBuffer = readConnectionInputStream(httpURLConnection); return new HttpReturn(true, httpURLConnection.getResponseCode(), stringBuffer.length() * 2, httpURLConnection.getContentType()); @@ -149,7 +148,7 @@ public class HttpPlugin { HttpURLConnection httpURLConnection = getRequestURLConnection(url, requestMethod); writeContentToConnectOutputSteam(content, httpURLConnection); - stringBuffer = readConnectionInputStreamToBuffer(httpURLConnection); + stringBuffer = readConnectionInputStream(httpURLConnection); return new HttpReturn(true, httpURLConnection.getResponseCode(), stringBuffer.length() * 2, httpURLConnection.getContentType()); From b4699d53d0f46dd2bf4c55457e47e5434da54357 Mon Sep 17 00:00:00 2001 From: Tienan Chen Date: Tue, 26 Nov 2013 10:33:49 +0800 Subject: [PATCH 087/196] let the agent collect the data and do statistics by one behavior --- .../impl/AbstractDataCollector.java | 11 ++--- .../impl/AgentResultDataCollector.java | 15 +++---- .../interfaces/DataStatistics.java | 3 +- .../agent/plugin/basic/HttpPlugin.java | 18 ++++---- .../agent/scenario/RunnableExecutor.java | 44 ------------------- .../agent/scenario/ScenarioEngine.java | 19 +++----- .../org/bench4q/agent/share/DealWithLog.java | 13 ++++++ .../agent/test/DataStatisticsTest.java | 14 ++++-- .../agent/test/DetailStatisticsTest.java | 27 ++++++++---- .../agent/test/TestWithScriptFile.java | 4 +- 10 files changed, 74 insertions(+), 94 deletions(-) delete mode 100644 src/main/java/org/bench4q/agent/scenario/RunnableExecutor.java create mode 100644 src/main/java/org/bench4q/agent/share/DealWithLog.java diff --git a/src/main/java/org/bench4q/agent/datacollector/impl/AbstractDataCollector.java b/src/main/java/org/bench4q/agent/datacollector/impl/AbstractDataCollector.java index ee7213a3..6cbedb9b 100644 --- a/src/main/java/org/bench4q/agent/datacollector/impl/AbstractDataCollector.java +++ b/src/main/java/org/bench4q/agent/datacollector/impl/AbstractDataCollector.java @@ -2,7 +2,6 @@ package org.bench4q.agent.datacollector.impl; import java.net.InetAddress; import java.net.UnknownHostException; -import java.util.List; import java.util.Map; import org.apache.log4j.Logger; @@ -41,19 +40,21 @@ public abstract class AbstractDataCollector implements DataStatistics { } } - public void add(List behaviorResults) { - // for (BehaviorResult behaviorResult : behaviorResults) { + // public void add(List behaviorResults) { + // } + + public void add(BehaviorResult behaviorResult) { // TestDetailModel testDetailModel = new TestDetailModel( // behaviorResult); // this.getStorageHelper().getLocalStorage() // .writeFile(testDetailModel.getModelString(), getSavePath()); - // } } protected abstract String getSavePath(); public abstract Object getBriefStatistics(); - public abstract Map getDetailStatistics(int id); + public abstract Map getDetailStatistics( + int id); } diff --git a/src/main/java/org/bench4q/agent/datacollector/impl/AgentResultDataCollector.java b/src/main/java/org/bench4q/agent/datacollector/impl/AgentResultDataCollector.java index 1045808e..f47ef0aa 100644 --- a/src/main/java/org/bench4q/agent/datacollector/impl/AgentResultDataCollector.java +++ b/src/main/java/org/bench4q/agent/datacollector/impl/AgentResultDataCollector.java @@ -3,7 +3,6 @@ package org.bench4q.agent.datacollector.impl; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; -import java.util.List; import java.util.Map; import java.util.UUID; @@ -125,13 +124,6 @@ public class AgentResultDataCollector extends AbstractDataCollector { // DataStatistics Interface start // /////////////////////////////// - public void add(List behaviorResults) { - super.add(behaviorResults); - for (BehaviorResult behaviorResult : behaviorResults) { - addItem(behaviorResult); - } - } - public AgentBriefStatusModel getBriefStatistics() { AgentBriefStatusModel result = new AgentBriefStatusModel(); result.setTimeFrame(System.currentTimeMillis() @@ -229,6 +221,13 @@ public class AgentResultDataCollector extends AbstractDataCollector { } } + @Override + public void add(BehaviorResult behaviorResult) { + // TODO Auto-generated method stub + super.add(behaviorResult); + addItem(behaviorResult); + } + @Override protected String getSavePath() { return "DetailResults" + System.getProperty("file.separator") diff --git a/src/main/java/org/bench4q/agent/datacollector/interfaces/DataStatistics.java b/src/main/java/org/bench4q/agent/datacollector/interfaces/DataStatistics.java index 6afad32d..0040b142 100644 --- a/src/main/java/org/bench4q/agent/datacollector/interfaces/DataStatistics.java +++ b/src/main/java/org/bench4q/agent/datacollector/interfaces/DataStatistics.java @@ -1,13 +1,12 @@ package org.bench4q.agent.datacollector.interfaces; -import java.util.List; import java.util.Map; import org.bench4q.agent.datacollector.impl.DetailStatusCodeResult; import org.bench4q.agent.scenario.BehaviorResult; public interface DataStatistics { - public void add(List behaviorResults); + public void add(BehaviorResult behaviorResult); public Object getBriefStatistics(); diff --git a/src/main/java/org/bench4q/agent/plugin/basic/HttpPlugin.java b/src/main/java/org/bench4q/agent/plugin/basic/HttpPlugin.java index b363a721..e0527feb 100644 --- a/src/main/java/org/bench4q/agent/plugin/basic/HttpPlugin.java +++ b/src/main/java/org/bench4q/agent/plugin/basic/HttpPlugin.java @@ -13,6 +13,7 @@ import org.bench4q.agent.plugin.Behavior; import org.bench4q.agent.plugin.Parameter; import org.bench4q.agent.plugin.Plugin; import org.bench4q.agent.plugin.result.HttpReturn; +import org.bench4q.agent.share.DealWithLog; @Plugin("Http") public class HttpPlugin { @@ -31,15 +32,14 @@ public class HttpPlugin { try { httpURLConnection = getRequestURLConnection(url, requestMethod); stringBuffer = readConnectionInputStream(httpURLConnection); - return new HttpReturn(true, httpURLConnection.getResponseCode(), stringBuffer.length() * 2, httpURLConnection.getContentType()); } catch (MalformedURLException e) { - logger.info(e.getStackTrace()); + logger.info(DealWithLog.getExceptionStackTrace(e)); return new HttpReturn(false, 400, 0, ""); } catch (IOException e) { - logger.info(e.getStackTrace()); + logger.info(DealWithLog.getExceptionStackTrace(e)); return new HttpReturn(false, 404, 0, ""); } @@ -108,10 +108,10 @@ public class HttpPlugin { stringBuffer.length() * 2, httpURLConnection.getContentType()); } catch (MalformedURLException e) { - logger.info(e.getStackTrace()); + logger.info(DealWithLog.getExceptionStackTrace(e)); return new HttpReturn(false, 400, 0, ""); } catch (IOException e) { - logger.info(e.getStackTrace()); + logger.info(DealWithLog.getExceptionStackTrace(e)); return new HttpReturn(false, 404, 0, ""); } @@ -131,10 +131,10 @@ public class HttpPlugin { stringBuffer.length() * 2, httpURLConnection.getContentType()); } catch (MalformedURLException e) { - logger.info(e.getStackTrace()); + logger.info(DealWithLog.getExceptionStackTrace(e)); return new HttpReturn(false, 400, 0, ""); } catch (IOException e) { - logger.info(e.getStackTrace()); + logger.info(DealWithLog.getExceptionStackTrace(e)); return new HttpReturn(false, 404, 0, ""); } } @@ -153,10 +153,10 @@ public class HttpPlugin { stringBuffer.length() * 2, httpURLConnection.getContentType()); } catch (MalformedURLException e) { - logger.info(e.getStackTrace()); + logger.info(DealWithLog.getExceptionStackTrace(e)); return new HttpReturn(false, 400, 0, ""); } catch (IOException e) { - logger.info(e.getStackTrace()); + logger.info(DealWithLog.getExceptionStackTrace(e)); return new HttpReturn(false, 404, 0, ""); } } diff --git a/src/main/java/org/bench4q/agent/scenario/RunnableExecutor.java b/src/main/java/org/bench4q/agent/scenario/RunnableExecutor.java deleted file mode 100644 index 1564dff9..00000000 --- a/src/main/java/org/bench4q/agent/scenario/RunnableExecutor.java +++ /dev/null @@ -1,44 +0,0 @@ -package org.bench4q.agent.scenario; - -import java.util.List; -import java.util.UUID; - -public class RunnableExecutor implements Runnable { - private ScenarioEngine scenarioEngine; - private UUID runId; - private List behaviorResults; - private Scenario scenario; - - private void setScenarioEngine(ScenarioEngine scenarioEngine) { - this.scenarioEngine = scenarioEngine; - } - - private void setBehaviorResults(List behaviorResults) { - this.behaviorResults = behaviorResults; - } - - private void setRunId(UUID runId) { - this.runId = runId; - } - - private void setScenario(Scenario scenario) { - this.scenario = scenario; - } - - public RunnableExecutor(ScenarioEngine scenarioEngine, UUID runId, - Scenario scenario, List behaviorResults) { - this.setScenarioEngine(scenarioEngine); - this.setRunId(runId); - this.setScenario(scenario); - this.setBehaviorResults(behaviorResults); - } - - public void run() { - ScenarioContext scenarioContext = this.scenarioEngine.getRunningTests() - .get(this.runId); - while (!scenarioContext.getExecutorService().isShutdown()) { - this.behaviorResults.addAll(this.scenarioEngine - .doRunScenario(this.scenario)); - } - } -} diff --git a/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java b/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java index 3a4f1ff7..76e8ec43 100644 --- a/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java +++ b/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java @@ -1,9 +1,7 @@ package org.bench4q.agent.scenario; -import java.util.ArrayList; import java.util.Date; import java.util.HashMap; -import java.util.List; import java.util.Map; import java.util.UUID; import java.util.concurrent.ExecutorService; @@ -78,8 +76,7 @@ public class ScenarioEngine { Runnable runnable = new Runnable() { public void run() { while (!scenarioContext.getExecutorService().isShutdown()) { - scenarioContext.getDataStatistics().add( - doRunScenario(scenario)); + doRunScenario(scenarioContext); System.out.println("End for once"); } } @@ -92,12 +89,11 @@ public class ScenarioEngine { } } - public List doRunScenario(Scenario scenario) { + public void doRunScenario(ScenarioContext context) { Map plugins = new HashMap(); - preparePlugins(scenario, plugins); + preparePlugins(context.getScenario(), plugins); - List ret = new ArrayList(); - for (Behavior behavior : scenario.getBehaviors()) { + for (Behavior behavior : context.getScenario().getBehaviors()) { Object plugin = plugins.get(behavior.getUse()); Map behaviorParameters = prepareBehaviorParameters(behavior); Date startDate = new Date(System.currentTimeMillis()); @@ -107,11 +103,10 @@ public class ScenarioEngine { if (!behavior.shouldBeCountResponseTime()) { continue; } - - ret.add(buildBehaviorResult(behavior, plugin, startDate, - pluginReturn, endDate)); + context.getDataStatistics().add( + buildBehaviorResult(behavior, plugin, startDate, + pluginReturn, endDate)); } - return ret; } private BehaviorResult buildBehaviorResult(Behavior behavior, diff --git a/src/main/java/org/bench4q/agent/share/DealWithLog.java b/src/main/java/org/bench4q/agent/share/DealWithLog.java new file mode 100644 index 00000000..d2fca2da --- /dev/null +++ b/src/main/java/org/bench4q/agent/share/DealWithLog.java @@ -0,0 +1,13 @@ +package org.bench4q.agent.share; + +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; + +public class DealWithLog { + public static ByteArrayOutputStream getExceptionStackTrace(Exception e) { + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + PrintStream printStream = new PrintStream(outputStream); + e.printStackTrace(printStream); + return outputStream; + } +} diff --git a/src/test/java/org/bench4q/agent/test/DataStatisticsTest.java b/src/test/java/org/bench4q/agent/test/DataStatisticsTest.java index 9eec2422..3c15d84c 100644 --- a/src/test/java/org/bench4q/agent/test/DataStatisticsTest.java +++ b/src/test/java/org/bench4q/agent/test/DataStatisticsTest.java @@ -44,7 +44,10 @@ public class DataStatisticsTest { @Test public void addZeroBriefTest() { - this.getDataStatistics().add(makeBehaviorResultList(0)); + for (BehaviorResult behaviorResult : makeBehaviorResultList(0)) { + this.getDataStatistics().add(behaviorResult); + } + AgentBriefStatusModel model = (AgentBriefStatusModel) this .getDataStatistics().getBriefStatistics(); AgentBriefStatusModel modelExpect = makeAllZeroModel(); @@ -54,7 +57,10 @@ public class DataStatisticsTest { @Test public void addOneBriefTest() throws InterruptedException { - this.getDataStatistics().add(makeBehaviorResultList(1)); + for (BehaviorResult behaviorResult : makeBehaviorResultList(1)) { + this.getDataStatistics().add(behaviorResult); + } + Thread.sleep(100); AgentBriefStatusModel model = (AgentBriefStatusModel) this .getDataStatistics().getBriefStatistics(); @@ -66,7 +72,9 @@ public class DataStatisticsTest { @Test public void addTwoBriefTest() throws InterruptedException { - this.getDataStatistics().add(makeBehaviorResultList(2)); + for (BehaviorResult behaviorResult : makeBehaviorResultList(2)) { + this.getDataStatistics().add(behaviorResult); + } Thread.sleep(100); AgentBriefStatusModel model = (AgentBriefStatusModel) this .getDataStatistics().getBriefStatistics(); diff --git a/src/test/java/org/bench4q/agent/test/DetailStatisticsTest.java b/src/test/java/org/bench4q/agent/test/DetailStatisticsTest.java index ca020854..314c1533 100644 --- a/src/test/java/org/bench4q/agent/test/DetailStatisticsTest.java +++ b/src/test/java/org/bench4q/agent/test/DetailStatisticsTest.java @@ -9,6 +9,7 @@ import java.util.UUID; import org.bench4q.agent.datacollector.impl.AgentResultDataCollector; import org.bench4q.agent.datacollector.impl.DetailStatusCodeResult; import org.bench4q.agent.datacollector.interfaces.DataStatistics; +import org.bench4q.agent.scenario.BehaviorResult; import org.bench4q.agent.storage.StorageHelper; import org.junit.Test; import org.springframework.context.ApplicationContext; @@ -42,17 +43,21 @@ public class DetailStatisticsTest { @Test public void addZeroTest() { - this.getDetailStatistics().add( - DataStatisticsTest.makeBehaviorResultList(0)); + for (BehaviorResult behaviorResult : DataStatisticsTest + .makeBehaviorResultList(0)) { + this.getDetailStatistics().add(behaviorResult); + } + Object object = this.detailStatistics.getDetailStatistics(0); assertEquals(null, object); } @Test public void addOneDetailTest() { - this.getDetailStatistics().add( - DataStatisticsTest.makeBehaviorResultList(1)); - + for (BehaviorResult behaviorResult : DataStatisticsTest + .makeBehaviorResultList(1)) { + this.getDetailStatistics().add(behaviorResult); + } Map map = this.detailStatistics .getDetailStatistics(1); @@ -71,8 +76,10 @@ public class DetailStatisticsTest { @Test public void addTwoDetailTest() { - this.getDetailStatistics().add( - DataStatisticsTest.makeBehaviorResultList(2)); + for (BehaviorResult behaviorResult : DataStatisticsTest + .makeBehaviorResultList(2)) { + this.getDetailStatistics().add(behaviorResult); + } Map map = this.detailStatistics .getDetailStatistics(1); assertTrue(mapEquals(map, makeExpectedMapForTwo())); @@ -112,8 +119,10 @@ public class DetailStatisticsTest { @Test public void addThreeTest() { - this.getDetailStatistics().add( - DataStatisticsTest.makeBehaviorResultList(3)); + for (BehaviorResult behaviorResult : DataStatisticsTest + .makeBehaviorResultList(3)) { + this.getDetailStatistics().add(behaviorResult); + } Map mapActual = this .getDetailStatistics().getDetailStatistics(1); assertTrue(mapEquals(mapActual, makeExpectedMapForThree())); diff --git a/src/test/java/org/bench4q/agent/test/TestWithScriptFile.java b/src/test/java/org/bench4q/agent/test/TestWithScriptFile.java index 53584c60..32e46f6e 100644 --- a/src/test/java/org/bench4q/agent/test/TestWithScriptFile.java +++ b/src/test/java/org/bench4q/agent/test/TestWithScriptFile.java @@ -18,7 +18,7 @@ public class TestWithScriptFile { private HttpRequester httpRequester; private String url = "http://localhost:6565/test/run"; private String filePath; - private static int load = 1; + private static int load = 100; public String getFilePath() { return filePath; @@ -38,7 +38,7 @@ public class TestWithScriptFile { public TestWithScriptFile() { this.setFilePath("scripts" + System.getProperty("file.separator") - + "scriptTimer.xml"); + + "ScriptSuzou.xml"); this.setHttpRequester(new HttpRequester()); } From 79ff480dbedd64163ef09ceb0c8de4d70fdad321 Mon Sep 17 00:00:00 2001 From: Tienan Chen Date: Tue, 26 Nov 2013 19:48:25 +0800 Subject: [PATCH 088/196] add the support of behaviorsBriefModel, to get the behavior's brief info. --- .../org/bench4q/agent/api/TestController.java | 98 +++++++++++-------- .../agent/api/model/BehaviorBriefModel.java | 55 +++++++++++ .../api/model/BehaviorDetailResultModel.java | 16 --- .../model/BehaviorStatusCodeResultModel.java | 69 +++++++++++++ .../api/model/TestBehaviorsBriefModel.java | 24 +++++ .../impl/AgentResultDataCollector.java | 1 + .../impl/DetailStatusCodeResult.java | 1 + 7 files changed, 205 insertions(+), 59 deletions(-) create mode 100644 src/main/java/org/bench4q/agent/api/model/BehaviorBriefModel.java delete mode 100644 src/main/java/org/bench4q/agent/api/model/BehaviorDetailResultModel.java create mode 100644 src/main/java/org/bench4q/agent/api/model/BehaviorStatusCodeResultModel.java create mode 100644 src/main/java/org/bench4q/agent/api/model/TestBehaviorsBriefModel.java diff --git a/src/main/java/org/bench4q/agent/api/TestController.java b/src/main/java/org/bench4q/agent/api/TestController.java index cfc775d7..6f91db74 100644 --- a/src/main/java/org/bench4q/agent/api/TestController.java +++ b/src/main/java/org/bench4q/agent/api/TestController.java @@ -4,6 +4,7 @@ import java.io.ByteArrayOutputStream; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.List; +import java.util.Map; import java.util.UUID; import javax.xml.bind.JAXBContext; @@ -12,16 +13,17 @@ import javax.xml.bind.Marshaller; import org.apache.log4j.Logger; import org.bench4q.agent.api.model.AgentBriefStatusModel; +import org.bench4q.agent.api.model.BehaviorBriefModel; import org.bench4q.agent.api.model.CleanTestResultModel; +import org.bench4q.agent.api.model.BehaviorStatusCodeResultModel; import org.bench4q.agent.api.model.ParameterModel; import org.bench4q.agent.api.model.RunScenarioModel; import org.bench4q.agent.api.model.RunScenarioResultModel; import org.bench4q.agent.api.model.StopTestModel; -import org.bench4q.agent.api.model.TestDetailModel; -import org.bench4q.agent.api.model.TestDetailStatusModel; +import org.bench4q.agent.api.model.TestBehaviorsBriefModel; import org.bench4q.agent.api.model.UsePluginModel; import org.bench4q.agent.api.model.behavior.BehaviorBaseModel; -import org.bench4q.agent.scenario.BehaviorResult; +import org.bench4q.agent.datacollector.impl.DetailStatusCodeResult; import org.bench4q.agent.scenario.Parameter; import org.bench4q.agent.scenario.Scenario; import org.bench4q.agent.scenario.ScenarioContext; @@ -161,55 +163,65 @@ public class TestController { return parameter; } - @RequestMapping(value = "/detail/{runId}", method = RequestMethod.GET) + @RequestMapping(value = "/testBehaviorsBrief/{runId}") @ResponseBody - public TestDetailStatusModel detail(@PathVariable UUID runId) { + public TestBehaviorsBriefModel testBehaviorBriefs(@PathVariable UUID runId) { + TestBehaviorsBriefModel ret = new TestBehaviorsBriefModel(); + List behaviorBriefModels = new ArrayList(); + ScenarioContext scenarioContext = this.getScenarioEngine() + .getRunningTests().get(runId); + if (scenarioContext == null || scenarioContext.isFinished()) { + return null; + } + for (Behavior behavior : scenarioContext.getScenario().getBehaviors()) { + int behaviorId = behavior.getId(); + Map map = scenarioContext + .getDataStatistics().getDetailStatistics(behaviorId); + behaviorBriefModels.add(buildBehaviorBrief(runId, behaviorId, map)); + } + ret.setBehaviorBriefModels(behaviorBriefModels); + return ret; + } + + @RequestMapping(value = "/behaviorBrief/{runId}/{behaviorId}", method = RequestMethod.GET) + @ResponseBody + public BehaviorBriefModel behaviorBrief(@PathVariable UUID runId, + @PathVariable int behaviorId) { ScenarioContext scenarioContext = this.getScenarioEngine() .getRunningTests().get(runId); if (scenarioContext == null) { return null; } - return buildTestDetailStatusModel(scenarioContext); + Map map = scenarioContext + .getDataStatistics().getDetailStatistics(behaviorId); + return buildBehaviorBrief(runId, behaviorId, map); } - private TestDetailStatusModel buildTestDetailStatusModel( - ScenarioContext scenarioContext) { - TestDetailStatusModel testStatusModel = new TestDetailStatusModel(); - testStatusModel.setStartDate(scenarioContext.getStartDate()); - testStatusModel.setTestDetailModels(new ArrayList()); - int failCount = 0; - int successCount = 0; - List behaviorResults = new ArrayList( - scenarioContext.getResults()); - long maxDate = 0; - long totalResponseTime = 0; - int validCount = 0; - for (BehaviorResult behaviorResult : behaviorResults) { - TestDetailModel testDetailModel = new TestDetailModel( - behaviorResult); - testStatusModel.getTestDetailModels().add(testDetailModel); - if (testDetailModel.getEndDate().getTime() > maxDate) { - maxDate = testDetailModel.getEndDate().getTime(); - } - if (testDetailModel.isSuccess()) { - successCount++; - } else { - failCount++; - } - if (!behaviorResult.getPluginName().contains("Timer")) { - totalResponseTime += behaviorResult.getResponseTime(); - validCount++; - } + private BehaviorBriefModel buildBehaviorBrief(UUID runId, int behaviorId, + Map map) { + List detailStatusCodeResultModels = new ArrayList(); + for (int statusCode : map.keySet()) { + BehaviorStatusCodeResultModel behaviorStatusCodeResultModel = new BehaviorStatusCodeResultModel(); + DetailStatusCodeResult detailStatusCodeResult = map.get(statusCode); + behaviorStatusCodeResultModel.setStatusCode(statusCode); + behaviorStatusCodeResultModel + .setCount(detailStatusCodeResult.count); + behaviorStatusCodeResultModel + .setContentLength(detailStatusCodeResult.contentLength); + behaviorStatusCodeResultModel + .setMinResponseTime(detailStatusCodeResult.minResponseTime); + behaviorStatusCodeResultModel + .setMaxResponseTime(detailStatusCodeResult.maxResponseTime); + behaviorStatusCodeResultModel + .setContentType(detailStatusCodeResult.contentType); + detailStatusCodeResultModels.add(behaviorStatusCodeResultModel); } - testStatusModel.setAverageResponseTime((totalResponseTime + 0.0) - / validCount); - testStatusModel.setElapsedTime(maxDate - - testStatusModel.getStartDate().getTime()); - testStatusModel.setFailCount(failCount); - testStatusModel.setSuccessCount(successCount); - testStatusModel.setFinishedCount(testStatusModel.getTestDetailModels() - .size()); - return testStatusModel; + BehaviorBriefModel behaviorBriefModel = new BehaviorBriefModel(); + behaviorBriefModel.setBehaviorId(behaviorId); + behaviorBriefModel + .setDetailStatusCodeResultModels(detailStatusCodeResultModels); + behaviorBriefModel.setTestId(runId); + return behaviorBriefModel; } @RequestMapping(value = "/brief/{runId}", method = RequestMethod.GET) diff --git a/src/main/java/org/bench4q/agent/api/model/BehaviorBriefModel.java b/src/main/java/org/bench4q/agent/api/model/BehaviorBriefModel.java new file mode 100644 index 00000000..94669aac --- /dev/null +++ b/src/main/java/org/bench4q/agent/api/model/BehaviorBriefModel.java @@ -0,0 +1,55 @@ +package org.bench4q.agent.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 = "BehaviorBriefModel") +public class BehaviorBriefModel { + private UUID testId; + private int behaviorId; + private int behaviorUrl; + private List detailStatusCodeResultModels; + + @XmlElement + public UUID getTestId() { + return testId; + } + + public void setTestId(UUID testId) { + this.testId = testId; + } + + @XmlElement + public int getBehaviorId() { + return behaviorId; + } + + public void setBehaviorId(int behaviorId) { + this.behaviorId = behaviorId; + } + + @XmlElement + public int getBehaviorUrl() { + return behaviorUrl; + } + + public void setBehaviorUrl(int behaviorUrl) { + this.behaviorUrl = behaviorUrl; + } + + @XmlElementWrapper(name = "detailStatusCodeResultList") + @XmlElement(name = "detailStatusCodeResult") + public List getDetailStatusCodeResultModels() { + return detailStatusCodeResultModels; + } + + public void setDetailStatusCodeResultModels( + List detailStatusCodeResultModels) { + this.detailStatusCodeResultModels = detailStatusCodeResultModels; + } + +} diff --git a/src/main/java/org/bench4q/agent/api/model/BehaviorDetailResultModel.java b/src/main/java/org/bench4q/agent/api/model/BehaviorDetailResultModel.java deleted file mode 100644 index 4ab90b18..00000000 --- a/src/main/java/org/bench4q/agent/api/model/BehaviorDetailResultModel.java +++ /dev/null @@ -1,16 +0,0 @@ -package org.bench4q.agent.api.model; - -public class BehaviorDetailResultModel { - private int behaviorId; - - // private List<> - - public int getBehaviorId() { - return behaviorId; - } - - public void setBehaviorId(int behaviorId) { - this.behaviorId = behaviorId; - } - -} diff --git a/src/main/java/org/bench4q/agent/api/model/BehaviorStatusCodeResultModel.java b/src/main/java/org/bench4q/agent/api/model/BehaviorStatusCodeResultModel.java new file mode 100644 index 00000000..e7e5aa41 --- /dev/null +++ b/src/main/java/org/bench4q/agent/api/model/BehaviorStatusCodeResultModel.java @@ -0,0 +1,69 @@ +package org.bench4q.agent.api.model; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; + +@XmlRootElement(name = "BehaviorStatusCodeResultModel") +public class BehaviorStatusCodeResultModel { + private int statusCode; + private long count; + private String contentType; + private long contentLength; + private long minResponseTime; + private long maxResponseTime; + + @XmlElement + public int getStatusCode() { + return statusCode; + } + + public void setStatusCode(int statusCode) { + this.statusCode = statusCode; + } + + @XmlElement + public long getCount() { + return count; + } + + public void setCount(long count) { + this.count = count; + } + + @XmlElement + public String getContentType() { + return contentType; + } + + public void setContentType(String contentType) { + this.contentType = contentType; + } + + @XmlElement + public long getContentLength() { + return contentLength; + } + + public void setContentLength(long contentLength) { + this.contentLength = contentLength; + } + + @XmlElement + public long getMinResponseTime() { + return minResponseTime; + } + + public void setMinResponseTime(long minResponseTime) { + this.minResponseTime = minResponseTime; + } + + @XmlElement + public long getMaxResponseTime() { + return maxResponseTime; + } + + public void setMaxResponseTime(long maxResponseTime) { + this.maxResponseTime = maxResponseTime; + } + +} diff --git a/src/main/java/org/bench4q/agent/api/model/TestBehaviorsBriefModel.java b/src/main/java/org/bench4q/agent/api/model/TestBehaviorsBriefModel.java new file mode 100644 index 00000000..d82c7f11 --- /dev/null +++ b/src/main/java/org/bench4q/agent/api/model/TestBehaviorsBriefModel.java @@ -0,0 +1,24 @@ +package org.bench4q.agent.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 = "testBehaviorBriefModel") +public class TestBehaviorsBriefModel { + private List behaviorBriefModels; + + @XmlElementWrapper(name = "behaviorBriefList") + @XmlElement(name = "behaviorBrief") + public List getBehaviorBriefModels() { + return behaviorBriefModels; + } + + public void setBehaviorBriefModels( + List behaviorBriefModels) { + this.behaviorBriefModels = behaviorBriefModels; + } + +} diff --git a/src/main/java/org/bench4q/agent/datacollector/impl/AgentResultDataCollector.java b/src/main/java/org/bench4q/agent/datacollector/impl/AgentResultDataCollector.java index f47ef0aa..77a19cea 100644 --- a/src/main/java/org/bench4q/agent/datacollector/impl/AgentResultDataCollector.java +++ b/src/main/java/org/bench4q/agent/datacollector/impl/AgentResultDataCollector.java @@ -212,6 +212,7 @@ public class AgentResultDataCollector extends AbstractDataCollector { detailResult.contentLength = 0; return; } + detailResult.contentType = behaviorResult.getContentType(); detailResult.contentLength += behaviorResult.getContentLength(); if (behaviorResult.getResponseTime() > detailResult.maxResponseTime) { detailResult.maxResponseTime = behaviorResult.getResponseTime(); diff --git a/src/main/java/org/bench4q/agent/datacollector/impl/DetailStatusCodeResult.java b/src/main/java/org/bench4q/agent/datacollector/impl/DetailStatusCodeResult.java index 0f11679a..3f23ce4e 100644 --- a/src/main/java/org/bench4q/agent/datacollector/impl/DetailStatusCodeResult.java +++ b/src/main/java/org/bench4q/agent/datacollector/impl/DetailStatusCodeResult.java @@ -7,6 +7,7 @@ public class DetailStatusCodeResult { public long contentLength; public long minResponseTime; public long maxResponseTime; + public String contentType; public DetailStatusCodeResult() { this.count = 0; From 0ef5e36e20e17a6724dcd1ce14ee9565112a9c59 Mon Sep 17 00:00:00 2001 From: Tienan Chen Date: Tue, 26 Nov 2013 20:42:24 +0800 Subject: [PATCH 089/196] really store the behaviorResult --- .../agent/api/model/BehaviorResultModel.java | 159 ++++++++++++++++++ .../impl/AbstractDataCollector.java | 44 ++++- .../impl/AgentResultDataCollector.java | 7 +- .../agent/scenario/BehaviorResult.java | 10 -- .../agent/scenario/ScenarioEngine.java | 1 - .../bench4q/agent/storage/LocalStorage.java | 2 +- .../agent/test/DataStatisticsTest.java | 1 - 7 files changed, 198 insertions(+), 26 deletions(-) create mode 100644 src/main/java/org/bench4q/agent/api/model/BehaviorResultModel.java diff --git a/src/main/java/org/bench4q/agent/api/model/BehaviorResultModel.java b/src/main/java/org/bench4q/agent/api/model/BehaviorResultModel.java new file mode 100644 index 00000000..5d327399 --- /dev/null +++ b/src/main/java/org/bench4q/agent/api/model/BehaviorResultModel.java @@ -0,0 +1,159 @@ +package org.bench4q.agent.api.model; + +import java.io.ByteArrayOutputStream; +import java.util.Date; +import java.util.UUID; + +import javax.xml.bind.JAXBContext; +import javax.xml.bind.JAXBException; +import javax.xml.bind.Marshaller; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; + +@XmlRootElement(name = "behaviorResultModel") +public class BehaviorResultModel { + private UUID id; + private String pluginId; + private String pluginName; + private String behaviorName; + private Date startDate; + private Date endDate; + private long responseTime; + private boolean success; + private int behaviorId; + private long contentLength; + private int statusCode; + private String contentType; + private boolean shouldBeCountResponseTime; + + @XmlElement + public UUID getId() { + return id; + } + + public void setId(UUID id) { + this.id = id; + } + + @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; + } + + @XmlElement + public int getBehaviorId() { + return behaviorId; + } + + public void setBehaviorId(int behaviorId) { + this.behaviorId = behaviorId; + } + + @XmlElement + public long getContentLength() { + return contentLength; + } + + public void setContentLength(long contentLength) { + this.contentLength = contentLength; + } + + @XmlElement + public int getStatusCode() { + return statusCode; + } + + public void setStatusCode(int statusCode) { + this.statusCode = statusCode; + } + + @XmlElement + public String getContentType() { + return contentType; + } + + public void setContentType(String contentType) { + this.contentType = contentType; + } + + @XmlElement + public boolean isShouldBeCountResponseTime() { + return shouldBeCountResponseTime; + } + + public void setShouldBeCountResponseTime(boolean shouldBeCountResponseTime) { + this.shouldBeCountResponseTime = shouldBeCountResponseTime; + } + + public String getModelString() { + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + Marshaller marshaller; + try { + marshaller = JAXBContext.newInstance(BehaviorResultModel.class) + .createMarshaller(); + marshaller.marshal(this, outputStream); + return outputStream.toString(); + } catch (JAXBException e) { + return ""; + } + + } +} diff --git a/src/main/java/org/bench4q/agent/datacollector/impl/AbstractDataCollector.java b/src/main/java/org/bench4q/agent/datacollector/impl/AbstractDataCollector.java index 6cbedb9b..e7b6f863 100644 --- a/src/main/java/org/bench4q/agent/datacollector/impl/AbstractDataCollector.java +++ b/src/main/java/org/bench4q/agent/datacollector/impl/AbstractDataCollector.java @@ -3,8 +3,11 @@ package org.bench4q.agent.datacollector.impl; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.Map; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; import org.apache.log4j.Logger; +import org.bench4q.agent.api.model.BehaviorResultModel; import org.bench4q.agent.datacollector.interfaces.DataStatistics; import org.bench4q.agent.helper.ApplicationContextHelper; import org.bench4q.agent.scenario.BehaviorResult; @@ -40,17 +43,40 @@ public abstract class AbstractDataCollector implements DataStatistics { } } - // public void add(List behaviorResults) { - // } - - public void add(BehaviorResult behaviorResult) { - // TestDetailModel testDetailModel = new TestDetailModel( - // behaviorResult); - // this.getStorageHelper().getLocalStorage() - // .writeFile(testDetailModel.getModelString(), getSavePath()); + public void add(final BehaviorResult behaviorResult) { + Runnable runnable = new Runnable() { + public void run() { + storageHelper.getLocalStorage().writeFile( + buildBehaviorResultModel(behaviorResult) + .getModelString(), + calculateSavePath(behaviorResult)); + } + }; + ExecutorService executorService = Executors.newCachedThreadPool(); + executorService.execute(runnable); + executorService.shutdown(); } - protected abstract String getSavePath(); + private BehaviorResultModel buildBehaviorResultModel( + BehaviorResult behaviorResult) { + BehaviorResultModel resultModel = new BehaviorResultModel(); + resultModel.setBehaviorId(behaviorResult.getBehaviorId()); + resultModel.setBehaviorName(behaviorResult.getBehaviorName()); + resultModel.setContentLength(behaviorResult.getContentLength()); + resultModel.setContentType(behaviorResult.getContentType()); + resultModel.setEndDate(behaviorResult.getEndDate()); + resultModel.setPluginId(behaviorResult.getPluginId()); + resultModel.setPluginName(behaviorResult.getPluginName()); + resultModel.setResponseTime(behaviorResult.getResponseTime()); + resultModel.setShouldBeCountResponseTime(behaviorResult + .isShouldBeCountResponseTime()); + resultModel.setStartDate(behaviorResult.getStartDate()); + resultModel.setStatusCode(behaviorResult.getStatusCode()); + resultModel.setSuccess(behaviorResult.isSuccess()); + return resultModel; + } + + protected abstract String calculateSavePath(BehaviorResult behaviorResult); public abstract Object getBriefStatistics(); diff --git a/src/main/java/org/bench4q/agent/datacollector/impl/AgentResultDataCollector.java b/src/main/java/org/bench4q/agent/datacollector/impl/AgentResultDataCollector.java index 77a19cea..28ecae55 100644 --- a/src/main/java/org/bench4q/agent/datacollector/impl/AgentResultDataCollector.java +++ b/src/main/java/org/bench4q/agent/datacollector/impl/AgentResultDataCollector.java @@ -224,17 +224,16 @@ public class AgentResultDataCollector extends AbstractDataCollector { @Override public void add(BehaviorResult behaviorResult) { - // TODO Auto-generated method stub super.add(behaviorResult); addItem(behaviorResult); } @Override - protected String getSavePath() { + protected String calculateSavePath(BehaviorResult behaviorResult) { return "DetailResults" + System.getProperty("file.separator") + new SimpleDateFormat("yyyyMMdd").format(new Date()) - + System.getProperty("file.separator") + this.getTestID() - + ".txt"; + + System.getProperty("file.separator") + this.getTestID() + "_" + + behaviorResult.getBehaviorId() + ".txt"; } @Override diff --git a/src/main/java/org/bench4q/agent/scenario/BehaviorResult.java b/src/main/java/org/bench4q/agent/scenario/BehaviorResult.java index 6522c1cf..1a2ef304 100644 --- a/src/main/java/org/bench4q/agent/scenario/BehaviorResult.java +++ b/src/main/java/org/bench4q/agent/scenario/BehaviorResult.java @@ -1,10 +1,8 @@ package org.bench4q.agent.scenario; import java.util.Date; -import java.util.UUID; public class BehaviorResult { - private UUID id; private String pluginId; private String pluginName; private String behaviorName; @@ -18,14 +16,6 @@ public class BehaviorResult { private String contentType; private boolean shouldBeCountResponseTime; - public UUID getId() { - return id; - } - - public void setId(UUID id) { - this.id = id; - } - public String getPluginId() { return pluginId; } diff --git a/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java b/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java index 76e8ec43..f3f452d9 100644 --- a/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java +++ b/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java @@ -113,7 +113,6 @@ public class ScenarioEngine { Object plugin, Date startDate, PluginReturn pluginReturn, Date endDate) { BehaviorResult result = new BehaviorResult(); - result.setId(UUID.randomUUID()); result.setStartDate(startDate); result.setEndDate(endDate); result.setSuccess(pluginReturn.isSuccess()); diff --git a/src/main/java/org/bench4q/agent/storage/LocalStorage.java b/src/main/java/org/bench4q/agent/storage/LocalStorage.java index 9eecafb7..6eb1b2da 100644 --- a/src/main/java/org/bench4q/agent/storage/LocalStorage.java +++ b/src/main/java/org/bench4q/agent/storage/LocalStorage.java @@ -37,7 +37,7 @@ public class LocalStorage implements Storage { file.mkdirs(); } OutputStreamWriter outputStreamWriter = new OutputStreamWriter( - new FileOutputStream(new File(path)), "UTF-8"); + new FileOutputStream(new File(path), true), "UTF-8"); outputStreamWriter.write(content); outputStreamWriter.flush(); outputStreamWriter.close(); diff --git a/src/test/java/org/bench4q/agent/test/DataStatisticsTest.java b/src/test/java/org/bench4q/agent/test/DataStatisticsTest.java index 3c15d84c..4de540cd 100644 --- a/src/test/java/org/bench4q/agent/test/DataStatisticsTest.java +++ b/src/test/java/org/bench4q/agent/test/DataStatisticsTest.java @@ -146,7 +146,6 @@ public class DataStatisticsTest { BehaviorResult result = new BehaviorResult(); result.setBehaviorName(""); result.setEndDate(new Date(date.getTime() + responseTime)); - result.setId(UUID.randomUUID()); result.setPluginId("Get"); result.setPluginName("get"); result.setResponseTime(responseTime); From 9cdaf9462e2a3a6e1b3508ba78f6e9b0145049d0 Mon Sep 17 00:00:00 2001 From: Tienan Chen Date: Wed, 27 Nov 2013 09:24:50 +0800 Subject: [PATCH 090/196] remove the behaviorsBrief bug --- src/main/java/org/bench4q/agent/api/TestController.java | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/bench4q/agent/api/TestController.java b/src/main/java/org/bench4q/agent/api/TestController.java index 6f91db74..8dcd179a 100644 --- a/src/main/java/org/bench4q/agent/api/TestController.java +++ b/src/main/java/org/bench4q/agent/api/TestController.java @@ -163,7 +163,7 @@ public class TestController { return parameter; } - @RequestMapping(value = "/testBehaviorsBrief/{runId}") + @RequestMapping(value = "/behaviorsBrief/{runId}") @ResponseBody public TestBehaviorsBriefModel testBehaviorBriefs(@PathVariable UUID runId) { TestBehaviorsBriefModel ret = new TestBehaviorsBriefModel(); @@ -177,13 +177,16 @@ public class TestController { int behaviorId = behavior.getId(); Map map = scenarioContext .getDataStatistics().getDetailStatistics(behaviorId); + if (map == null) { + continue; + } behaviorBriefModels.add(buildBehaviorBrief(runId, behaviorId, map)); } ret.setBehaviorBriefModels(behaviorBriefModels); return ret; } - @RequestMapping(value = "/behaviorBrief/{runId}/{behaviorId}", method = RequestMethod.GET) + @RequestMapping(value = "/brief/{runId}/{behaviorId}", method = RequestMethod.GET) @ResponseBody public BehaviorBriefModel behaviorBrief(@PathVariable UUID runId, @PathVariable int behaviorId) { From c32e58c19d5e4d7e136fb81db5ad7c46244bd855 Mon Sep 17 00:00:00 2001 From: Tienan Chen Date: Wed, 27 Nov 2013 09:40:07 +0800 Subject: [PATCH 091/196] refactor for behaviorsBrief --- .../org/bench4q/agent/api/TestController.java | 1 - .../agent/api/model/BehaviorBriefModel.java | 18 +++---------- .../impl/AgentResultDataCollector.java | 27 ++++++++++--------- .../impl/DetailStatusCodeResult.java | 3 ++- .../agent/test/DetailStatisticsTest.java | 4 +-- 5 files changed, 21 insertions(+), 32 deletions(-) diff --git a/src/main/java/org/bench4q/agent/api/TestController.java b/src/main/java/org/bench4q/agent/api/TestController.java index 8dcd179a..67efd25b 100644 --- a/src/main/java/org/bench4q/agent/api/TestController.java +++ b/src/main/java/org/bench4q/agent/api/TestController.java @@ -223,7 +223,6 @@ public class TestController { behaviorBriefModel.setBehaviorId(behaviorId); behaviorBriefModel .setDetailStatusCodeResultModels(detailStatusCodeResultModels); - behaviorBriefModel.setTestId(runId); return behaviorBriefModel; } diff --git a/src/main/java/org/bench4q/agent/api/model/BehaviorBriefModel.java b/src/main/java/org/bench4q/agent/api/model/BehaviorBriefModel.java index 94669aac..cd6a0d17 100644 --- a/src/main/java/org/bench4q/agent/api/model/BehaviorBriefModel.java +++ b/src/main/java/org/bench4q/agent/api/model/BehaviorBriefModel.java @@ -1,28 +1,16 @@ package org.bench4q.agent.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 = "BehaviorBriefModel") public class BehaviorBriefModel { - private UUID testId; private int behaviorId; - private int behaviorUrl; + private String behaviorUrl; private List detailStatusCodeResultModels; - @XmlElement - public UUID getTestId() { - return testId; - } - - public void setTestId(UUID testId) { - this.testId = testId; - } - @XmlElement public int getBehaviorId() { return behaviorId; @@ -33,11 +21,11 @@ public class BehaviorBriefModel { } @XmlElement - public int getBehaviorUrl() { + public String getBehaviorUrl() { return behaviorUrl; } - public void setBehaviorUrl(int behaviorUrl) { + public void setBehaviorUrl(String behaviorUrl) { this.behaviorUrl = behaviorUrl; } diff --git a/src/main/java/org/bench4q/agent/datacollector/impl/AgentResultDataCollector.java b/src/main/java/org/bench4q/agent/datacollector/impl/AgentResultDataCollector.java index 28ecae55..341d7ca6 100644 --- a/src/main/java/org/bench4q/agent/datacollector/impl/AgentResultDataCollector.java +++ b/src/main/java/org/bench4q/agent/datacollector/impl/AgentResultDataCollector.java @@ -84,14 +84,10 @@ public class AgentResultDataCollector extends AbstractDataCollector { return testID == null ? "default" : testID.toString(); } - public void setTestID(UUID testID) { + private void setTestID(UUID testID) { this.testID = testID; } - public Map> getDetailMap() { - return detailMap; - } - private void setDetailMap( Map> detailMap) { this.detailMap = detailMap; @@ -103,7 +99,7 @@ public class AgentResultDataCollector extends AbstractDataCollector { init(); } - public void init() { + private void init() { reset(); this.setCumulativeFailCount(0); this.setCumulativeSucessfulCount(0); @@ -191,16 +187,15 @@ public class AgentResultDataCollector extends AbstractDataCollector { } private void dealWithDetailResult(BehaviorResult behaviorResult) { - if (!this.detailMap.containsKey(behaviorResult.getBehaviorId())) { - this.detailMap.put(new Integer(behaviorResult.getBehaviorId()), - new HashMap()); - } + insertWhenNotExist(behaviorResult); Map detailStatusMap = this.detailMap .get(behaviorResult.getBehaviorId()); if (!detailStatusMap.containsKey(behaviorResult.getStatusCode())) { - detailStatusMap.put(new Integer(behaviorResult.getStatusCode()), - new DetailStatusCodeResult()); + detailStatusMap + .put(new Integer(behaviorResult.getStatusCode()), + new DetailStatusCodeResult(behaviorResult + .getContentType())); } DetailStatusCodeResult detailResult = detailStatusMap @@ -212,7 +207,6 @@ public class AgentResultDataCollector extends AbstractDataCollector { detailResult.contentLength = 0; return; } - detailResult.contentType = behaviorResult.getContentType(); detailResult.contentLength += behaviorResult.getContentLength(); if (behaviorResult.getResponseTime() > detailResult.maxResponseTime) { detailResult.maxResponseTime = behaviorResult.getResponseTime(); @@ -222,6 +216,13 @@ public class AgentResultDataCollector extends AbstractDataCollector { } } + private void insertWhenNotExist(BehaviorResult behaviorResult) { + if (!this.detailMap.containsKey(behaviorResult.getBehaviorId())) { + this.detailMap.put(new Integer(behaviorResult.getBehaviorId()), + new HashMap()); + } + } + @Override public void add(BehaviorResult behaviorResult) { super.add(behaviorResult); diff --git a/src/main/java/org/bench4q/agent/datacollector/impl/DetailStatusCodeResult.java b/src/main/java/org/bench4q/agent/datacollector/impl/DetailStatusCodeResult.java index 3f23ce4e..7fda6d77 100644 --- a/src/main/java/org/bench4q/agent/datacollector/impl/DetailStatusCodeResult.java +++ b/src/main/java/org/bench4q/agent/datacollector/impl/DetailStatusCodeResult.java @@ -9,7 +9,8 @@ public class DetailStatusCodeResult { public long maxResponseTime; public String contentType; - public DetailStatusCodeResult() { + public DetailStatusCodeResult(String contentType) { + this.contentType = contentType; this.count = 0; this.contentLength = 0; this.minResponseTime = Long.MAX_VALUE; diff --git a/src/test/java/org/bench4q/agent/test/DetailStatisticsTest.java b/src/test/java/org/bench4q/agent/test/DetailStatisticsTest.java index 314c1533..d414d46f 100644 --- a/src/test/java/org/bench4q/agent/test/DetailStatisticsTest.java +++ b/src/test/java/org/bench4q/agent/test/DetailStatisticsTest.java @@ -66,7 +66,7 @@ public class DetailStatisticsTest { } private DetailStatusCodeResult makeExpectedResultForOne() { - DetailStatusCodeResult ret = new DetailStatusCodeResult(); + DetailStatusCodeResult ret = new DetailStatusCodeResult(""); ret.contentLength = 20; ret.count = 1; ret.maxResponseTime = 200; @@ -95,7 +95,7 @@ public class DetailStatisticsTest { private DetailStatusCodeResult buildCodeResult(long contentLength, long count, long maxResponseTime, long minResponseTime) { - DetailStatusCodeResult ret = new DetailStatusCodeResult(); + DetailStatusCodeResult ret = new DetailStatusCodeResult(""); ret.contentLength = contentLength; ret.count = count; ret.maxResponseTime = maxResponseTime; From 275da0f97aee16fd3f89a0bdd699fc1b01b4cf48 Mon Sep 17 00:00:00 2001 From: Tienan Chen Date: Wed, 27 Nov 2013 09:47:11 +0800 Subject: [PATCH 092/196] refactor --- .../org/bench4q/agent/api/TestController.java | 3 ++- .../agent/scenario/ScenarioContext.java | 22 ++++++++----------- 2 files changed, 11 insertions(+), 14 deletions(-) diff --git a/src/main/java/org/bench4q/agent/api/TestController.java b/src/main/java/org/bench4q/agent/api/TestController.java index 67efd25b..31b88308 100644 --- a/src/main/java/org/bench4q/agent/api/TestController.java +++ b/src/main/java/org/bench4q/agent/api/TestController.java @@ -3,6 +3,7 @@ package org.bench4q.agent.api; import java.io.ByteArrayOutputStream; import java.net.UnknownHostException; import java.util.ArrayList; +import java.util.Date; import java.util.List; import java.util.Map; import java.util.UUID; @@ -248,9 +249,9 @@ public class TestController { if (scenarioContext == null) { return null; } + scenarioContext.setEndDate(new Date(System.currentTimeMillis())); scenarioContext.getExecutorService().shutdownNow(); scenarioContext.setFinished(true); - StopTestModel stopTestModel = new StopTestModel(); stopTestModel.setSuccess(true); return stopTestModel; diff --git a/src/main/java/org/bench4q/agent/scenario/ScenarioContext.java b/src/main/java/org/bench4q/agent/scenario/ScenarioContext.java index 1cf8a2b2..1e407e10 100644 --- a/src/main/java/org/bench4q/agent/scenario/ScenarioContext.java +++ b/src/main/java/org/bench4q/agent/scenario/ScenarioContext.java @@ -1,7 +1,6 @@ package org.bench4q.agent.scenario; import java.util.Date; -import java.util.List; import java.util.UUID; import java.util.concurrent.ExecutorService; @@ -10,9 +9,9 @@ import org.bench4q.agent.datacollector.interfaces.DataStatistics; public class ScenarioContext { private Date startDate; + private Date endDate; private ExecutorService executorService; private Scenario scenario; - private List results; private boolean finished; private DataStatistics dataStatistics; @@ -24,6 +23,14 @@ public class ScenarioContext { this.startDate = saveStartDate; } + public Date getEndDate() { + return endDate; + } + + public void setEndDate(Date endDate) { + this.endDate = endDate; + } + public ExecutorService getExecutorService() { return executorService; } @@ -40,14 +47,6 @@ public class ScenarioContext { this.scenario = scenario; } - public List getResults() { - return results; - } - - public void setResults(List results) { - this.results = results; - } - public boolean isFinished() { return finished; } @@ -64,9 +63,6 @@ public class ScenarioContext { this.dataStatistics = dataStatistics; } - private ScenarioContext() { - } - public static ScenarioContext buildScenarioContext(UUID testId, final Scenario scenario, int poolSize, ExecutorService executorService) { From 7aa7926100768f391366822bbc592d40a3b8f1a5 Mon Sep 17 00:00:00 2001 From: Tienan Chen Date: Fri, 29 Nov 2013 09:56:15 +0800 Subject: [PATCH 093/196] remove redundant code --- .../agent/api/model/TestDetailModel.java | 113 ------------------ .../api/model/TestDetailStatusModel.java | 94 --------------- 2 files changed, 207 deletions(-) delete mode 100644 src/main/java/org/bench4q/agent/api/model/TestDetailModel.java delete mode 100644 src/main/java/org/bench4q/agent/api/model/TestDetailStatusModel.java diff --git a/src/main/java/org/bench4q/agent/api/model/TestDetailModel.java b/src/main/java/org/bench4q/agent/api/model/TestDetailModel.java deleted file mode 100644 index 3ece7270..00000000 --- a/src/main/java/org/bench4q/agent/api/model/TestDetailModel.java +++ /dev/null @@ -1,113 +0,0 @@ -package org.bench4q.agent.api.model; - -import java.io.ByteArrayOutputStream; -import java.util.Date; - -import javax.xml.bind.JAXBContext; -import javax.xml.bind.JAXBException; -import javax.xml.bind.Marshaller; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; - -import org.bench4q.agent.scenario.BehaviorResult; - -@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; - } - - public TestDetailModel() { - } - - public TestDetailModel(BehaviorResult behaviorResult) { - this.setBehaviorName(behaviorResult.getBehaviorName()); - this.setEndDate(behaviorResult.getEndDate()); - this.setPluginId(behaviorResult.getPluginId()); - this.setPluginName(behaviorResult.getPluginName()); - this.setResponseTime(behaviorResult.getResponseTime()); - this.setStartDate(behaviorResult.getStartDate()); - this.setSuccess(behaviorResult.isSuccess()); - } - - public String getModelString() { - ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); - Marshaller marshaller; - try { - marshaller = JAXBContext.newInstance(TestDetailModel.class) - .createMarshaller(); - marshaller.marshal(this, outputStream); - return outputStream.toString(); - } catch (JAXBException e) { - e.printStackTrace(); - return ""; - } - } -} diff --git a/src/main/java/org/bench4q/agent/api/model/TestDetailStatusModel.java b/src/main/java/org/bench4q/agent/api/model/TestDetailStatusModel.java deleted file mode 100644 index a94f2225..00000000 --- a/src/main/java/org/bench4q/agent/api/model/TestDetailStatusModel.java +++ /dev/null @@ -1,94 +0,0 @@ -package org.bench4q.agent.api.model; - -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 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 getTestDetailModels() { - return testDetailModels; - } - - public void setTestDetailModels(List testDetailModels) { - this.testDetailModels = testDetailModels; - } - -} From 2ece66cf93513d1640465b64e7d3fb4b2e85602d Mon Sep 17 00:00:00 2001 From: Tienan Chen Date: Mon, 2 Dec 2013 14:25:39 +0800 Subject: [PATCH 094/196] refactor the models with an inheritance system for data statistics --- .../org/bench4q/agent/api/model/AgentBriefStatusModel.java | 2 +- .../org/bench4q/agent/api/model/DataStatisticsModel.java | 5 +++++ .../org/bench4q/agent/api/model/TestBehaviorsBriefModel.java | 2 +- 3 files changed, 7 insertions(+), 2 deletions(-) create mode 100644 src/main/java/org/bench4q/agent/api/model/DataStatisticsModel.java diff --git a/src/main/java/org/bench4q/agent/api/model/AgentBriefStatusModel.java b/src/main/java/org/bench4q/agent/api/model/AgentBriefStatusModel.java index e6140f3e..f3559f4a 100644 --- a/src/main/java/org/bench4q/agent/api/model/AgentBriefStatusModel.java +++ b/src/main/java/org/bench4q/agent/api/model/AgentBriefStatusModel.java @@ -10,7 +10,7 @@ import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement -public class AgentBriefStatusModel { +public class AgentBriefStatusModel extends DataStatisticsModel { private long timeFrame; private long minResponseTime; private long maxResponseTime; diff --git a/src/main/java/org/bench4q/agent/api/model/DataStatisticsModel.java b/src/main/java/org/bench4q/agent/api/model/DataStatisticsModel.java new file mode 100644 index 00000000..302d70eb --- /dev/null +++ b/src/main/java/org/bench4q/agent/api/model/DataStatisticsModel.java @@ -0,0 +1,5 @@ +package org.bench4q.agent.api.model; + +public abstract class DataStatisticsModel { + +} diff --git a/src/main/java/org/bench4q/agent/api/model/TestBehaviorsBriefModel.java b/src/main/java/org/bench4q/agent/api/model/TestBehaviorsBriefModel.java index d82c7f11..e61dc7c2 100644 --- a/src/main/java/org/bench4q/agent/api/model/TestBehaviorsBriefModel.java +++ b/src/main/java/org/bench4q/agent/api/model/TestBehaviorsBriefModel.java @@ -7,7 +7,7 @@ import javax.xml.bind.annotation.XmlElementWrapper; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement(name = "testBehaviorBriefModel") -public class TestBehaviorsBriefModel { +public class TestBehaviorsBriefModel extends DataStatisticsModel { private List behaviorBriefModels; @XmlElementWrapper(name = "behaviorBriefList") From da61bb3317e8b53001e4ce84c2dd4eecdfb640cb Mon Sep 17 00:00:00 2001 From: Tienan Chen Date: Mon, 2 Dec 2013 14:58:44 +0800 Subject: [PATCH 095/196] add totalResponseTime to BehaviorsCodeResultModel --- .../java/org/bench4q/agent/api/TestController.java | 2 ++ .../agent/api/model/BehaviorStatusCodeResultModel.java | 10 ++++++++++ .../datacollector/impl/AgentResultDataCollector.java | 7 +++++-- .../datacollector/impl/DetailStatusCodeResult.java | 2 ++ .../org/bench4q/agent/plugin/basic/HttpPlugin.java | 1 - 5 files changed, 19 insertions(+), 3 deletions(-) diff --git a/src/main/java/org/bench4q/agent/api/TestController.java b/src/main/java/org/bench4q/agent/api/TestController.java index 31b88308..459b3196 100644 --- a/src/main/java/org/bench4q/agent/api/TestController.java +++ b/src/main/java/org/bench4q/agent/api/TestController.java @@ -218,6 +218,8 @@ public class TestController { .setMaxResponseTime(detailStatusCodeResult.maxResponseTime); behaviorStatusCodeResultModel .setContentType(detailStatusCodeResult.contentType); + behaviorStatusCodeResultModel + .setTotalResponseTimeThisTime(detailStatusCodeResult.totalResponseTimeThisTime); detailStatusCodeResultModels.add(behaviorStatusCodeResultModel); } BehaviorBriefModel behaviorBriefModel = new BehaviorBriefModel(); diff --git a/src/main/java/org/bench4q/agent/api/model/BehaviorStatusCodeResultModel.java b/src/main/java/org/bench4q/agent/api/model/BehaviorStatusCodeResultModel.java index e7e5aa41..11d243c8 100644 --- a/src/main/java/org/bench4q/agent/api/model/BehaviorStatusCodeResultModel.java +++ b/src/main/java/org/bench4q/agent/api/model/BehaviorStatusCodeResultModel.java @@ -11,6 +11,7 @@ public class BehaviorStatusCodeResultModel { private long contentLength; private long minResponseTime; private long maxResponseTime; + private long totalResponseTimeThisTime; @XmlElement public int getStatusCode() { @@ -66,4 +67,13 @@ public class BehaviorStatusCodeResultModel { this.maxResponseTime = maxResponseTime; } + @XmlElement + public long getTotalResponseTimeThisTime() { + return totalResponseTimeThisTime; + } + + public void setTotalResponseTimeThisTime(long totalResponseTimeThisTime) { + this.totalResponseTimeThisTime = totalResponseTimeThisTime; + } + } diff --git a/src/main/java/org/bench4q/agent/datacollector/impl/AgentResultDataCollector.java b/src/main/java/org/bench4q/agent/datacollector/impl/AgentResultDataCollector.java index 341d7ca6..42516ab1 100644 --- a/src/main/java/org/bench4q/agent/datacollector/impl/AgentResultDataCollector.java +++ b/src/main/java/org/bench4q/agent/datacollector/impl/AgentResultDataCollector.java @@ -205,9 +205,12 @@ public class AgentResultDataCollector extends AbstractDataCollector { detailResult.maxResponseTime = 0; detailResult.minResponseTime = 0; detailResult.contentLength = 0; + detailResult.totalResponseTimeThisTime = 0; return; } detailResult.contentLength += behaviorResult.getContentLength(); + detailResult.totalResponseTimeThisTime += behaviorResult + .getResponseTime(); if (behaviorResult.getResponseTime() > detailResult.maxResponseTime) { detailResult.maxResponseTime = behaviorResult.getResponseTime(); } @@ -239,10 +242,10 @@ public class AgentResultDataCollector extends AbstractDataCollector { @Override public Map getDetailStatistics(int id) { - if (!this.detailMap.containsKey(new Integer(id))) { + if (!this.detailMap.containsKey(id)) { return null; } - return this.detailMap.get(new Integer(id)); + return this.detailMap.get(id); } } diff --git a/src/main/java/org/bench4q/agent/datacollector/impl/DetailStatusCodeResult.java b/src/main/java/org/bench4q/agent/datacollector/impl/DetailStatusCodeResult.java index 7fda6d77..f17673cf 100644 --- a/src/main/java/org/bench4q/agent/datacollector/impl/DetailStatusCodeResult.java +++ b/src/main/java/org/bench4q/agent/datacollector/impl/DetailStatusCodeResult.java @@ -7,9 +7,11 @@ public class DetailStatusCodeResult { public long contentLength; public long minResponseTime; public long maxResponseTime; + public long totalResponseTimeThisTime; public String contentType; public DetailStatusCodeResult(String contentType) { + this.totalResponseTimeThisTime = 0; this.contentType = contentType; this.count = 0; this.contentLength = 0; diff --git a/src/main/java/org/bench4q/agent/plugin/basic/HttpPlugin.java b/src/main/java/org/bench4q/agent/plugin/basic/HttpPlugin.java index e0527feb..7612dfcb 100644 --- a/src/main/java/org/bench4q/agent/plugin/basic/HttpPlugin.java +++ b/src/main/java/org/bench4q/agent/plugin/basic/HttpPlugin.java @@ -28,7 +28,6 @@ public class HttpPlugin { HttpURLConnection httpURLConnection = null; StringBuffer stringBuffer = null; String requestMethod = "GET"; - try { httpURLConnection = getRequestURLConnection(url, requestMethod); stringBuffer = readConnectionInputStream(httpURLConnection); From 6c1149244095053abce9d94134a84c3ad8a440ae Mon Sep 17 00:00:00 2001 From: Tienan Chen Date: Tue, 3 Dec 2013 14:37:02 +0800 Subject: [PATCH 096/196] start the spring servlet at start up --- src/main/java/org/bench4q/agent/AgentServer.java | 1 + 1 file changed, 1 insertion(+) diff --git a/src/main/java/org/bench4q/agent/AgentServer.java b/src/main/java/org/bench4q/agent/AgentServer.java index bfd0ac52..aaeda1e1 100644 --- a/src/main/java/org/bench4q/agent/AgentServer.java +++ b/src/main/java/org/bench4q/agent/AgentServer.java @@ -43,6 +43,7 @@ public class AgentServer { servletHolder .setInitParameter("contextConfigLocation", "classpath*:/org/bench4q/agent/config/application-context.xml"); + servletHolder.setInitOrder(1); this.getServer().setHandler(servletContextHandler); this.getServer().start(); return true; From 908b8e4bd93ddc9a4ca6a0b34e52f8ec356092e1 Mon Sep 17 00:00:00 2001 From: Tienan Chen Date: Tue, 3 Dec 2013 14:53:08 +0800 Subject: [PATCH 097/196] update jetty version and setInitOrder at start up --- pom.xml | 4 ++-- src/main/java/org/bench4q/agent/AgentServer.java | 7 +------ 2 files changed, 3 insertions(+), 8 deletions(-) diff --git a/pom.xml b/pom.xml index fa33d735..8cce6661 100644 --- a/pom.xml +++ b/pom.xml @@ -20,12 +20,12 @@ org.eclipse.jetty jetty-server - 8.1.11.v20130520 + 9.1.0.RC2 org.eclipse.jetty jetty-servlet - 8.1.11.v20130520 + 9.1.0.RC2 org.springframework diff --git a/src/main/java/org/bench4q/agent/AgentServer.java b/src/main/java/org/bench4q/agent/AgentServer.java index aaeda1e1..0f21e431 100644 --- a/src/main/java/org/bench4q/agent/AgentServer.java +++ b/src/main/java/org/bench4q/agent/AgentServer.java @@ -1,8 +1,6 @@ package org.bench4q.agent; -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.web.servlet.DispatcherServlet; @@ -33,10 +31,7 @@ public class AgentServer { public boolean start() { try { - this.setServer(new Server()); - Connector connector = new SocketConnector(); - connector.setPort(this.getPort()); - this.getServer().addConnector(connector); + this.setServer(new Server(this.getPort())); ServletContextHandler servletContextHandler = new ServletContextHandler(); ServletHolder servletHolder = servletContextHandler.addServlet( DispatcherServlet.class, "/"); From e331259c07edc1a9811a1ff575470f540d4bb20f Mon Sep 17 00:00:00 2001 From: coderfengyun Date: Tue, 10 Dec 2013 17:13:59 +0800 Subject: [PATCH 098/196] add batch behavior and runScenarioModelNew to agent --- .../agent/api/model/BatchBehavior.java | 55 +++++++++++++++++++ .../agent/api/model/RunScenarioModelNew.java | 50 +++++++++++++++++ 2 files changed, 105 insertions(+) create mode 100644 src/main/java/org/bench4q/agent/api/model/BatchBehavior.java create mode 100644 src/main/java/org/bench4q/agent/api/model/RunScenarioModelNew.java diff --git a/src/main/java/org/bench4q/agent/api/model/BatchBehavior.java b/src/main/java/org/bench4q/agent/api/model/BatchBehavior.java new file mode 100644 index 00000000..62a80ec6 --- /dev/null +++ b/src/main/java/org/bench4q/agent/api/model/BatchBehavior.java @@ -0,0 +1,55 @@ +package org.bench4q.agent.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.agent.api.model.behavior.BehaviorBaseModel; + +@XmlRootElement(name = "batch") +public class BatchBehavior { + private int Id; + private int parentId; + private int childId; + private List behaviors; + + @XmlElement + public int getId() { + return Id; + } + + public void setId(int id) { + Id = id; + } + + @XmlElement + public int getParentId() { + return parentId; + } + + public void setParentId(int parentBatchId) { + this.parentId = parentBatchId; + } + + @XmlElement + public int getChildId() { + return childId; + } + + public void setChildId(int childId) { + this.childId = childId; + } + + @XmlElementWrapper(name = "behaviors") + @XmlElement + public List getBehaviors() { + return behaviors; + } + + public void setBehaviors(List behaviors) { + this.behaviors = behaviors; + } + +} diff --git a/src/main/java/org/bench4q/agent/api/model/RunScenarioModelNew.java b/src/main/java/org/bench4q/agent/api/model/RunScenarioModelNew.java new file mode 100644 index 00000000..62e2f7ba --- /dev/null +++ b/src/main/java/org/bench4q/agent/api/model/RunScenarioModelNew.java @@ -0,0 +1,50 @@ +package org.bench4q.agent.api.model; + +import java.util.ArrayList; +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 RunScenarioModelNew { + + private int poolSize; + private List usePlugins; + private List batches; + + @XmlElement + public int getPoolSize() { + return poolSize; + } + + public void setPoolSize(int poolSize) { + this.poolSize = poolSize; + } + + @XmlElementWrapper(name = "usePlugins") + @XmlElement(name = "usePlugin") + public List getUsePlugins() { + return usePlugins; + } + + public void setUsePlugins(List usePlugins) { + this.usePlugins = usePlugins; + } + + @XmlElementWrapper(name = "batches") + @XmlElement + public List getBatches() { + return batches; + } + + public void setBatches(List batches) { + this.batches = batches; + } + + public RunScenarioModelNew() { + this.setBatches(new ArrayList()); + this.setUsePlugins(new ArrayList()); + } +} From 839e1574126dc54c4b0ead58d0f0188887aac236 Mon Sep 17 00:00:00 2001 From: coderfengyun Date: Tue, 10 Dec 2013 19:58:26 +0800 Subject: [PATCH 099/196] add content type to detailresult, and pass the old tests --- .../345376a7-d01c-4faa-af89-4a3e1a182048.xml | 1 + .../org/bench4q/agent/api/TestController.java | 77 ++++++++++++------- ...rioModel.java => RunScenarioModelOld.java} | 2 +- .../agent/api/model/behavior/Batch.java | 43 +++++++++++ .../impl/DetailStatusCodeResult.java | 5 +- .../agent/scenario/ScenarioContext.java | 8 +- .../agent/scenario/ScenarioEngine.java | 33 ++++---- .../bench4q/agent/scenario/ScenarioNew.java | 25 ++++++ .../{Scenario.java => ScenarioOld.java} | 2 +- .../agent/test/DetailStatisticsTest.java | 12 +-- .../agent/test/TestWithScriptFile.java | 14 ++-- 11 files changed, 161 insertions(+), 61 deletions(-) create mode 100644 Scripts/345376a7-d01c-4faa-af89-4a3e1a182048.xml rename src/main/java/org/bench4q/agent/api/model/{RunScenarioModel.java => RunScenarioModelOld.java} (93%) create mode 100644 src/main/java/org/bench4q/agent/api/model/behavior/Batch.java create mode 100644 src/main/java/org/bench4q/agent/scenario/ScenarioNew.java rename src/main/java/org/bench4q/agent/scenario/{Scenario.java => ScenarioOld.java} (89%) diff --git a/Scripts/345376a7-d01c-4faa-af89-4a3e1a182048.xml b/Scripts/345376a7-d01c-4faa-af89-4a3e1a182048.xml new file mode 100644 index 00000000..d65eda6c --- /dev/null +++ b/Scripts/345376a7-d01c-4faa-af89-4a3e1a182048.xml @@ -0,0 +1 @@ +1Geturlhttp://localhost:8080/Bench4QTestCase/testcase.htmlparametershttp-10-10httpHttptimerConstantTimer \ No newline at end of file diff --git a/src/main/java/org/bench4q/agent/api/TestController.java b/src/main/java/org/bench4q/agent/api/TestController.java index 459b3196..76f02f10 100644 --- a/src/main/java/org/bench4q/agent/api/TestController.java +++ b/src/main/java/org/bench4q/agent/api/TestController.java @@ -14,19 +14,22 @@ import javax.xml.bind.Marshaller; import org.apache.log4j.Logger; import org.bench4q.agent.api.model.AgentBriefStatusModel; +import org.bench4q.agent.api.model.BatchBehavior; import org.bench4q.agent.api.model.BehaviorBriefModel; import org.bench4q.agent.api.model.CleanTestResultModel; import org.bench4q.agent.api.model.BehaviorStatusCodeResultModel; import org.bench4q.agent.api.model.ParameterModel; -import org.bench4q.agent.api.model.RunScenarioModel; +import org.bench4q.agent.api.model.RunScenarioModelNew; +import org.bench4q.agent.api.model.RunScenarioModelOld; import org.bench4q.agent.api.model.RunScenarioResultModel; import org.bench4q.agent.api.model.StopTestModel; import org.bench4q.agent.api.model.TestBehaviorsBriefModel; import org.bench4q.agent.api.model.UsePluginModel; +import org.bench4q.agent.api.model.behavior.Batch; import org.bench4q.agent.api.model.behavior.BehaviorBaseModel; import org.bench4q.agent.datacollector.impl.DetailStatusCodeResult; import org.bench4q.agent.scenario.Parameter; -import org.bench4q.agent.scenario.Scenario; +import org.bench4q.agent.scenario.ScenarioNew; import org.bench4q.agent.scenario.ScenarioContext; import org.bench4q.agent.scenario.ScenarioEngine; import org.bench4q.agent.scenario.UsePlugin; @@ -62,9 +65,9 @@ public class TestController { @RequestMapping(value = "/run", method = RequestMethod.POST) @ResponseBody public RunScenarioResultModel run( - @RequestBody RunScenarioModel runScenarioModel) + @RequestBody RunScenarioModelNew runScenarioModel) throws UnknownHostException { - Scenario scenario = extractScenario(runScenarioModel); + ScenarioNew scenario = extractScenario(runScenarioModel); UUID runId = UUID.randomUUID(); System.out.println(runScenarioModel.getPoolSize()); this.getLogger().info(marshalRunScenarioModel(runScenarioModel)); @@ -75,11 +78,11 @@ public class TestController { return runScenarioResultModel; } - private String marshalRunScenarioModel(RunScenarioModel inModel) { + private String marshalRunScenarioModel(RunScenarioModelNew inModel) { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); Marshaller marshaller; try { - marshaller = JAXBContext.newInstance(RunScenarioModel.class) + marshaller = JAXBContext.newInstance(RunScenarioModelOld.class) .createMarshaller(); marshaller.marshal(inModel, outputStream); return outputStream.toString(); @@ -89,31 +92,28 @@ public class TestController { } - private Scenario extractScenario(RunScenarioModel runScenarioModel) { - Scenario scenario = new Scenario(); + private ScenarioNew extractScenario(RunScenarioModelNew runScenarioModel) { + ScenarioNew scenario = new ScenarioNew(); scenario.setUsePlugins(new UsePlugin[runScenarioModel.getUsePlugins() .size()]); - scenario.setBehaviors(new Behavior[runScenarioModel.getBehaviors() - .size()]); + scenario.setBatches(new Batch[runScenarioModel.getBatches().size()]); extractUsePlugins(runScenarioModel, scenario); - extractUserBehaviors(runScenarioModel, scenario); + extractBatches(runScenarioModel, scenario); return scenario; } - private void extractUserBehaviors(RunScenarioModel runScenarioModel, - Scenario scenario) { + private void extractBatches(RunScenarioModelNew runScenarioModel, + ScenarioNew scenario) { int i; - List behaviorBaseModels = runScenarioModel.getBehaviors(); - for (i = 0; i < runScenarioModel.getBehaviors().size(); i++) { - BehaviorBaseModel behaviorModel = (BehaviorBaseModel) behaviorBaseModels - .get(i); - Behavior userBehavior = extractBehavior(behaviorModel); - scenario.getBehaviors()[i] = userBehavior; + List batches = runScenarioModel.getBatches(); + for (i = 0; i < runScenarioModel.getBatches().size(); i++) { + BatchBehavior batch = batches.get(i); + scenario.getBatches()[i] = extractBatch(batch); } } - private void extractUsePlugins(RunScenarioModel runScenarioModel, - Scenario scenario) { + private void extractUsePlugins(RunScenarioModelNew runScenarioModel, + ScenarioNew scenario) { int i; List usePluginModels = runScenarioModel.getUsePlugins(); for (i = 0; i < runScenarioModel.getUsePlugins().size(); i++) { @@ -123,6 +123,23 @@ public class TestController { } } + private Batch extractBatch(BatchBehavior batchModel) { + Batch batch = new Batch(); + batch.setBehaviors(new Behavior[batchModel.getBehaviors().size()]); + batch.setId(batchModel.getId()); + batch.setParentId(batchModel.getParentId()); + batch.setChildId(batchModel.getChildId()); + if (batchModel.getBehaviors() == null) { + return batch; + } + batch.setBehaviors(new Behavior[batchModel.getBehaviors().size()]); + for (int i = 0; i < batchModel.getBehaviors().size(); ++i) { + batch.getBehaviors()[i] = extractBehavior(batchModel.getBehaviors() + .get(i)); + } + return batch; + } + private Behavior extractBehavior(BehaviorBaseModel behaviorModel) { Behavior behavior = BehaviorFactory.getBuisinessObject(behaviorModel); behavior.setName(behaviorModel.getName()); @@ -174,14 +191,18 @@ public class TestController { if (scenarioContext == null || scenarioContext.isFinished()) { return null; } - for (Behavior behavior : scenarioContext.getScenario().getBehaviors()) { - int behaviorId = behavior.getId(); - Map map = scenarioContext - .getDataStatistics().getDetailStatistics(behaviorId); - if (map == null) { - continue; + for (Batch batch : scenarioContext.getScenario().getBatches()) { + for (Behavior behavior : batch.getBehaviors()) { + int behaviorId = behavior.getId(); + Map map = scenarioContext + .getDataStatistics().getDetailStatistics(behaviorId); + if (map == null) { + continue; + } + behaviorBriefModels.add(buildBehaviorBrief(runId, behaviorId, + map)); + } - behaviorBriefModels.add(buildBehaviorBrief(runId, behaviorId, map)); } ret.setBehaviorBriefModels(behaviorBriefModels); return ret; diff --git a/src/main/java/org/bench4q/agent/api/model/RunScenarioModel.java b/src/main/java/org/bench4q/agent/api/model/RunScenarioModelOld.java similarity index 93% rename from src/main/java/org/bench4q/agent/api/model/RunScenarioModel.java rename to src/main/java/org/bench4q/agent/api/model/RunScenarioModelOld.java index 5be0a0f7..1c594387 100644 --- a/src/main/java/org/bench4q/agent/api/model/RunScenarioModel.java +++ b/src/main/java/org/bench4q/agent/api/model/RunScenarioModelOld.java @@ -11,7 +11,7 @@ import org.bench4q.agent.api.model.behavior.TimerBehaviorModel; import org.bench4q.agent.api.model.behavior.UserBehaviorModel; @XmlRootElement(name = "runScenario") -public class RunScenarioModel { +public class RunScenarioModelOld { private int poolSize; private List usePlugins; private List behaviors; diff --git a/src/main/java/org/bench4q/agent/api/model/behavior/Batch.java b/src/main/java/org/bench4q/agent/api/model/behavior/Batch.java new file mode 100644 index 00000000..469c2a0e --- /dev/null +++ b/src/main/java/org/bench4q/agent/api/model/behavior/Batch.java @@ -0,0 +1,43 @@ +package org.bench4q.agent.api.model.behavior; + +import org.bench4q.agent.scenario.behavior.Behavior; + +public class Batch { + private int id; + private int parentId; + private int childId; + private Behavior[] behaviors; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public int getParentId() { + return parentId; + } + + public void setParentId(int parentId) { + this.parentId = parentId; + } + + public int getChildId() { + return childId; + } + + public void setChildId(int childId) { + this.childId = childId; + } + + public Behavior[] getBehaviors() { + return behaviors; + } + + public void setBehaviors(Behavior[] behaviors) { + this.behaviors = behaviors; + } + +} diff --git a/src/main/java/org/bench4q/agent/datacollector/impl/DetailStatusCodeResult.java b/src/main/java/org/bench4q/agent/datacollector/impl/DetailStatusCodeResult.java index f17673cf..759964f6 100644 --- a/src/main/java/org/bench4q/agent/datacollector/impl/DetailStatusCodeResult.java +++ b/src/main/java/org/bench4q/agent/datacollector/impl/DetailStatusCodeResult.java @@ -29,7 +29,10 @@ public class DetailStatusCodeResult { try { for (Field field : fields) { field.setAccessible(true); - + if (field.getName().equals("contentType")) { + field.get(expectedObj).equals(field.get(this)); + continue; + } if (field.getLong(this) != field.getLong(expectedObj)) { System.out.println(field.getName() + " is diferent, this is " + field.getLong(this) diff --git a/src/main/java/org/bench4q/agent/scenario/ScenarioContext.java b/src/main/java/org/bench4q/agent/scenario/ScenarioContext.java index 1e407e10..23c7bd37 100644 --- a/src/main/java/org/bench4q/agent/scenario/ScenarioContext.java +++ b/src/main/java/org/bench4q/agent/scenario/ScenarioContext.java @@ -11,7 +11,7 @@ public class ScenarioContext { private Date startDate; private Date endDate; private ExecutorService executorService; - private Scenario scenario; + private ScenarioNew scenario; private boolean finished; private DataStatistics dataStatistics; @@ -39,11 +39,11 @@ public class ScenarioContext { this.executorService = executorService; } - public Scenario getScenario() { + public ScenarioNew getScenario() { return scenario; } - public void setScenario(Scenario scenario) { + public void setScenario(ScenarioNew scenario) { this.scenario = scenario; } @@ -64,7 +64,7 @@ public class ScenarioContext { } public static ScenarioContext buildScenarioContext(UUID testId, - final Scenario scenario, int poolSize, + final ScenarioNew scenario, int poolSize, ExecutorService executorService) { ScenarioContext scenarioContext = new ScenarioContext(); scenarioContext.setScenario(scenario); diff --git a/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java b/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java index f3f452d9..a341c5e6 100644 --- a/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java +++ b/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java @@ -8,6 +8,7 @@ import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import org.apache.log4j.Logger; +import org.bench4q.agent.api.model.behavior.Batch; import org.bench4q.agent.plugin.Plugin; import org.bench4q.agent.plugin.PluginManager; import org.bench4q.agent.plugin.result.HttpReturn; @@ -64,7 +65,7 @@ public class ScenarioEngine { this.runningTests = runningTests; } - public void runScenario(UUID runId, final Scenario scenario, int poolSize) { + public void runScenario(UUID runId, final ScenarioNew scenario, int poolSize) { try { ExecutorService executorService = Executors .newFixedThreadPool(poolSize); @@ -93,19 +94,22 @@ public class ScenarioEngine { Map plugins = new HashMap(); preparePlugins(context.getScenario(), plugins); - for (Behavior behavior : context.getScenario().getBehaviors()) { - Object plugin = plugins.get(behavior.getUse()); - Map behaviorParameters = prepareBehaviorParameters(behavior); - Date startDate = new Date(System.currentTimeMillis()); - PluginReturn pluginReturn = (PluginReturn) this.getPluginManager() - .doBehavior(plugin, behavior.getName(), behaviorParameters); - Date endDate = new Date(System.currentTimeMillis()); - if (!behavior.shouldBeCountResponseTime()) { - continue; + for (Batch batch : context.getScenario().getBatches()) { + for (Behavior behavior : batch.getBehaviors()) { + Object plugin = plugins.get(behavior.getUse()); + Map behaviorParameters = prepareBehaviorParameters(behavior); + Date startDate = new Date(System.currentTimeMillis()); + PluginReturn pluginReturn = (PluginReturn) this + .getPluginManager().doBehavior(plugin, + behavior.getName(), behaviorParameters); + Date endDate = new Date(System.currentTimeMillis()); + if (!behavior.shouldBeCountResponseTime()) { + continue; + } + context.getDataStatistics().add( + buildBehaviorResult(behavior, plugin, startDate, + pluginReturn, endDate)); } - context.getDataStatistics().add( - buildBehaviorResult(behavior, plugin, startDate, - pluginReturn, endDate)); } } @@ -141,7 +145,8 @@ public class ScenarioEngine { return behaviorParameters; } - private void preparePlugins(Scenario scenario, Map plugins) { + private void preparePlugins(ScenarioNew scenario, + Map plugins) { for (UsePlugin usePlugin : scenario.getUsePlugins()) { String pluginId = usePlugin.getId(); Class pluginClass = this.getPluginManager().getPlugins() diff --git a/src/main/java/org/bench4q/agent/scenario/ScenarioNew.java b/src/main/java/org/bench4q/agent/scenario/ScenarioNew.java new file mode 100644 index 00000000..2e008714 --- /dev/null +++ b/src/main/java/org/bench4q/agent/scenario/ScenarioNew.java @@ -0,0 +1,25 @@ +package org.bench4q.agent.scenario; + +import org.bench4q.agent.api.model.behavior.Batch; + +public class ScenarioNew { + private UsePlugin[] usePlugins; + private Batch[] batches; + + public UsePlugin[] getUsePlugins() { + return usePlugins; + } + + public void setUsePlugins(UsePlugin[] usePlugins) { + this.usePlugins = usePlugins; + } + + public Batch[] getBatches() { + return batches; + } + + public void setBatches(Batch[] batches) { + this.batches = batches; + } + +} diff --git a/src/main/java/org/bench4q/agent/scenario/Scenario.java b/src/main/java/org/bench4q/agent/scenario/ScenarioOld.java similarity index 89% rename from src/main/java/org/bench4q/agent/scenario/Scenario.java rename to src/main/java/org/bench4q/agent/scenario/ScenarioOld.java index 82e1c0a0..983e4e2e 100644 --- a/src/main/java/org/bench4q/agent/scenario/Scenario.java +++ b/src/main/java/org/bench4q/agent/scenario/ScenarioOld.java @@ -2,7 +2,7 @@ package org.bench4q.agent.scenario; import org.bench4q.agent.scenario.behavior.Behavior; -public class Scenario { +public class ScenarioOld { private UsePlugin[] usePlugins; private Behavior[] behaviors; diff --git a/src/test/java/org/bench4q/agent/test/DetailStatisticsTest.java b/src/test/java/org/bench4q/agent/test/DetailStatisticsTest.java index d414d46f..fb099c07 100644 --- a/src/test/java/org/bench4q/agent/test/DetailStatisticsTest.java +++ b/src/test/java/org/bench4q/agent/test/DetailStatisticsTest.java @@ -88,18 +88,20 @@ public class DetailStatisticsTest { private Map makeExpectedMapForTwo() { Map ret = new HashMap(); - ret.put(new Integer(200), buildCodeResult(20, 1, 200, 200)); - ret.put(new Integer(400), buildCodeResult(0, 1, 0, 0)); + ret.put(new Integer(200), buildCodeResult(20, 1, 200, 200, 200)); + ret.put(new Integer(400), buildCodeResult(0, 1, 0, 0, 0)); return ret; } private DetailStatusCodeResult buildCodeResult(long contentLength, - long count, long maxResponseTime, long minResponseTime) { + long count, long maxResponseTime, long minResponseTime, + long totalResponseTimeThisTime) { DetailStatusCodeResult ret = new DetailStatusCodeResult(""); ret.contentLength = contentLength; ret.count = count; ret.maxResponseTime = maxResponseTime; ret.minResponseTime = minResponseTime; + ret.totalResponseTimeThisTime = totalResponseTimeThisTime; return ret; } @@ -130,8 +132,8 @@ public class DetailStatisticsTest { private Map makeExpectedMapForThree() { Map retMap = new HashMap(); - retMap.put(200, buildCodeResult(40, 2, 220, 200)); - retMap.put(400, buildCodeResult(0, 1, 0, 0)); + retMap.put(200, buildCodeResult(40, 2, 220, 200, 420)); + retMap.put(400, buildCodeResult(0, 1, 0, 0, 0)); return retMap; } } diff --git a/src/test/java/org/bench4q/agent/test/TestWithScriptFile.java b/src/test/java/org/bench4q/agent/test/TestWithScriptFile.java index 32e46f6e..8436091f 100644 --- a/src/test/java/org/bench4q/agent/test/TestWithScriptFile.java +++ b/src/test/java/org/bench4q/agent/test/TestWithScriptFile.java @@ -10,7 +10,7 @@ import javax.xml.bind.JAXBException; import javax.xml.bind.Unmarshaller; import org.apache.commons.io.FileUtils; -import org.bench4q.agent.api.model.RunScenarioModel; +import org.bench4q.agent.api.model.RunScenarioModelOld; import Communication.HttpRequester; @@ -50,7 +50,7 @@ public class TestWithScriptFile { String scriptContent; try { scriptContent = FileUtils.readFileToString(file); - RunScenarioModel runScenarioModel = extractRunScenarioModel(scriptContent); + RunScenarioModelOld runScenarioModel = extractRunScenarioModel(scriptContent); if (runScenarioModel == null) { System.out.println("can't execute an unvalid script"); return; @@ -64,11 +64,11 @@ public class TestWithScriptFile { } } - private RunScenarioModel extractRunScenarioModel(String scriptContent) { + private RunScenarioModelOld extractRunScenarioModel(String scriptContent) { try { Unmarshaller unmarshaller = JAXBContext.newInstance( - RunScenarioModel.class).createUnmarshaller(); - return (RunScenarioModel) unmarshaller + RunScenarioModelOld.class).createUnmarshaller(); + return (RunScenarioModelOld) unmarshaller .unmarshal(new ByteArrayInputStream(scriptContent .getBytes())); } catch (JAXBException e) { @@ -78,10 +78,10 @@ public class TestWithScriptFile { } - private String marshalRunScenarioModel(RunScenarioModel model) + private String marshalRunScenarioModel(RunScenarioModelOld model) throws JAXBException { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); - JAXBContext.newInstance(RunScenarioModel.class).createMarshaller() + JAXBContext.newInstance(RunScenarioModelOld.class).createMarshaller() .marshal(model, outputStream); return outputStream.toString(); } From b4dc21b576bde3ad9bb2965ec8b2050fff5c6f33 Mon Sep 17 00:00:00 2001 From: coderfengyun Date: Tue, 10 Dec 2013 20:56:48 +0800 Subject: [PATCH 100/196] now agent can run scenario with a batch --- Scripts/forBatch.xml | 41 +++++++++++++++++++ .../org/bench4q/agent/api/TestController.java | 2 +- .../agent/api/model/BatchBehavior.java | 7 +++- .../agent/api/model/RunScenarioModelNew.java | 3 +- .../model/behavior => scenario}/Batch.java | 2 +- .../agent/scenario/ScenarioEngine.java | 1 - .../bench4q/agent/scenario/ScenarioNew.java | 1 - .../agent/test/TestWithScriptFile.java | 25 ++++++----- 8 files changed, 65 insertions(+), 17 deletions(-) create mode 100644 Scripts/forBatch.xml rename src/main/java/org/bench4q/agent/{api/model/behavior => scenario}/Batch.java (87%) diff --git a/Scripts/forBatch.xml b/Scripts/forBatch.xml new file mode 100644 index 00000000..8ac85584 --- /dev/null +++ b/Scripts/forBatch.xml @@ -0,0 +1,41 @@ + + + + + + + 1 + Get + + + url + http://localhost:8080/Bench4QTestCase/testcase.html + + + + parameters + + + + http + + + -1 + 0 + -1 + + + 0 + + + http + Http + + + + timer + ConstantTimer + + + + \ No newline at end of file diff --git a/src/main/java/org/bench4q/agent/api/TestController.java b/src/main/java/org/bench4q/agent/api/TestController.java index 76f02f10..7b30b915 100644 --- a/src/main/java/org/bench4q/agent/api/TestController.java +++ b/src/main/java/org/bench4q/agent/api/TestController.java @@ -25,9 +25,9 @@ import org.bench4q.agent.api.model.RunScenarioResultModel; import org.bench4q.agent.api.model.StopTestModel; import org.bench4q.agent.api.model.TestBehaviorsBriefModel; import org.bench4q.agent.api.model.UsePluginModel; -import org.bench4q.agent.api.model.behavior.Batch; import org.bench4q.agent.api.model.behavior.BehaviorBaseModel; import org.bench4q.agent.datacollector.impl.DetailStatusCodeResult; +import org.bench4q.agent.scenario.Batch; import org.bench4q.agent.scenario.Parameter; import org.bench4q.agent.scenario.ScenarioNew; import org.bench4q.agent.scenario.ScenarioContext; diff --git a/src/main/java/org/bench4q/agent/api/model/BatchBehavior.java b/src/main/java/org/bench4q/agent/api/model/BatchBehavior.java index 62a80ec6..2727b660 100644 --- a/src/main/java/org/bench4q/agent/api/model/BatchBehavior.java +++ b/src/main/java/org/bench4q/agent/api/model/BatchBehavior.java @@ -4,9 +4,12 @@ import java.util.List; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElementWrapper; +import javax.xml.bind.annotation.XmlElements; import javax.xml.bind.annotation.XmlRootElement; import org.bench4q.agent.api.model.behavior.BehaviorBaseModel; +import org.bench4q.agent.api.model.behavior.TimerBehaviorModel; +import org.bench4q.agent.api.model.behavior.UserBehaviorModel; @XmlRootElement(name = "batch") public class BatchBehavior { @@ -43,7 +46,9 @@ public class BatchBehavior { } @XmlElementWrapper(name = "behaviors") - @XmlElement + @XmlElements(value = { + @XmlElement(name = "userBehavior", type = UserBehaviorModel.class), + @XmlElement(name = "timerBehavior", type = TimerBehaviorModel.class) }) public List getBehaviors() { return behaviors; } diff --git a/src/main/java/org/bench4q/agent/api/model/RunScenarioModelNew.java b/src/main/java/org/bench4q/agent/api/model/RunScenarioModelNew.java index 62e2f7ba..327b1286 100644 --- a/src/main/java/org/bench4q/agent/api/model/RunScenarioModelNew.java +++ b/src/main/java/org/bench4q/agent/api/model/RunScenarioModelNew.java @@ -9,7 +9,6 @@ import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement(name = "runScenario") public class RunScenarioModelNew { - private int poolSize; private List usePlugins; private List batches; @@ -34,7 +33,7 @@ public class RunScenarioModelNew { } @XmlElementWrapper(name = "batches") - @XmlElement + @XmlElement(name = "batch") public List getBatches() { return batches; } diff --git a/src/main/java/org/bench4q/agent/api/model/behavior/Batch.java b/src/main/java/org/bench4q/agent/scenario/Batch.java similarity index 87% rename from src/main/java/org/bench4q/agent/api/model/behavior/Batch.java rename to src/main/java/org/bench4q/agent/scenario/Batch.java index 469c2a0e..82ee79d2 100644 --- a/src/main/java/org/bench4q/agent/api/model/behavior/Batch.java +++ b/src/main/java/org/bench4q/agent/scenario/Batch.java @@ -1,4 +1,4 @@ -package org.bench4q.agent.api.model.behavior; +package org.bench4q.agent.scenario; import org.bench4q.agent.scenario.behavior.Behavior; diff --git a/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java b/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java index a341c5e6..17ef8821 100644 --- a/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java +++ b/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java @@ -8,7 +8,6 @@ import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import org.apache.log4j.Logger; -import org.bench4q.agent.api.model.behavior.Batch; import org.bench4q.agent.plugin.Plugin; import org.bench4q.agent.plugin.PluginManager; import org.bench4q.agent.plugin.result.HttpReturn; diff --git a/src/main/java/org/bench4q/agent/scenario/ScenarioNew.java b/src/main/java/org/bench4q/agent/scenario/ScenarioNew.java index 2e008714..d82366f8 100644 --- a/src/main/java/org/bench4q/agent/scenario/ScenarioNew.java +++ b/src/main/java/org/bench4q/agent/scenario/ScenarioNew.java @@ -1,6 +1,5 @@ package org.bench4q.agent.scenario; -import org.bench4q.agent.api.model.behavior.Batch; public class ScenarioNew { private UsePlugin[] usePlugins; diff --git a/src/test/java/org/bench4q/agent/test/TestWithScriptFile.java b/src/test/java/org/bench4q/agent/test/TestWithScriptFile.java index 8436091f..e0a56c8a 100644 --- a/src/test/java/org/bench4q/agent/test/TestWithScriptFile.java +++ b/src/test/java/org/bench4q/agent/test/TestWithScriptFile.java @@ -4,14 +4,14 @@ import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; +import static org.junit.Assert.*; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Unmarshaller; import org.apache.commons.io.FileUtils; -import org.bench4q.agent.api.model.RunScenarioModelOld; - +import org.bench4q.agent.api.model.RunScenarioModelNew; import Communication.HttpRequester; public class TestWithScriptFile { @@ -37,24 +37,28 @@ public class TestWithScriptFile { } public TestWithScriptFile() { - this.setFilePath("scripts" + System.getProperty("file.separator") - + "ScriptSuzou.xml"); + this.setFilePath("Scripts" + System.getProperty("file.separator") + + "forBatch.xml"); this.setHttpRequester(new HttpRequester()); } public void testWithScript() throws JAXBException { File file = new File(this.getFilePath()); if (!file.exists()) { + System.out.println("There's no this script!"); return; } String scriptContent; try { scriptContent = FileUtils.readFileToString(file); - RunScenarioModelOld runScenarioModel = extractRunScenarioModel(scriptContent); + RunScenarioModelNew runScenarioModel = extractRunScenarioModel(scriptContent); if (runScenarioModel == null) { System.out.println("can't execute an unvalid script"); return; } + assertTrue(runScenarioModel.getBatches().size() > 0); + assertTrue(runScenarioModel.getBatches().get(0).getBehaviors() + .size() > 0); runScenarioModel.setPoolSize(load); this.getHttpRequester().sendPostXml(this.url, @@ -64,24 +68,25 @@ public class TestWithScriptFile { } } - private RunScenarioModelOld extractRunScenarioModel(String scriptContent) { + private RunScenarioModelNew extractRunScenarioModel(String scriptContent) { try { Unmarshaller unmarshaller = JAXBContext.newInstance( - RunScenarioModelOld.class).createUnmarshaller(); - return (RunScenarioModelOld) unmarshaller + RunScenarioModelNew.class).createUnmarshaller(); + return (RunScenarioModelNew) unmarshaller .unmarshal(new ByteArrayInputStream(scriptContent .getBytes())); } catch (JAXBException e) { System.out.println("model unmarshal has an exception!"); + e.printStackTrace(); return null; } } - private String marshalRunScenarioModel(RunScenarioModelOld model) + private String marshalRunScenarioModel(RunScenarioModelNew model) throws JAXBException { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); - JAXBContext.newInstance(RunScenarioModelOld.class).createMarshaller() + JAXBContext.newInstance(RunScenarioModelNew.class).createMarshaller() .marshal(model, outputStream); return outputStream.toString(); } From 6f2a884494eabfeca39075f08977716887a52758 Mon Sep 17 00:00:00 2001 From: coderfengyun Date: Wed, 11 Dec 2013 11:00:52 +0800 Subject: [PATCH 101/196] Now, agent can run the script with batch in sequence --- Scripts/forBatch.xml | 11 +++- pom.xml | 5 ++ .../org/bench4q/agent/api/TestController.java | 3 +- .../bench4q/agent/plugin/PluginManager.java | 7 ++- .../agent/scenario/ScenarioEngine.java | 1 + .../agent/test/TestWithScriptFile.java | 51 ++++++++++++++++--- 6 files changed, 64 insertions(+), 14 deletions(-) diff --git a/Scripts/forBatch.xml b/Scripts/forBatch.xml index 8ac85584..d2db49f7 100644 --- a/Scripts/forBatch.xml +++ b/Scripts/forBatch.xml @@ -19,13 +19,20 @@ http - + + 0 + Sleep + + + + time234 + timer -1 0 -1 - 0 + 20 http diff --git a/pom.xml b/pom.xml index 8cce6661..eb773c80 100644 --- a/pom.xml +++ b/pom.xml @@ -47,6 +47,11 @@ log4j 1.2.17 + + org.bench4q + bench4q-share + 0.0.1-SNAPSHOT + diff --git a/src/main/java/org/bench4q/agent/api/TestController.java b/src/main/java/org/bench4q/agent/api/TestController.java index 7b30b915..91af6873 100644 --- a/src/main/java/org/bench4q/agent/api/TestController.java +++ b/src/main/java/org/bench4q/agent/api/TestController.java @@ -20,7 +20,6 @@ import org.bench4q.agent.api.model.CleanTestResultModel; import org.bench4q.agent.api.model.BehaviorStatusCodeResultModel; import org.bench4q.agent.api.model.ParameterModel; import org.bench4q.agent.api.model.RunScenarioModelNew; -import org.bench4q.agent.api.model.RunScenarioModelOld; import org.bench4q.agent.api.model.RunScenarioResultModel; import org.bench4q.agent.api.model.StopTestModel; import org.bench4q.agent.api.model.TestBehaviorsBriefModel; @@ -82,7 +81,7 @@ public class TestController { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); Marshaller marshaller; try { - marshaller = JAXBContext.newInstance(RunScenarioModelOld.class) + marshaller = JAXBContext.newInstance(RunScenarioModelNew.class) .createMarshaller(); marshaller.marshal(inModel, outputStream); return outputStream.toString(); diff --git a/src/main/java/org/bench4q/agent/plugin/PluginManager.java b/src/main/java/org/bench4q/agent/plugin/PluginManager.java index 08bb4205..d5e6629f 100644 --- a/src/main/java/org/bench4q/agent/plugin/PluginManager.java +++ b/src/main/java/org/bench4q/agent/plugin/PluginManager.java @@ -8,6 +8,8 @@ import java.util.HashMap; import java.util.List; import java.util.Map; +import org.apache.log4j.Logger; +import org.bench4q.agent.share.DealWithLog; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @@ -16,6 +18,7 @@ public class PluginManager { private ClassHelper classHelper; private TypeConverter typeConverter; private Map> plugins; + private Logger logger = Logger.getLogger(PluginManager.class); @Autowired public PluginManager(ClassHelper classHelper, TypeConverter typeConverter) { @@ -119,7 +122,7 @@ public class PluginManager { } return parameterNames; } catch (Exception e) { - e.printStackTrace(); + logger.error(DealWithLog.getExceptionStackTrace(e)); return null; } } @@ -240,7 +243,7 @@ public class PluginManager { Object[] params = prepareParameters(method, parameters); return method.invoke(plugin, params); } catch (Exception e) { - e.printStackTrace(); + return null; } } diff --git a/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java b/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java index 17ef8821..e0b51b2a 100644 --- a/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java +++ b/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java @@ -71,6 +71,7 @@ public class ScenarioEngine { final ScenarioContext scenarioContext = ScenarioContext .buildScenarioContext(runId, scenario, poolSize, executorService); + System.out.println(poolSize); int i; this.getRunningTests().put(runId, scenarioContext); Runnable runnable = new Runnable() { diff --git a/src/test/java/org/bench4q/agent/test/TestWithScriptFile.java b/src/test/java/org/bench4q/agent/test/TestWithScriptFile.java index e0a56c8a..b4d62a53 100644 --- a/src/test/java/org/bench4q/agent/test/TestWithScriptFile.java +++ b/src/test/java/org/bench4q/agent/test/TestWithScriptFile.java @@ -4,6 +4,8 @@ import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; +import java.util.UUID; + import static org.junit.Assert.*; import javax.xml.bind.JAXBContext; @@ -12,12 +14,18 @@ import javax.xml.bind.Unmarshaller; import org.apache.commons.io.FileUtils; import org.bench4q.agent.api.model.RunScenarioModelNew; +import org.bench4q.agent.api.model.RunScenarioResultModel; +import org.bench4q.agent.api.model.behavior.TimerBehaviorModel; +import org.bench4q.share.helper.MarshalHelper; + import Communication.HttpRequester; +import Communication.HttpRequester.HttpResponse; public class TestWithScriptFile { private HttpRequester httpRequester; - private String url = "http://localhost:6565/test/run"; + private String url = "http://localhost:6565/test"; private String filePath; + private UUID testId; private static int load = 100; public String getFilePath() { @@ -36,13 +44,21 @@ public class TestWithScriptFile { this.httpRequester = httpRequester; } + public UUID getTestId() { + return testId; + } + + public void setTestId(UUID testId) { + this.testId = testId; + } + public TestWithScriptFile() { this.setFilePath("Scripts" + System.getProperty("file.separator") + "forBatch.xml"); this.setHttpRequester(new HttpRequester()); } - public void testWithScript() throws JAXBException { + public void startTest() throws JAXBException { File file = new File(this.getFilePath()); if (!file.exists()) { System.out.println("There's no this script!"); @@ -56,13 +72,24 @@ public class TestWithScriptFile { System.out.println("can't execute an unvalid script"); return; } - assertTrue(runScenarioModel.getBatches().size() > 0); - assertTrue(runScenarioModel.getBatches().get(0).getBehaviors() - .size() > 0); + assertEquals(1, runScenarioModel.getBatches().size()); + assertEquals(2, runScenarioModel.getBatches().get(0).getBehaviors() + .size()); + TimerBehaviorModel timerBehaviorModel = (TimerBehaviorModel) runScenarioModel + .getBatches().get(0).getBehaviors().get(1); + assertEquals( + 234, + Integer.parseInt(timerBehaviorModel.getParameters().get(0) + .getValue())); runScenarioModel.setPoolSize(load); - this.getHttpRequester().sendPostXml(this.url, + HttpResponse httpResponse = this.getHttpRequester().sendPostXml( + this.url + "/run", marshalRunScenarioModel(runScenarioModel), null); + RunScenarioResultModel resultModel = (RunScenarioResultModel) MarshalHelper + .unmarshal(RunScenarioResultModel.class, + httpResponse.getContent()); + this.setTestId(resultModel.getRunId()); } catch (IOException e) { System.out.println("IO exception!"); } @@ -91,8 +118,16 @@ public class TestWithScriptFile { return outputStream.toString(); } - public static void main(String[] args) throws JAXBException { + private void stopTest() throws IOException { + this.getHttpRequester().sendGet( + this.url + "/stop/" + this.getTestId().toString(), null, null); + } + + public static void main(String[] args) throws JAXBException, + InterruptedException, IOException { TestWithScriptFile testWithScriptFile = new TestWithScriptFile(); - testWithScriptFile.testWithScript(); + testWithScriptFile.startTest(); + Thread.sleep(60000); + testWithScriptFile.stopTest(); } } From 02c7d0ecc86fa56f9b1f4319d5ae83604ace9291 Mon Sep 17 00:00:00 2001 From: coderfengyun Date: Wed, 11 Dec 2013 13:52:48 +0800 Subject: [PATCH 102/196] add a integrated test about start, brief, behaviorsBrief, behaviorBrief and stop --- .../org/bench4q/agent/api/TestController.java | 2 +- .../agent/test/TestWithScriptFile.java | 54 ++++++++++++++++--- 2 files changed, 49 insertions(+), 7 deletions(-) diff --git a/src/main/java/org/bench4q/agent/api/TestController.java b/src/main/java/org/bench4q/agent/api/TestController.java index 91af6873..85b9479c 100644 --- a/src/main/java/org/bench4q/agent/api/TestController.java +++ b/src/main/java/org/bench4q/agent/api/TestController.java @@ -182,7 +182,7 @@ public class TestController { @RequestMapping(value = "/behaviorsBrief/{runId}") @ResponseBody - public TestBehaviorsBriefModel testBehaviorBriefs(@PathVariable UUID runId) { + public TestBehaviorsBriefModel behaviorsBrief(@PathVariable UUID runId) { TestBehaviorsBriefModel ret = new TestBehaviorsBriefModel(); List behaviorBriefModels = new ArrayList(); ScenarioContext scenarioContext = this.getScenarioEngine() diff --git a/src/test/java/org/bench4q/agent/test/TestWithScriptFile.java b/src/test/java/org/bench4q/agent/test/TestWithScriptFile.java index b4d62a53..27b2abf9 100644 --- a/src/test/java/org/bench4q/agent/test/TestWithScriptFile.java +++ b/src/test/java/org/bench4q/agent/test/TestWithScriptFile.java @@ -13,10 +13,14 @@ import javax.xml.bind.JAXBException; import javax.xml.bind.Unmarshaller; import org.apache.commons.io.FileUtils; +import org.bench4q.agent.api.model.AgentBriefStatusModel; +import org.bench4q.agent.api.model.BehaviorBriefModel; import org.bench4q.agent.api.model.RunScenarioModelNew; import org.bench4q.agent.api.model.RunScenarioResultModel; +import org.bench4q.agent.api.model.TestBehaviorsBriefModel; import org.bench4q.agent.api.model.behavior.TimerBehaviorModel; import org.bench4q.share.helper.MarshalHelper; +import org.junit.Test; import Communication.HttpRequester; import Communication.HttpRequester.HttpResponse; @@ -119,15 +123,53 @@ public class TestWithScriptFile { } private void stopTest() throws IOException { + System.out.println("Enter stopTest!"); this.getHttpRequester().sendGet( this.url + "/stop/" + this.getTestId().toString(), null, null); } - public static void main(String[] args) throws JAXBException, - InterruptedException, IOException { - TestWithScriptFile testWithScriptFile = new TestWithScriptFile(); - testWithScriptFile.startTest(); - Thread.sleep(60000); - testWithScriptFile.stopTest(); + private void brief() throws IOException { + System.out.println("Enter brief!"); + HttpResponse httpResponse = this.getHttpRequester().sendGet( + this.url + "/brief/" + this.getTestId().toString(), null, null); + AgentBriefStatusModel briefModel = (AgentBriefStatusModel) MarshalHelper + .unmarshal(AgentBriefStatusModel.class, + httpResponse.getContent()); + assertTrue(briefModel.getTimeFrame() > 0); + } + + private void behaviorsBrief() throws IOException { + System.out.println("Enter behaviorsBrief!"); + HttpResponse httpResponse = this.getHttpRequester().sendGet( + this.url + "/behaviorsBrief/" + this.getTestId().toString(), + null, null); + TestBehaviorsBriefModel behaviorsBriefModel = (TestBehaviorsBriefModel) MarshalHelper + .unmarshal(TestBehaviorsBriefModel.class, + httpResponse.getContent()); + assertTrue(behaviorsBriefModel.getBehaviorBriefModels().size() > 0); + } + + private void behaviorBrief() throws IOException { + System.out.println("Enter behaviorBrief!"); + HttpResponse httpResponse = this.getHttpRequester().sendGet( + this.url + "/brief/" + this.getTestId().toString() + "/1", + null, null); + BehaviorBriefModel behaviorBriefModel = (BehaviorBriefModel) MarshalHelper + .unmarshal(BehaviorBriefModel.class, httpResponse.getContent()); + assertTrue(behaviorBriefModel.getDetailStatusCodeResultModels().size() > 0); + } + + @Test + public void integrateTest() throws JAXBException, InterruptedException, + IOException { + this.startTest(); + Thread.sleep(5000); + this.brief(); + Thread.sleep(5000); + this.behaviorsBrief(); + Thread.sleep(5000); + this.behaviorBrief(); + Thread.sleep(5000); + this.stopTest(); } } From 85016b3e26632d4f3a941bc1831332327edbe77a Mon Sep 17 00:00:00 2001 From: Coderfengyun Date: Fri, 13 Dec 2013 10:04:39 +0800 Subject: [PATCH 103/196] delete RunScenarioModelOld --- .../agent/api/model/RunScenarioModelOld.java | 49 ------------------- 1 file changed, 49 deletions(-) delete mode 100644 src/main/java/org/bench4q/agent/api/model/RunScenarioModelOld.java diff --git a/src/main/java/org/bench4q/agent/api/model/RunScenarioModelOld.java b/src/main/java/org/bench4q/agent/api/model/RunScenarioModelOld.java deleted file mode 100644 index 1c594387..00000000 --- a/src/main/java/org/bench4q/agent/api/model/RunScenarioModelOld.java +++ /dev/null @@ -1,49 +0,0 @@ -package org.bench4q.agent.api.model; - -import java.util.List; - -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlElementWrapper; -import javax.xml.bind.annotation.XmlElements; -import javax.xml.bind.annotation.XmlRootElement; - -import org.bench4q.agent.api.model.behavior.TimerBehaviorModel; -import org.bench4q.agent.api.model.behavior.UserBehaviorModel; - -@XmlRootElement(name = "runScenario") -public class RunScenarioModelOld { - private int poolSize; - private List usePlugins; - private List behaviors; - - @XmlElement - public int getPoolSize() { - return poolSize; - } - - public void setPoolSize(int poolSize) { - this.poolSize = poolSize; - } - - @XmlElementWrapper(name = "usePlugins") - @XmlElement(name = "usePlugin") - public List getUsePlugins() { - return usePlugins; - } - - public void setUsePlugins(List usePlugins) { - this.usePlugins = usePlugins; - } - - @XmlElementWrapper(name = "behaviors") - @XmlElements(value = { - @XmlElement(name = "userBehavior", type = UserBehaviorModel.class), - @XmlElement(name = "timerBehavior", type = TimerBehaviorModel.class) }) - public List getBehaviors() { - return behaviors; - } - - public void setBehaviors(List behaviors) { - this.behaviors = behaviors; - } -} From 9fc5bc77c1c0dac3490060a92f7a55e363397f11 Mon Sep 17 00:00:00 2001 From: Coderfengyun Date: Fri, 13 Dec 2013 10:33:56 +0800 Subject: [PATCH 104/196] the model about scenario use the share ones --- .../org/bench4q/agent/api/TestController.java | 10 ++-- .../agent/api/model/BatchBehavior.java | 60 ------------------- .../agent/api/model/ParameterModel.java | 29 --------- .../agent/api/model/RunScenarioModelNew.java | 49 --------------- .../agent/api/model/UsePluginModel.java | 43 ------------- .../api/model/behavior/BehaviorBaseModel.java | 53 ---------------- .../model/behavior/TimerBehaviorModel.java | 24 -------- .../api/model/behavior/UserBehaviorModel.java | 20 ------- .../scenario/behavior/BehaviorFactory.java | 6 +- .../agent/test/TestWithScriptFile.java | 4 +- .../bench4q/agent/test/model/ModelTest.java | 2 +- .../test/model/UserBehaviorModelTest.java | 4 +- 12 files changed, 13 insertions(+), 291 deletions(-) delete mode 100644 src/main/java/org/bench4q/agent/api/model/BatchBehavior.java delete mode 100644 src/main/java/org/bench4q/agent/api/model/ParameterModel.java delete mode 100644 src/main/java/org/bench4q/agent/api/model/RunScenarioModelNew.java delete mode 100644 src/main/java/org/bench4q/agent/api/model/UsePluginModel.java delete mode 100644 src/main/java/org/bench4q/agent/api/model/behavior/BehaviorBaseModel.java delete mode 100644 src/main/java/org/bench4q/agent/api/model/behavior/TimerBehaviorModel.java delete mode 100644 src/main/java/org/bench4q/agent/api/model/behavior/UserBehaviorModel.java diff --git a/src/main/java/org/bench4q/agent/api/TestController.java b/src/main/java/org/bench4q/agent/api/TestController.java index 85b9479c..c95a5437 100644 --- a/src/main/java/org/bench4q/agent/api/TestController.java +++ b/src/main/java/org/bench4q/agent/api/TestController.java @@ -14,17 +14,12 @@ import javax.xml.bind.Marshaller; import org.apache.log4j.Logger; import org.bench4q.agent.api.model.AgentBriefStatusModel; -import org.bench4q.agent.api.model.BatchBehavior; import org.bench4q.agent.api.model.BehaviorBriefModel; import org.bench4q.agent.api.model.CleanTestResultModel; import org.bench4q.agent.api.model.BehaviorStatusCodeResultModel; -import org.bench4q.agent.api.model.ParameterModel; -import org.bench4q.agent.api.model.RunScenarioModelNew; import org.bench4q.agent.api.model.RunScenarioResultModel; import org.bench4q.agent.api.model.StopTestModel; import org.bench4q.agent.api.model.TestBehaviorsBriefModel; -import org.bench4q.agent.api.model.UsePluginModel; -import org.bench4q.agent.api.model.behavior.BehaviorBaseModel; import org.bench4q.agent.datacollector.impl.DetailStatusCodeResult; import org.bench4q.agent.scenario.Batch; import org.bench4q.agent.scenario.Parameter; @@ -34,6 +29,11 @@ import org.bench4q.agent.scenario.ScenarioEngine; import org.bench4q.agent.scenario.UsePlugin; import org.bench4q.agent.scenario.behavior.Behavior; import org.bench4q.agent.scenario.behavior.BehaviorFactory; +import org.bench4q.share.models.agent.ParameterModel; +import org.bench4q.share.models.agent.RunScenarioModelNew; +import org.bench4q.share.models.agent.scriptrecord.BatchBehavior; +import org.bench4q.share.models.agent.scriptrecord.BehaviorBaseModel; +import org.bench4q.share.models.agent.scriptrecord.UsePluginModel; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; diff --git a/src/main/java/org/bench4q/agent/api/model/BatchBehavior.java b/src/main/java/org/bench4q/agent/api/model/BatchBehavior.java deleted file mode 100644 index 2727b660..00000000 --- a/src/main/java/org/bench4q/agent/api/model/BatchBehavior.java +++ /dev/null @@ -1,60 +0,0 @@ -package org.bench4q.agent.api.model; - -import java.util.List; - -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlElementWrapper; -import javax.xml.bind.annotation.XmlElements; -import javax.xml.bind.annotation.XmlRootElement; - -import org.bench4q.agent.api.model.behavior.BehaviorBaseModel; -import org.bench4q.agent.api.model.behavior.TimerBehaviorModel; -import org.bench4q.agent.api.model.behavior.UserBehaviorModel; - -@XmlRootElement(name = "batch") -public class BatchBehavior { - private int Id; - private int parentId; - private int childId; - private List behaviors; - - @XmlElement - public int getId() { - return Id; - } - - public void setId(int id) { - Id = id; - } - - @XmlElement - public int getParentId() { - return parentId; - } - - public void setParentId(int parentBatchId) { - this.parentId = parentBatchId; - } - - @XmlElement - public int getChildId() { - return childId; - } - - public void setChildId(int childId) { - this.childId = childId; - } - - @XmlElementWrapper(name = "behaviors") - @XmlElements(value = { - @XmlElement(name = "userBehavior", type = UserBehaviorModel.class), - @XmlElement(name = "timerBehavior", type = TimerBehaviorModel.class) }) - public List getBehaviors() { - return behaviors; - } - - public void setBehaviors(List behaviors) { - this.behaviors = behaviors; - } - -} diff --git a/src/main/java/org/bench4q/agent/api/model/ParameterModel.java b/src/main/java/org/bench4q/agent/api/model/ParameterModel.java deleted file mode 100644 index 130f7abb..00000000 --- a/src/main/java/org/bench4q/agent/api/model/ParameterModel.java +++ /dev/null @@ -1,29 +0,0 @@ -package org.bench4q.agent.api.model; - -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; - } - -} diff --git a/src/main/java/org/bench4q/agent/api/model/RunScenarioModelNew.java b/src/main/java/org/bench4q/agent/api/model/RunScenarioModelNew.java deleted file mode 100644 index 327b1286..00000000 --- a/src/main/java/org/bench4q/agent/api/model/RunScenarioModelNew.java +++ /dev/null @@ -1,49 +0,0 @@ -package org.bench4q.agent.api.model; - -import java.util.ArrayList; -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 RunScenarioModelNew { - private int poolSize; - private List usePlugins; - private List batches; - - @XmlElement - public int getPoolSize() { - return poolSize; - } - - public void setPoolSize(int poolSize) { - this.poolSize = poolSize; - } - - @XmlElementWrapper(name = "usePlugins") - @XmlElement(name = "usePlugin") - public List getUsePlugins() { - return usePlugins; - } - - public void setUsePlugins(List usePlugins) { - this.usePlugins = usePlugins; - } - - @XmlElementWrapper(name = "batches") - @XmlElement(name = "batch") - public List getBatches() { - return batches; - } - - public void setBatches(List batches) { - this.batches = batches; - } - - public RunScenarioModelNew() { - this.setBatches(new ArrayList()); - this.setUsePlugins(new ArrayList()); - } -} diff --git a/src/main/java/org/bench4q/agent/api/model/UsePluginModel.java b/src/main/java/org/bench4q/agent/api/model/UsePluginModel.java deleted file mode 100644 index f5c61d51..00000000 --- a/src/main/java/org/bench4q/agent/api/model/UsePluginModel.java +++ /dev/null @@ -1,43 +0,0 @@ -package org.bench4q.agent.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 = "usePlugin") -public class UsePluginModel { - private String id; - private String name; - private List 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 getParameters() { - return parameters; - } - - public void setParameters(List parameters) { - this.parameters = parameters; - } - -} diff --git a/src/main/java/org/bench4q/agent/api/model/behavior/BehaviorBaseModel.java b/src/main/java/org/bench4q/agent/api/model/behavior/BehaviorBaseModel.java deleted file mode 100644 index 57e05c5b..00000000 --- a/src/main/java/org/bench4q/agent/api/model/behavior/BehaviorBaseModel.java +++ /dev/null @@ -1,53 +0,0 @@ -package org.bench4q.agent.api.model.behavior; - -import java.util.List; - -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlElementWrapper; - -import org.bench4q.agent.api.model.ParameterModel; - -public abstract class BehaviorBaseModel { - private int id; - private String use; - private String name; - private List parameters; - - @XmlElement - public int getId() { - return id; - } - - public void setId(int id) { - this.id = id; - } - - @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 getParameters() { - return parameters; - } - - public void setParameters(List parameters) { - this.parameters = parameters; - } - -} diff --git a/src/main/java/org/bench4q/agent/api/model/behavior/TimerBehaviorModel.java b/src/main/java/org/bench4q/agent/api/model/behavior/TimerBehaviorModel.java deleted file mode 100644 index 5204fdb7..00000000 --- a/src/main/java/org/bench4q/agent/api/model/behavior/TimerBehaviorModel.java +++ /dev/null @@ -1,24 +0,0 @@ -package org.bench4q.agent.api.model.behavior; - -import java.io.ByteArrayOutputStream; - -import javax.xml.bind.JAXBContext; -import javax.xml.bind.Marshaller; -import javax.xml.bind.annotation.XmlRootElement; - -@XmlRootElement(name = "timerBehavior") -public class TimerBehaviorModel extends BehaviorBaseModel { - - public String getModelString() { - ByteArrayOutputStream os = new ByteArrayOutputStream(); - try { - Marshaller marshaller = JAXBContext.newInstance(this.getClass()) - .createMarshaller(); - marshaller.marshal(this, os); - } catch (Exception e) { - e.printStackTrace(); - } - return os.toString(); - } - -} diff --git a/src/main/java/org/bench4q/agent/api/model/behavior/UserBehaviorModel.java b/src/main/java/org/bench4q/agent/api/model/behavior/UserBehaviorModel.java deleted file mode 100644 index 0d94308d..00000000 --- a/src/main/java/org/bench4q/agent/api/model/behavior/UserBehaviorModel.java +++ /dev/null @@ -1,20 +0,0 @@ -package org.bench4q.agent.api.model.behavior; - -import java.io.ByteArrayOutputStream; - -import javax.xml.bind.JAXBContext; -import javax.xml.bind.JAXBException; -import javax.xml.bind.Marshaller; -import javax.xml.bind.annotation.XmlRootElement; - -@XmlRootElement(name = "userBehavior") -public class UserBehaviorModel extends BehaviorBaseModel { - public String getModelString() throws JAXBException { - ByteArrayOutputStream os = new ByteArrayOutputStream(); - Marshaller marshaller = JAXBContext.newInstance(this.getClass()) - .createMarshaller(); - marshaller.marshal(this, os); - return os.toString(); - } - -} diff --git a/src/main/java/org/bench4q/agent/scenario/behavior/BehaviorFactory.java b/src/main/java/org/bench4q/agent/scenario/behavior/BehaviorFactory.java index f8d37fd3..a8724867 100644 --- a/src/main/java/org/bench4q/agent/scenario/behavior/BehaviorFactory.java +++ b/src/main/java/org/bench4q/agent/scenario/behavior/BehaviorFactory.java @@ -1,8 +1,8 @@ package org.bench4q.agent.scenario.behavior; -import org.bench4q.agent.api.model.behavior.BehaviorBaseModel; -import org.bench4q.agent.api.model.behavior.TimerBehaviorModel; -import org.bench4q.agent.api.model.behavior.UserBehaviorModel; +import org.bench4q.share.models.agent.scriptrecord.BehaviorBaseModel; +import org.bench4q.share.models.agent.scriptrecord.TimerBehaviorModel; +import org.bench4q.share.models.agent.scriptrecord.UserBehaviorModel; public class BehaviorFactory { public static Behavior getBuisinessObject(BehaviorBaseModel modelInput) { diff --git a/src/test/java/org/bench4q/agent/test/TestWithScriptFile.java b/src/test/java/org/bench4q/agent/test/TestWithScriptFile.java index 27b2abf9..9e4c320a 100644 --- a/src/test/java/org/bench4q/agent/test/TestWithScriptFile.java +++ b/src/test/java/org/bench4q/agent/test/TestWithScriptFile.java @@ -15,11 +15,11 @@ import javax.xml.bind.Unmarshaller; import org.apache.commons.io.FileUtils; import org.bench4q.agent.api.model.AgentBriefStatusModel; import org.bench4q.agent.api.model.BehaviorBriefModel; -import org.bench4q.agent.api.model.RunScenarioModelNew; import org.bench4q.agent.api.model.RunScenarioResultModel; import org.bench4q.agent.api.model.TestBehaviorsBriefModel; -import org.bench4q.agent.api.model.behavior.TimerBehaviorModel; import org.bench4q.share.helper.MarshalHelper; +import org.bench4q.share.models.agent.RunScenarioModelNew; +import org.bench4q.share.models.agent.scriptrecord.TimerBehaviorModel; import org.junit.Test; import Communication.HttpRequester; diff --git a/src/test/java/org/bench4q/agent/test/model/ModelTest.java b/src/test/java/org/bench4q/agent/test/model/ModelTest.java index 5428ef66..31dc3ed5 100644 --- a/src/test/java/org/bench4q/agent/test/model/ModelTest.java +++ b/src/test/java/org/bench4q/agent/test/model/ModelTest.java @@ -8,7 +8,7 @@ import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.annotation.XmlRootElement; -import org.bench4q.agent.api.model.behavior.BehaviorBaseModel; +import org.bench4q.share.models.agent.scriptrecord.BehaviorBaseModel; import org.junit.Test; import static org.junit.Assert.*; diff --git a/src/test/java/org/bench4q/agent/test/model/UserBehaviorModelTest.java b/src/test/java/org/bench4q/agent/test/model/UserBehaviorModelTest.java index 601416f4..9db6836f 100644 --- a/src/test/java/org/bench4q/agent/test/model/UserBehaviorModelTest.java +++ b/src/test/java/org/bench4q/agent/test/model/UserBehaviorModelTest.java @@ -8,8 +8,8 @@ import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Unmarshaller; -import org.bench4q.agent.api.model.behavior.BehaviorBaseModel; -import org.bench4q.agent.api.model.behavior.UserBehaviorModel; +import org.bench4q.share.models.agent.scriptrecord.BehaviorBaseModel; +import org.bench4q.share.models.agent.scriptrecord.UserBehaviorModel; import org.junit.Test; public class UserBehaviorModelTest { From 22789ada8ef4889e762eb111f41d6e2a5629de0c Mon Sep 17 00:00:00 2001 From: Coderfengyun Date: Fri, 13 Dec 2013 14:04:27 +0800 Subject: [PATCH 105/196] now, agent can run the latest batch in latest runScenarioModel --- Scripts/forBatch.xml | 48 ------ Scripts/goodForBatch.xml | 146 ++++++++++++++++++ .../org/bench4q/agent/api/TestController.java | 14 +- .../agent/test/TestWithScriptFile.java | 31 ++-- 4 files changed, 165 insertions(+), 74 deletions(-) delete mode 100644 Scripts/forBatch.xml create mode 100644 Scripts/goodForBatch.xml diff --git a/Scripts/forBatch.xml b/Scripts/forBatch.xml deleted file mode 100644 index d2db49f7..00000000 --- a/Scripts/forBatch.xml +++ /dev/null @@ -1,48 +0,0 @@ - - - - - - - 1 - Get - - - url - http://localhost:8080/Bench4QTestCase/testcase.html - - - - parameters - - - - http - - - 0 - Sleep - - - - time234 - timer - -1 - 0 - -1 - - - 20 - - - http - Http - - - - timer - ConstantTimer - - - - \ No newline at end of file diff --git a/Scripts/goodForBatch.xml b/Scripts/goodForBatch.xml new file mode 100644 index 00000000..985d6fa6 --- /dev/null +++ b/Scripts/goodForBatch.xml @@ -0,0 +1,146 @@ + + + + + + + 1 + Get + + + url + http://133.133.12.3:8080/Bench4QTestCase/testcase.html + + + + parameters + + + + http + + + 2 + 0 + -1 + + + + + 0 + Sleep + + + time + 2500 + + + timer + + + -1 + 1 + -1 + + + + + 3 + Get + + + url + http://133.133.12.3:8080/Bench4QTestCase/images/3.jpg + + + + parameters + + + + http + + + 4 + Get + + + url + http://133.133.12.3:8080/Bench4QTestCase/script/agentTable.js + + + + parameters + + + + http + + + 5 + Get + + + url + http://133.133.12.3:8080/Bench4QTestCase/script/base.js + + + + parameters + + + + http + + + 6 + Get + + + url + http://133.133.12.3:8080/Bench4QTestCase/images/1.jpg + + + + parameters + + + + http + + + 7 + Get + + + url + http://133.133.12.3:8080/Bench4QTestCase/images/2.jpg + + + + parameters + + + + http + + + -1 + 2 + 0 + + + 0 + + + http + Http + + + + timer + ConstantTimer + + + + \ No newline at end of file diff --git a/src/main/java/org/bench4q/agent/api/TestController.java b/src/main/java/org/bench4q/agent/api/TestController.java index c95a5437..f9506023 100644 --- a/src/main/java/org/bench4q/agent/api/TestController.java +++ b/src/main/java/org/bench4q/agent/api/TestController.java @@ -30,7 +30,7 @@ import org.bench4q.agent.scenario.UsePlugin; import org.bench4q.agent.scenario.behavior.Behavior; import org.bench4q.agent.scenario.behavior.BehaviorFactory; import org.bench4q.share.models.agent.ParameterModel; -import org.bench4q.share.models.agent.RunScenarioModelNew; +import org.bench4q.share.models.agent.RunScenarioModel; import org.bench4q.share.models.agent.scriptrecord.BatchBehavior; import org.bench4q.share.models.agent.scriptrecord.BehaviorBaseModel; import org.bench4q.share.models.agent.scriptrecord.UsePluginModel; @@ -64,7 +64,7 @@ public class TestController { @RequestMapping(value = "/run", method = RequestMethod.POST) @ResponseBody public RunScenarioResultModel run( - @RequestBody RunScenarioModelNew runScenarioModel) + @RequestBody RunScenarioModel runScenarioModel) throws UnknownHostException { ScenarioNew scenario = extractScenario(runScenarioModel); UUID runId = UUID.randomUUID(); @@ -77,11 +77,11 @@ public class TestController { return runScenarioResultModel; } - private String marshalRunScenarioModel(RunScenarioModelNew inModel) { + private String marshalRunScenarioModel(RunScenarioModel inModel) { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); Marshaller marshaller; try { - marshaller = JAXBContext.newInstance(RunScenarioModelNew.class) + marshaller = JAXBContext.newInstance(RunScenarioModel.class) .createMarshaller(); marshaller.marshal(inModel, outputStream); return outputStream.toString(); @@ -91,7 +91,7 @@ public class TestController { } - private ScenarioNew extractScenario(RunScenarioModelNew runScenarioModel) { + private ScenarioNew extractScenario(RunScenarioModel runScenarioModel) { ScenarioNew scenario = new ScenarioNew(); scenario.setUsePlugins(new UsePlugin[runScenarioModel.getUsePlugins() .size()]); @@ -101,7 +101,7 @@ public class TestController { return scenario; } - private void extractBatches(RunScenarioModelNew runScenarioModel, + private void extractBatches(RunScenarioModel runScenarioModel, ScenarioNew scenario) { int i; List batches = runScenarioModel.getBatches(); @@ -111,7 +111,7 @@ public class TestController { } } - private void extractUsePlugins(RunScenarioModelNew runScenarioModel, + private void extractUsePlugins(RunScenarioModel runScenarioModel, ScenarioNew scenario) { int i; List usePluginModels = runScenarioModel.getUsePlugins(); diff --git a/src/test/java/org/bench4q/agent/test/TestWithScriptFile.java b/src/test/java/org/bench4q/agent/test/TestWithScriptFile.java index 9e4c320a..9ac96c57 100644 --- a/src/test/java/org/bench4q/agent/test/TestWithScriptFile.java +++ b/src/test/java/org/bench4q/agent/test/TestWithScriptFile.java @@ -18,8 +18,7 @@ import org.bench4q.agent.api.model.BehaviorBriefModel; import org.bench4q.agent.api.model.RunScenarioResultModel; import org.bench4q.agent.api.model.TestBehaviorsBriefModel; import org.bench4q.share.helper.MarshalHelper; -import org.bench4q.share.models.agent.RunScenarioModelNew; -import org.bench4q.share.models.agent.scriptrecord.TimerBehaviorModel; +import org.bench4q.share.models.agent.RunScenarioModel; import org.junit.Test; import Communication.HttpRequester; @@ -30,7 +29,7 @@ public class TestWithScriptFile { private String url = "http://localhost:6565/test"; private String filePath; private UUID testId; - private static int load = 100; + private static int load = 10; public String getFilePath() { return filePath; @@ -58,7 +57,7 @@ public class TestWithScriptFile { public TestWithScriptFile() { this.setFilePath("Scripts" + System.getProperty("file.separator") - + "forBatch.xml"); + + "goodForBatch.xml"); this.setHttpRequester(new HttpRequester()); } @@ -71,20 +70,14 @@ public class TestWithScriptFile { String scriptContent; try { scriptContent = FileUtils.readFileToString(file); - RunScenarioModelNew runScenarioModel = extractRunScenarioModel(scriptContent); + RunScenarioModel runScenarioModel = extractRunScenarioModel(scriptContent); if (runScenarioModel == null) { System.out.println("can't execute an unvalid script"); return; } - assertEquals(1, runScenarioModel.getBatches().size()); - assertEquals(2, runScenarioModel.getBatches().get(0).getBehaviors() - .size()); - TimerBehaviorModel timerBehaviorModel = (TimerBehaviorModel) runScenarioModel - .getBatches().get(0).getBehaviors().get(1); - assertEquals( - 234, - Integer.parseInt(timerBehaviorModel.getParameters().get(0) - .getValue())); + assertTrue(runScenarioModel.getBatches().size() > 0); + assertTrue(runScenarioModel.getBatches().get(0).getBehaviors() + .size() > 0); runScenarioModel.setPoolSize(load); HttpResponse httpResponse = this.getHttpRequester().sendPostXml( @@ -99,11 +92,11 @@ public class TestWithScriptFile { } } - private RunScenarioModelNew extractRunScenarioModel(String scriptContent) { + private RunScenarioModel extractRunScenarioModel(String scriptContent) { try { Unmarshaller unmarshaller = JAXBContext.newInstance( - RunScenarioModelNew.class).createUnmarshaller(); - return (RunScenarioModelNew) unmarshaller + RunScenarioModel.class).createUnmarshaller(); + return (RunScenarioModel) unmarshaller .unmarshal(new ByteArrayInputStream(scriptContent .getBytes())); } catch (JAXBException e) { @@ -114,10 +107,10 @@ public class TestWithScriptFile { } - private String marshalRunScenarioModel(RunScenarioModelNew model) + private String marshalRunScenarioModel(RunScenarioModel model) throws JAXBException { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); - JAXBContext.newInstance(RunScenarioModelNew.class).createMarshaller() + JAXBContext.newInstance(RunScenarioModel.class).createMarshaller() .marshal(model, outputStream); return outputStream.toString(); } From 600ea1f494edc7d0e7a8e3bc5fa041c7eb7b4a9f Mon Sep 17 00:00:00 2001 From: coderfengyun Date: Mon, 16 Dec 2013 10:05:49 +0800 Subject: [PATCH 106/196] edit the save path of the detail result --- .../agent/datacollector/impl/AgentResultDataCollector.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/main/java/org/bench4q/agent/datacollector/impl/AgentResultDataCollector.java b/src/main/java/org/bench4q/agent/datacollector/impl/AgentResultDataCollector.java index 42516ab1..53b460af 100644 --- a/src/main/java/org/bench4q/agent/datacollector/impl/AgentResultDataCollector.java +++ b/src/main/java/org/bench4q/agent/datacollector/impl/AgentResultDataCollector.java @@ -237,7 +237,8 @@ public class AgentResultDataCollector extends AbstractDataCollector { return "DetailResults" + System.getProperty("file.separator") + new SimpleDateFormat("yyyyMMdd").format(new Date()) + System.getProperty("file.separator") + this.getTestID() + "_" - + behaviorResult.getBehaviorId() + ".txt"; + + behaviorResult.getBehaviorId() + "_" + + System.currentTimeMillis() + ".txt"; } @Override From f842cf364064ad9304cd36d412fb04f1019a8cd6 Mon Sep 17 00:00:00 2001 From: coderfengyun Date: Mon, 16 Dec 2013 14:09:01 +0800 Subject: [PATCH 107/196] add a configuration for agent. --- configure/agent-config.properties | 2 + src/main/java/org/bench4q/agent/Main.java | 56 ++++++++++++++++++- .../impl/AbstractDataCollector.java | 4 ++ .../impl/AgentResultDataCollector.java | 6 +- src/main/resources/agent-config.properties | 5 ++ .../java/org/bench4q/agent/test/MainTest.java | 34 +++++++++++ 6 files changed, 104 insertions(+), 3 deletions(-) create mode 100644 configure/agent-config.properties create mode 100644 src/main/resources/agent-config.properties create mode 100644 src/test/java/org/bench4q/agent/test/MainTest.java diff --git a/configure/agent-config.properties b/configure/agent-config.properties new file mode 100644 index 00000000..9ab434f8 --- /dev/null +++ b/configure/agent-config.properties @@ -0,0 +1,2 @@ +isToSaveDetailResult=false +servePort=6565 \ No newline at end of file diff --git a/src/main/java/org/bench4q/agent/Main.java b/src/main/java/org/bench4q/agent/Main.java index 43ca4fee..5b756a1f 100644 --- a/src/main/java/org/bench4q/agent/Main.java +++ b/src/main/java/org/bench4q/agent/Main.java @@ -1,9 +1,63 @@ package org.bench4q.agent; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.util.Properties; + +import org.apache.log4j.Logger; + public class Main { + private static final String CONFIG_FILE_NAME = "agent-config.properties"; + private static String dirPath = "configure" + + System.getProperty("file.separator"); + private static Logger logger = Logger.getLogger(Main.class); public static void main(String[] args) { - AgentServer agentServer = new AgentServer(6565); + init(); + AgentServer agentServer = new AgentServer(getPortToServe()); agentServer.start(); } + + public static void init() { + + File dirFile = new File(dirPath); + if (!dirFile.exists()) { + dirFile.mkdirs(); + } + File configFile = new File(dirPath + CONFIG_FILE_NAME); + + if (!configFile.exists()) { + createDefaultConfig(configFile); + } + } + + private static void createDefaultConfig(File configFile) { + try { + if (configFile.createNewFile()) { + FileOutputStream outputStream = new FileOutputStream(configFile); + String content = "isToSaveDetailResult=false" + "\n" + + "servePort=6565"; + outputStream.write(content.getBytes()); + outputStream.flush(); + outputStream.close(); + } + } catch (Exception e) { + } + } + + private static int getPortToServe() { + int result = 6565; + try { + FileInputStream inputStream = new FileInputStream(new File(dirPath + + CONFIG_FILE_NAME)); + Properties properties = new Properties(); + properties.load(inputStream); + return (Integer) properties.get("servePort"); + } catch (IOException e) { + logger.error("There is an error when getPortToServe!"); + } + return result; + } } diff --git a/src/main/java/org/bench4q/agent/datacollector/impl/AbstractDataCollector.java b/src/main/java/org/bench4q/agent/datacollector/impl/AbstractDataCollector.java index e7b6f863..472592e4 100644 --- a/src/main/java/org/bench4q/agent/datacollector/impl/AbstractDataCollector.java +++ b/src/main/java/org/bench4q/agent/datacollector/impl/AbstractDataCollector.java @@ -16,6 +16,7 @@ import org.bench4q.agent.storage.StorageHelper; public abstract class AbstractDataCollector implements DataStatistics { protected StorageHelper storageHelper; private Logger logger = Logger.getLogger(AbstractDataCollector.class); + private static boolean isToSave = false; protected StorageHelper getStorageHelper() { return storageHelper; @@ -44,6 +45,9 @@ public abstract class AbstractDataCollector implements DataStatistics { } public void add(final BehaviorResult behaviorResult) { + if (!isToSave) { + return; + } Runnable runnable = new Runnable() { public void run() { storageHelper.getLocalStorage().writeFile( diff --git a/src/main/java/org/bench4q/agent/datacollector/impl/AgentResultDataCollector.java b/src/main/java/org/bench4q/agent/datacollector/impl/AgentResultDataCollector.java index 53b460af..3fca6039 100644 --- a/src/main/java/org/bench4q/agent/datacollector/impl/AgentResultDataCollector.java +++ b/src/main/java/org/bench4q/agent/datacollector/impl/AgentResultDataCollector.java @@ -234,11 +234,13 @@ public class AgentResultDataCollector extends AbstractDataCollector { @Override protected String calculateSavePath(BehaviorResult behaviorResult) { + Date now = new Date(); + return "DetailResults" + System.getProperty("file.separator") - + new SimpleDateFormat("yyyyMMdd").format(new Date()) + + new SimpleDateFormat("yyyyMMdd").format(now) + System.getProperty("file.separator") + this.getTestID() + "_" + behaviorResult.getBehaviorId() + "_" - + System.currentTimeMillis() + ".txt"; + + new SimpleDateFormat("hhmm") + ".txt"; } @Override diff --git a/src/main/resources/agent-config.properties b/src/main/resources/agent-config.properties new file mode 100644 index 00000000..2bff7082 --- /dev/null +++ b/src/main/resources/agent-config.properties @@ -0,0 +1,5 @@ +# let the administrator can decide whether to save the detail result of behavior. +isToSaveDetailResult=false + +# let the administrator can decide which port the agent should use in running +servePort=6565 \ No newline at end of file diff --git a/src/test/java/org/bench4q/agent/test/MainTest.java b/src/test/java/org/bench4q/agent/test/MainTest.java new file mode 100644 index 00000000..deed2f07 --- /dev/null +++ b/src/test/java/org/bench4q/agent/test/MainTest.java @@ -0,0 +1,34 @@ +package org.bench4q.agent.test; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.util.Properties; + +import org.bench4q.agent.Main; +import org.junit.Test; + +import static org.junit.Assert.*; + +public class MainTest { + public MainTest() { + Main.init(); + } + + @Test + public void initTest() { + Main.init(); + assertTrue(new File("configure").exists()); + } + + @Test + public void getPortServeTest() throws IOException { + FileInputStream inputStream = new FileInputStream(new File("configure" + + System.getProperty("file.separator") + + "agent-config.properties")); + Properties properties = new Properties(); + properties.load(inputStream); + assertEquals(6565, + Integer.parseInt((String) properties.get("servePort"))); + } +} From 985865f7189815b1184f90e5de69e976481c3775 Mon Sep 17 00:00:00 2001 From: coderfengyun Date: Mon, 16 Dec 2013 14:28:40 +0800 Subject: [PATCH 108/196] load properties from configuration file --- src/main/java/org/bench4q/agent/Main.java | 25 +++++++++++-------- .../impl/AbstractDataCollector.java | 4 +-- 2 files changed, 16 insertions(+), 13 deletions(-) diff --git a/src/main/java/org/bench4q/agent/Main.java b/src/main/java/org/bench4q/agent/Main.java index 5b756a1f..489600ca 100644 --- a/src/main/java/org/bench4q/agent/Main.java +++ b/src/main/java/org/bench4q/agent/Main.java @@ -10,27 +10,29 @@ import org.apache.log4j.Logger; public class Main { private static final String CONFIG_FILE_NAME = "agent-config.properties"; - private static String dirPath = "configure" + private static String DIR_PATH = "configure" + System.getProperty("file.separator"); private static Logger logger = Logger.getLogger(Main.class); + private static int PORT_TO_SERVE; + public static boolean IS_TO_SAVE_DETAIL; public static void main(String[] args) { init(); - AgentServer agentServer = new AgentServer(getPortToServe()); + AgentServer agentServer = new AgentServer(PORT_TO_SERVE); agentServer.start(); } public static void init() { - - File dirFile = new File(dirPath); + // TODO: when the configuration exists, should validate it + File dirFile = new File(DIR_PATH); if (!dirFile.exists()) { dirFile.mkdirs(); } - File configFile = new File(dirPath + CONFIG_FILE_NAME); - + File configFile = new File(DIR_PATH + CONFIG_FILE_NAME); if (!configFile.exists()) { createDefaultConfig(configFile); } + initProperties(); } private static void createDefaultConfig(File configFile) { @@ -47,17 +49,18 @@ public class Main { } } - private static int getPortToServe() { - int result = 6565; + private static void initProperties() { try { - FileInputStream inputStream = new FileInputStream(new File(dirPath + FileInputStream inputStream = new FileInputStream(new File(DIR_PATH + CONFIG_FILE_NAME)); Properties properties = new Properties(); properties.load(inputStream); - return (Integer) properties.get("servePort"); + PORT_TO_SERVE = (Integer) properties.get("servePort"); + IS_TO_SAVE_DETAIL = (Boolean) properties + .get("isToSaveDetailResult"); } catch (IOException e) { logger.error("There is an error when getPortToServe!"); } - return result; } + } diff --git a/src/main/java/org/bench4q/agent/datacollector/impl/AbstractDataCollector.java b/src/main/java/org/bench4q/agent/datacollector/impl/AbstractDataCollector.java index 472592e4..1b094d77 100644 --- a/src/main/java/org/bench4q/agent/datacollector/impl/AbstractDataCollector.java +++ b/src/main/java/org/bench4q/agent/datacollector/impl/AbstractDataCollector.java @@ -7,6 +7,7 @@ import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import org.apache.log4j.Logger; +import org.bench4q.agent.Main; import org.bench4q.agent.api.model.BehaviorResultModel; import org.bench4q.agent.datacollector.interfaces.DataStatistics; import org.bench4q.agent.helper.ApplicationContextHelper; @@ -16,7 +17,6 @@ import org.bench4q.agent.storage.StorageHelper; public abstract class AbstractDataCollector implements DataStatistics { protected StorageHelper storageHelper; private Logger logger = Logger.getLogger(AbstractDataCollector.class); - private static boolean isToSave = false; protected StorageHelper getStorageHelper() { return storageHelper; @@ -45,7 +45,7 @@ public abstract class AbstractDataCollector implements DataStatistics { } public void add(final BehaviorResult behaviorResult) { - if (!isToSave) { + if (!Main.IS_TO_SAVE_DETAIL) { return; } Runnable runnable = new Runnable() { From e6ba50df5dc9fa82a28314d8fd08b7807e2b3cd8 Mon Sep 17 00:00:00 2001 From: coderfengyun Date: Mon, 16 Dec 2013 14:34:24 +0800 Subject: [PATCH 109/196] refactor and passs the tests --- src/main/java/org/bench4q/agent/Main.java | 7 ++++--- src/test/java/org/bench4q/agent/test/MainTest.java | 5 ++++- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/src/main/java/org/bench4q/agent/Main.java b/src/main/java/org/bench4q/agent/Main.java index 489600ca..159213f7 100644 --- a/src/main/java/org/bench4q/agent/Main.java +++ b/src/main/java/org/bench4q/agent/Main.java @@ -55,9 +55,10 @@ public class Main { + CONFIG_FILE_NAME)); Properties properties = new Properties(); properties.load(inputStream); - PORT_TO_SERVE = (Integer) properties.get("servePort"); - IS_TO_SAVE_DETAIL = (Boolean) properties - .get("isToSaveDetailResult"); + PORT_TO_SERVE = Integer.parseInt((String) properties + .get("servePort")); + IS_TO_SAVE_DETAIL = Boolean.parseBoolean((String) properties + .get("isToSaveDetailResult")); } catch (IOException e) { logger.error("There is an error when getPortToServe!"); } diff --git a/src/test/java/org/bench4q/agent/test/MainTest.java b/src/test/java/org/bench4q/agent/test/MainTest.java index deed2f07..c79fa7d1 100644 --- a/src/test/java/org/bench4q/agent/test/MainTest.java +++ b/src/test/java/org/bench4q/agent/test/MainTest.java @@ -22,7 +22,7 @@ public class MainTest { } @Test - public void getPortServeTest() throws IOException { + public void getPropertiesTest() throws IOException { FileInputStream inputStream = new FileInputStream(new File("configure" + System.getProperty("file.separator") + "agent-config.properties")); @@ -30,5 +30,8 @@ public class MainTest { properties.load(inputStream); assertEquals(6565, Integer.parseInt((String) properties.get("servePort"))); + assertEquals(false, Boolean.parseBoolean((String) properties + .get("isToSaveDetailResult"))); } + } From 4a4586205f0444054f7bdc2053d18d61dcf98c2a Mon Sep 17 00:00:00 2001 From: coderfengyun Date: Mon, 16 Dec 2013 22:58:27 +0800 Subject: [PATCH 110/196] now, i can save the detailResult with double buffer in Asynchronous way , and need more tests --- StorageTest/testInput.txt | 1 + pom.xml | 10 ++ .../impl/AbstractDataCollector.java | 16 --- .../org/bench4q/agent/storage/Buffer.java | 53 ++++++++ .../agent/storage/DoubleBufferStorage.java | 127 ++++++++++++++++++ src/main/resources/agent-config.properties | 5 - .../test/storage/TestDoubleBufferStorage.java | 108 +++++++++++++++ src/test/java/test-storage-context.xml | 10 ++ 8 files changed, 309 insertions(+), 21 deletions(-) create mode 100644 StorageTest/testInput.txt create mode 100644 src/main/java/org/bench4q/agent/storage/Buffer.java create mode 100644 src/main/java/org/bench4q/agent/storage/DoubleBufferStorage.java delete mode 100644 src/main/resources/agent-config.properties create mode 100644 src/test/java/org/bench4q/agent/test/storage/TestDoubleBufferStorage.java create mode 100644 src/test/java/test-storage-context.xml diff --git a/StorageTest/testInput.txt b/StorageTest/testInput.txt new file mode 100644 index 00000000..785f1382 --- /dev/null +++ b/StorageTest/testInput.txt @@ -0,0 +1 @@ +1Get1064text/html2013-12-16T10:01:02.620+08:00httpHttp6true2013-12-16T10:01:02.614+08:00200true \ No newline at end of file diff --git a/pom.xml b/pom.xml index eb773c80..703d59a6 100644 --- a/pom.xml +++ b/pom.xml @@ -52,6 +52,16 @@ bench4q-share 0.0.1-SNAPSHOT + + org.springframework + spring-core + 3.2.5.RELEASE + + + org.springframework + spring-test + 3.2.5.RELEASE + diff --git a/src/main/java/org/bench4q/agent/datacollector/impl/AbstractDataCollector.java b/src/main/java/org/bench4q/agent/datacollector/impl/AbstractDataCollector.java index 1b094d77..2b913db2 100644 --- a/src/main/java/org/bench4q/agent/datacollector/impl/AbstractDataCollector.java +++ b/src/main/java/org/bench4q/agent/datacollector/impl/AbstractDataCollector.java @@ -1,12 +1,9 @@ package org.bench4q.agent.datacollector.impl; -import java.net.InetAddress; -import java.net.UnknownHostException; import java.util.Map; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; -import org.apache.log4j.Logger; import org.bench4q.agent.Main; import org.bench4q.agent.api.model.BehaviorResultModel; import org.bench4q.agent.datacollector.interfaces.DataStatistics; @@ -16,7 +13,6 @@ import org.bench4q.agent.storage.StorageHelper; public abstract class AbstractDataCollector implements DataStatistics { protected StorageHelper storageHelper; - private Logger logger = Logger.getLogger(AbstractDataCollector.class); protected StorageHelper getStorageHelper() { return storageHelper; @@ -32,18 +28,6 @@ public abstract class AbstractDataCollector implements DataStatistics { StorageHelper.class)); } - protected String getHostName() { - InetAddress addr; - try { - addr = InetAddress.getLocalHost(); - return addr.getHostAddress().toString(); - } catch (UnknownHostException e) { - this.logger - .error("There is an exception when get hostName of this machine!"); - return null; - } - } - public void add(final BehaviorResult behaviorResult) { if (!Main.IS_TO_SAVE_DETAIL) { return; diff --git a/src/main/java/org/bench4q/agent/storage/Buffer.java b/src/main/java/org/bench4q/agent/storage/Buffer.java new file mode 100644 index 00000000..a01ac1ab --- /dev/null +++ b/src/main/java/org/bench4q/agent/storage/Buffer.java @@ -0,0 +1,53 @@ +package org.bench4q.agent.storage; + +public class Buffer { + private byte[] content; + private int currentPos; + private int totalSize; + + public byte[] getContent() { + return content; + } + + public void setContent(byte[] content) { + this.content = content; + } + + public int getCurrentPos() { + return currentPos; + } + + public void setCurrentPos(int currentPos) { + this.currentPos = currentPos; + } + + public int getTotalSize() { + return totalSize; + } + + public void setTotalSize(int totalSize) { + this.totalSize = totalSize; + } + + public static Buffer createBuffer(int totalSize) { + Buffer buffer = new Buffer(); + buffer.setContent(new byte[totalSize]); + buffer.setCurrentPos(0); + buffer.setTotalSize(totalSize); + return buffer; + } + + public int getRemainSize() { + return this.totalSize - this.currentPos; + } + + public void reset() { + this.setCurrentPos(0); + } + + void writeToCurrentBuffer(int size, byte[] cache) { + System.arraycopy(cache, 0, this.getContent(), this.getCurrentPos(), + size); + this.setCurrentPos(this.getCurrentPos() + size); + } +} diff --git a/src/main/java/org/bench4q/agent/storage/DoubleBufferStorage.java b/src/main/java/org/bench4q/agent/storage/DoubleBufferStorage.java new file mode 100644 index 00000000..89538937 --- /dev/null +++ b/src/main/java/org/bench4q/agent/storage/DoubleBufferStorage.java @@ -0,0 +1,127 @@ +package org.bench4q.agent.storage; + +import java.io.ByteArrayInputStream; +import java.nio.charset.Charset; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +import org.bench4q.agent.api.model.CleanTestResultModel; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +@Component +public class DoubleBufferStorage implements Storage { + private static Charset charset = Charset.forName("utf-8"); + private static int BUFFER_SIZE = 48 * 1024; + private List bufferList; + private int currentBufferIndex; + private LocalStorage localStorage; + public CleanTestResultModel forTest = new CleanTestResultModel(); + + public int getCurrentBufferIndex() { + return currentBufferIndex; + } + + private void setCurrentBufferIndex(int currentBuffer) { + this.currentBufferIndex = currentBuffer; + } + + public List getBufferList() { + + return bufferList; + + } + + private void setBufferList(List bufferList) { + this.bufferList = bufferList; + } + + public LocalStorage getLocalStorage() { + return localStorage; + } + + @Autowired + private void setLocalStorage(LocalStorage localStorage) { + this.localStorage = localStorage; + } + + public DoubleBufferStorage() { + this.setBufferList(new ArrayList()); + this.getBufferList().add(Buffer.createBuffer(BUFFER_SIZE)); + this.getBufferList().add(Buffer.createBuffer(BUFFER_SIZE)); + this.setCurrentBufferIndex(0); + } + + public String readFile(String path) { + return this.getLocalStorage().readFile(path); + } + + public boolean writeFile(String content, String path) { + ByteArrayInputStream inputStream = new ByteArrayInputStream( + content.getBytes(charset)); + int readLength = 1024; + int size = -1; + byte[] cache = new byte[readLength]; + while ((size = inputStream.read(cache, 0, readLength)) != -1) { + if (getCurrentBuffer().getRemainSize() <= readLength + size) { + doSaveAndChangeBuffer(regeneratePath(path)); + } + this.getCurrentBuffer().writeToCurrentBuffer(size, cache); + } + return true; + } + + public String regeneratePath(String path, int index) { + return path.substring(0, path.lastIndexOf(".")) + "_" + + getCurrentBufferIndex() + ".xml"; + } + + private String regeneratePath(String path) { + return regeneratePath(path, this.getCurrentBufferIndex()); + } + + private void doSaveAndChangeBuffer(final String path) { + final Buffer bufferUnderSave = this.getCurrentBuffer(); + final LocalStorage finalLocalStorage = this.getLocalStorage(); + byte[] meaningfulContent = new byte[bufferUnderSave.getCurrentPos()]; + final CleanTestResultModel signModel = forTest; + System.arraycopy(bufferUnderSave.getContent(), 0, meaningfulContent, 0, + bufferUnderSave.getCurrentPos()); + final String writeContent = new String(meaningfulContent); + // this.getLocalStorage().writeFile(writeContent, path); + // bufferUnderSave.reset(); + Runnable runnable = new Runnable() { + public void run() { + finalLocalStorage.writeFile(writeContent, path); + bufferUnderSave.reset(); + signModel.setSuccess(true); + } + }; + ExecutorService service = Executors.newFixedThreadPool(1); + service.execute(runnable); + service.shutdown(); + changBuffer(); + } + + private void changBuffer() { + int maxRemainSize = 0; + int maxRemainSizeBufferIndex = -1; + for (int i = 0; i < this.getBufferList().size(); ++i) { + if (this.getBufferList().get(i).getRemainSize() > maxRemainSize) { + maxRemainSize = this.getBufferList().get(i).getRemainSize(); + maxRemainSizeBufferIndex = i; + } + } + if (maxRemainSizeBufferIndex == -1) { + this.getBufferList().add(Buffer.createBuffer(BUFFER_SIZE)); + maxRemainSizeBufferIndex = this.getBufferList().size() - 1; + } + this.setCurrentBufferIndex(maxRemainSizeBufferIndex); + } + + public Buffer getCurrentBuffer() { + return this.getBufferList().get(this.getCurrentBufferIndex()); + } +} diff --git a/src/main/resources/agent-config.properties b/src/main/resources/agent-config.properties deleted file mode 100644 index 2bff7082..00000000 --- a/src/main/resources/agent-config.properties +++ /dev/null @@ -1,5 +0,0 @@ -# let the administrator can decide whether to save the detail result of behavior. -isToSaveDetailResult=false - -# let the administrator can decide which port the agent should use in running -servePort=6565 \ No newline at end of file diff --git a/src/test/java/org/bench4q/agent/test/storage/TestDoubleBufferStorage.java b/src/test/java/org/bench4q/agent/test/storage/TestDoubleBufferStorage.java new file mode 100644 index 00000000..a6f0c003 --- /dev/null +++ b/src/test/java/org/bench4q/agent/test/storage/TestDoubleBufferStorage.java @@ -0,0 +1,108 @@ +package org.bench4q.agent.test.storage; + +import static org.junit.Assert.*; + +import java.io.File; +import java.io.IOException; + +import org.bench4q.agent.storage.DoubleBufferStorage; +import org.junit.After; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(locations = { "classpath:test-storage-context.xml" }) +public class TestDoubleBufferStorage { + private DoubleBufferStorage doubleBufferStorage; + private static String SAVE_DIR = "StorageTest" + + System.getProperty("file.separator"); + private static final String INPUT_FILE_PATH = SAVE_DIR + "testInput.txt"; + private static String SAVE_PATH = SAVE_DIR + "test.txt"; + + private DoubleBufferStorage getDoubleBufferStorage() { + return doubleBufferStorage; + } + + @Autowired + private void setDoubleBufferStorage(DoubleBufferStorage doubleBufferStorage) { + this.doubleBufferStorage = doubleBufferStorage; + } + + public TestDoubleBufferStorage() throws IOException { + File dir = new File(SAVE_DIR); + if (!dir.exists()) { + dir.mkdirs(); + } + File outPutFile = new File(SAVE_PATH); + if (!outPutFile.exists()) { + outPutFile.createNewFile(); + } + File inputFile = new File(INPUT_FILE_PATH); + if (!inputFile.exists()) { + inputFile.createNewFile(); + } + } + + @After + public void cleanUp() { + for (int i = 0; i < 2; i++) { + String realSavePathString = this.getDoubleBufferStorage() + .regeneratePath(SAVE_PATH, i); + File inputFile = new File(realSavePathString); + if (inputFile.exists()) { + inputFile.delete(); + } + } + } + + @Test + public void testWriteWithLittleContent() { + this.getDoubleBufferStorage().writeFile("test", SAVE_PATH); + assertEquals(48 * 1024 - 4, this.getDoubleBufferStorage() + .getCurrentBuffer().getRemainSize()); + for (int i = 0; i < this.getDoubleBufferStorage().getBufferList() + .size() + && i != this.getDoubleBufferStorage().getCurrentBufferIndex(); i++) { + assertEquals(48 * 1024, this.getDoubleBufferStorage() + .getBufferList().get(i).getRemainSize()); + } + } + + @Test + public void testWriteWithJustLargerThanOneBufferContent() + throws InterruptedException { + String realSavePathString = this.getDoubleBufferStorage() + .regeneratePath(SAVE_PATH, + this.getDoubleBufferStorage().getCurrentBufferIndex()); + doWriteFile(95); + while (!this.getDoubleBufferStorage().forTest.isSuccess()) { + Thread.sleep(1000); + } + String readContent = this.getDoubleBufferStorage().readFile( + realSavePathString); + assertTrue(readContent.length() <= 48 * 1024); + assertTrue(readContent.length() >= 46 * 1024); + assertTrue(readContent.indexOf("encoding") > 0); + System.out.println(this.getDoubleBufferStorage().getCurrentBuffer() + .getCurrentPos()); + assertTrue(this.getDoubleBufferStorage().getCurrentBuffer() + .getCurrentPos() == 1563); + } + + private void doWriteFile(int size) { + for (int i = 0; i < size; i++) { + String saveContent = this.getDoubleBufferStorage().readFile( + INPUT_FILE_PATH); + this.getDoubleBufferStorage().writeFile(saveContent, SAVE_PATH); + } + } + + @Test + public void testWriteWithJustLargerThanTwoBufferContent() { + doWriteFile(92 * 2 + 2); + + } +} diff --git a/src/test/java/test-storage-context.xml b/src/test/java/test-storage-context.xml new file mode 100644 index 00000000..7c690e9a --- /dev/null +++ b/src/test/java/test-storage-context.xml @@ -0,0 +1,10 @@ + + + + + From efdd0583eaaf45b3119ecee6e25bc497149c0ea0 Mon Sep 17 00:00:00 2001 From: coderfengyun Date: Tue, 17 Dec 2013 09:26:39 +0800 Subject: [PATCH 111/196] edit the clean up in test --- .../bench4q/agent/storage/DoubleBufferStorage.java | 9 +++------ .../agent/test/storage/TestDoubleBufferStorage.java | 12 ++++++++---- 2 files changed, 11 insertions(+), 10 deletions(-) diff --git a/src/main/java/org/bench4q/agent/storage/DoubleBufferStorage.java b/src/main/java/org/bench4q/agent/storage/DoubleBufferStorage.java index 89538937..acdfb26c 100644 --- a/src/main/java/org/bench4q/agent/storage/DoubleBufferStorage.java +++ b/src/main/java/org/bench4q/agent/storage/DoubleBufferStorage.java @@ -74,8 +74,7 @@ public class DoubleBufferStorage implements Storage { } public String regeneratePath(String path, int index) { - return path.substring(0, path.lastIndexOf(".")) + "_" - + getCurrentBufferIndex() + ".xml"; + return path.substring(0, path.lastIndexOf(".")) + "_" + index + ".xml"; } private String regeneratePath(String path) { @@ -84,17 +83,15 @@ public class DoubleBufferStorage implements Storage { private void doSaveAndChangeBuffer(final String path) { final Buffer bufferUnderSave = this.getCurrentBuffer(); - final LocalStorage finalLocalStorage = this.getLocalStorage(); byte[] meaningfulContent = new byte[bufferUnderSave.getCurrentPos()]; final CleanTestResultModel signModel = forTest; System.arraycopy(bufferUnderSave.getContent(), 0, meaningfulContent, 0, bufferUnderSave.getCurrentPos()); final String writeContent = new String(meaningfulContent); - // this.getLocalStorage().writeFile(writeContent, path); - // bufferUnderSave.reset(); + Runnable runnable = new Runnable() { public void run() { - finalLocalStorage.writeFile(writeContent, path); + getLocalStorage().writeFile(writeContent, path); bufferUnderSave.reset(); signModel.setSuccess(true); } diff --git a/src/test/java/org/bench4q/agent/test/storage/TestDoubleBufferStorage.java b/src/test/java/org/bench4q/agent/test/storage/TestDoubleBufferStorage.java index a6f0c003..8d6f9c05 100644 --- a/src/test/java/org/bench4q/agent/test/storage/TestDoubleBufferStorage.java +++ b/src/test/java/org/bench4q/agent/test/storage/TestDoubleBufferStorage.java @@ -48,12 +48,16 @@ public class TestDoubleBufferStorage { @After public void cleanUp() { - for (int i = 0; i < 2; i++) { + File file = new File(SAVE_DIR + "test.txt"); + if (file.exists()) { + file.delete(); + } + for (int i = 0; i < 2; ++i) { String realSavePathString = this.getDoubleBufferStorage() .regeneratePath(SAVE_PATH, i); - File inputFile = new File(realSavePathString); - if (inputFile.exists()) { - inputFile.delete(); + File output = new File(realSavePathString); + if (output.exists()) { + output.delete(); } } } From c92e86ab9baf23a1f983baa210bd207b4c79e2f7 Mon Sep 17 00:00:00 2001 From: coderfengyun Date: Tue, 17 Dec 2013 10:06:59 +0800 Subject: [PATCH 112/196] refactor --- .../org/bench4q/agent/storage/Buffer.java | 4 ++ .../agent/storage/DoubleBufferStorage.java | 43 +++++++++++-------- .../test/storage/TestDoubleBufferStorage.java | 16 +++++++ 3 files changed, 46 insertions(+), 17 deletions(-) diff --git a/src/main/java/org/bench4q/agent/storage/Buffer.java b/src/main/java/org/bench4q/agent/storage/Buffer.java index a01ac1ab..516c9212 100644 --- a/src/main/java/org/bench4q/agent/storage/Buffer.java +++ b/src/main/java/org/bench4q/agent/storage/Buffer.java @@ -45,6 +45,10 @@ public class Buffer { this.setCurrentPos(0); } + public void setFull() { + this.setCurrentPos(this.getTotalSize()); + } + void writeToCurrentBuffer(int size, byte[] cache) { System.arraycopy(cache, 0, this.getContent(), this.getCurrentPos(), size); diff --git a/src/main/java/org/bench4q/agent/storage/DoubleBufferStorage.java b/src/main/java/org/bench4q/agent/storage/DoubleBufferStorage.java index acdfb26c..6e2116a5 100644 --- a/src/main/java/org/bench4q/agent/storage/DoubleBufferStorage.java +++ b/src/main/java/org/bench4q/agent/storage/DoubleBufferStorage.java @@ -13,6 +13,7 @@ import org.springframework.stereotype.Component; @Component public class DoubleBufferStorage implements Storage { + private static final int THRESHOLD = 1024; private static Charset charset = Charset.forName("utf-8"); private static int BUFFER_SIZE = 48 * 1024; private List bufferList; @@ -24,7 +25,7 @@ public class DoubleBufferStorage implements Storage { return currentBufferIndex; } - private void setCurrentBufferIndex(int currentBuffer) { + public void setCurrentBufferIndex(int currentBuffer) { this.currentBufferIndex = currentBuffer; } @@ -61,18 +62,22 @@ public class DoubleBufferStorage implements Storage { public boolean writeFile(String content, String path) { ByteArrayInputStream inputStream = new ByteArrayInputStream( content.getBytes(charset)); - int readLength = 1024; int size = -1; - byte[] cache = new byte[readLength]; - while ((size = inputStream.read(cache, 0, readLength)) != -1) { - if (getCurrentBuffer().getRemainSize() <= readLength + size) { - doSaveAndChangeBuffer(regeneratePath(path)); + byte[] cache = new byte[THRESHOLD]; + while ((size = inputStream.read(cache, 0, THRESHOLD)) != -1) { + if (isCurrentBufferFull(size)) { + doSave(regeneratePath(path)); + changeToTheMaxRemainBuffer(); } this.getCurrentBuffer().writeToCurrentBuffer(size, cache); } return true; } + private boolean isCurrentBufferFull(int size) { + return getCurrentBuffer().getRemainSize() <= THRESHOLD + size; + } + public String regeneratePath(String path, int index) { return path.substring(0, path.lastIndexOf(".")) + "_" + index + ".xml"; } @@ -81,31 +86,35 @@ public class DoubleBufferStorage implements Storage { return regeneratePath(path, this.getCurrentBufferIndex()); } - private void doSaveAndChangeBuffer(final String path) { + private void doSave(final String path) { final Buffer bufferUnderSave = this.getCurrentBuffer(); - byte[] meaningfulContent = new byte[bufferUnderSave.getCurrentPos()]; - final CleanTestResultModel signModel = forTest; - System.arraycopy(bufferUnderSave.getContent(), 0, meaningfulContent, 0, - bufferUnderSave.getCurrentPos()); - final String writeContent = new String(meaningfulContent); - + final String writeContent = this.getMeaningfulContent(); Runnable runnable = new Runnable() { public void run() { getLocalStorage().writeFile(writeContent, path); bufferUnderSave.reset(); - signModel.setSuccess(true); + forTest.setSuccess(true); } }; ExecutorService service = Executors.newFixedThreadPool(1); service.execute(runnable); service.shutdown(); - changBuffer(); + } - private void changBuffer() { - int maxRemainSize = 0; + private String getMeaningfulContent() { + byte[] meaningfulContent = new byte[getCurrentBuffer().getCurrentPos()]; + System.arraycopy(getCurrentBuffer().getContent(), 0, meaningfulContent, + 0, getCurrentBuffer().getCurrentPos()); + return new String(meaningfulContent); + } + + public void changeToTheMaxRemainBuffer() { + int maxRemainSize = 2 * THRESHOLD; int maxRemainSizeBufferIndex = -1; for (int i = 0; i < this.getBufferList().size(); ++i) { + System.out.println(i + " remain : " + + this.getBufferList().get(i).getRemainSize()); if (this.getBufferList().get(i).getRemainSize() > maxRemainSize) { maxRemainSize = this.getBufferList().get(i).getRemainSize(); maxRemainSizeBufferIndex = i; diff --git a/src/test/java/org/bench4q/agent/test/storage/TestDoubleBufferStorage.java b/src/test/java/org/bench4q/agent/test/storage/TestDoubleBufferStorage.java index 8d6f9c05..937b5d4f 100644 --- a/src/test/java/org/bench4q/agent/test/storage/TestDoubleBufferStorage.java +++ b/src/test/java/org/bench4q/agent/test/storage/TestDoubleBufferStorage.java @@ -92,6 +92,8 @@ public class TestDoubleBufferStorage { assertTrue(readContent.indexOf("encoding") > 0); System.out.println(this.getDoubleBufferStorage().getCurrentBuffer() .getCurrentPos()); + System.out.println(this.getDoubleBufferStorage() + .getCurrentBufferIndex()); assertTrue(this.getDoubleBufferStorage().getCurrentBuffer() .getCurrentPos() == 1563); } @@ -109,4 +111,18 @@ public class TestDoubleBufferStorage { doWriteFile(92 * 2 + 2); } + + @Test + public void testChangeBuffer() { + this.getDoubleBufferStorage().getBufferList().get(0) + .setCurrentPos(48 * 1024 - 1220); + this.getDoubleBufferStorage().getBufferList().get(1).setCurrentPos(0); + this.getDoubleBufferStorage().setCurrentBufferIndex(0); + this.getDoubleBufferStorage().changeToTheMaxRemainBuffer(); + assertEquals(1220, this.getDoubleBufferStorage().getBufferList().get(0) + .getRemainSize()); + assertEquals(48 * 1024, this.getDoubleBufferStorage().getBufferList() + .get(1).getRemainSize()); + assertEquals(1, this.getDoubleBufferStorage().getCurrentBufferIndex()); + } } From 4daa76633e7f24b40c3707472c8e96edb17280e1 Mon Sep 17 00:00:00 2001 From: coderfengyun Date: Tue, 17 Dec 2013 14:22:28 +0800 Subject: [PATCH 113/196] refactor the way to access to private methods --- .../agent/storage/DoubleBufferStorage.java | 16 ++- .../test/storage/TestDoubleBufferStorage.java | 119 +++++++++++++----- 2 files changed, 92 insertions(+), 43 deletions(-) diff --git a/src/main/java/org/bench4q/agent/storage/DoubleBufferStorage.java b/src/main/java/org/bench4q/agent/storage/DoubleBufferStorage.java index 6e2116a5..1f3c947a 100644 --- a/src/main/java/org/bench4q/agent/storage/DoubleBufferStorage.java +++ b/src/main/java/org/bench4q/agent/storage/DoubleBufferStorage.java @@ -12,7 +12,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Component -public class DoubleBufferStorage implements Storage { +public class DoubleBufferStorage { private static final int THRESHOLD = 1024; private static Charset charset = Charset.forName("utf-8"); private static int BUFFER_SIZE = 48 * 1024; @@ -21,25 +21,23 @@ public class DoubleBufferStorage implements Storage { private LocalStorage localStorage; public CleanTestResultModel forTest = new CleanTestResultModel(); - public int getCurrentBufferIndex() { + private int getCurrentBufferIndex() { return currentBufferIndex; } - public void setCurrentBufferIndex(int currentBuffer) { + private void setCurrentBufferIndex(int currentBuffer) { this.currentBufferIndex = currentBuffer; } - public List getBufferList() { - + private List getBufferList() { return bufferList; - } private void setBufferList(List bufferList) { this.bufferList = bufferList; } - public LocalStorage getLocalStorage() { + private LocalStorage getLocalStorage() { return localStorage; } @@ -109,7 +107,7 @@ public class DoubleBufferStorage implements Storage { return new String(meaningfulContent); } - public void changeToTheMaxRemainBuffer() { + private void changeToTheMaxRemainBuffer() { int maxRemainSize = 2 * THRESHOLD; int maxRemainSizeBufferIndex = -1; for (int i = 0; i < this.getBufferList().size(); ++i) { @@ -127,7 +125,7 @@ public class DoubleBufferStorage implements Storage { this.setCurrentBufferIndex(maxRemainSizeBufferIndex); } - public Buffer getCurrentBuffer() { + private Buffer getCurrentBuffer() { return this.getBufferList().get(this.getCurrentBufferIndex()); } } diff --git a/src/test/java/org/bench4q/agent/test/storage/TestDoubleBufferStorage.java b/src/test/java/org/bench4q/agent/test/storage/TestDoubleBufferStorage.java index 937b5d4f..148e6df9 100644 --- a/src/test/java/org/bench4q/agent/test/storage/TestDoubleBufferStorage.java +++ b/src/test/java/org/bench4q/agent/test/storage/TestDoubleBufferStorage.java @@ -4,12 +4,17 @@ import static org.junit.Assert.*; import java.io.File; import java.io.IOException; +import java.lang.reflect.Method; +import java.util.List; +import org.bench4q.agent.storage.Buffer; import org.bench4q.agent.storage.DoubleBufferStorage; import org.junit.After; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.annotation.DirtiesContext.ClassMode; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @@ -52,7 +57,7 @@ public class TestDoubleBufferStorage { if (file.exists()) { file.delete(); } - for (int i = 0; i < 2; ++i) { + for (int i = 0; i < 4; ++i) { String realSavePathString = this.getDoubleBufferStorage() .regeneratePath(SAVE_PATH, i); File output = new File(realSavePathString); @@ -62,25 +67,29 @@ public class TestDoubleBufferStorage { } } + @SuppressWarnings("unchecked") @Test - public void testWriteWithLittleContent() { + public void testWriteWithLittleContent() throws Exception { this.getDoubleBufferStorage().writeFile("test", SAVE_PATH); - assertEquals(48 * 1024 - 4, this.getDoubleBufferStorage() - .getCurrentBuffer().getRemainSize()); - for (int i = 0; i < this.getDoubleBufferStorage().getBufferList() - .size() - && i != this.getDoubleBufferStorage().getCurrentBufferIndex(); i++) { - assertEquals(48 * 1024, this.getDoubleBufferStorage() - .getBufferList().get(i).getRemainSize()); + assertEquals(48 * 1024 - 4, ((Buffer) this.invokePrivateMethod( + "getCurrentBuffer", null, null)).getRemainSize()); + List buffers = ((List) this.invokePrivateMethod( + "getBufferList", null, null)); + for (int i = 0; i < buffers.size() + && i != (Integer) this.invokePrivateMethod( + "getCurrentBufferIndex", null, null); i++) { + assertEquals(48 * 1024, buffers.get(i).getRemainSize()); } } @Test - public void testWriteWithJustLargerThanOneBufferContent() - throws InterruptedException { + @DirtiesContext(classMode = ClassMode.AFTER_EACH_TEST_METHOD) + public void testWriteWithJustLargerThanOneBufferContent() throws Exception { String realSavePathString = this.getDoubleBufferStorage() - .regeneratePath(SAVE_PATH, - this.getDoubleBufferStorage().getCurrentBufferIndex()); + .regeneratePath( + SAVE_PATH, + (Integer) this.invokePrivateMethod( + "getCurrentBufferIndex", null, null)); doWriteFile(95); while (!this.getDoubleBufferStorage().forTest.isSuccess()) { Thread.sleep(1000); @@ -90,39 +99,81 @@ public class TestDoubleBufferStorage { assertTrue(readContent.length() <= 48 * 1024); assertTrue(readContent.length() >= 46 * 1024); assertTrue(readContent.indexOf("encoding") > 0); - System.out.println(this.getDoubleBufferStorage().getCurrentBuffer() - .getCurrentPos()); - System.out.println(this.getDoubleBufferStorage() - .getCurrentBufferIndex()); - assertTrue(this.getDoubleBufferStorage().getCurrentBuffer() - .getCurrentPos() == 1563); + Buffer currentBuffer = (Buffer) this.invokePrivateMethod( + "getCurrentBuffer", null, null); + System.out.println(currentBuffer.getCurrentPos()); + System.out.println((Integer) this.invokePrivateMethod( + "getCurrentBufferIndex", null, null)); + assertTrue(currentBuffer.getCurrentPos() == 1563); } private void doWriteFile(int size) { + String saveContent = this.getDoubleBufferStorage().readFile( + INPUT_FILE_PATH); for (int i = 0; i < size; i++) { - String saveContent = this.getDoubleBufferStorage().readFile( - INPUT_FILE_PATH); this.getDoubleBufferStorage().writeFile(saveContent, SAVE_PATH); } } @Test - public void testWriteWithJustLargerThanTwoBufferContent() { + @DirtiesContext(classMode = ClassMode.AFTER_EACH_TEST_METHOD) + public void testWriteWithJustLargerThanTwoBufferContent() + throws InterruptedException { doWriteFile(92 * 2 + 2); - + while (!this.getDoubleBufferStorage().forTest.isSuccess()) { + Thread.sleep(1000); + } + assertEquals(47932 * 2, getResultLength()); } @Test - public void testChangeBuffer() { - this.getDoubleBufferStorage().getBufferList().get(0) - .setCurrentPos(48 * 1024 - 1220); - this.getDoubleBufferStorage().getBufferList().get(1).setCurrentPos(0); - this.getDoubleBufferStorage().setCurrentBufferIndex(0); - this.getDoubleBufferStorage().changeToTheMaxRemainBuffer(); - assertEquals(1220, this.getDoubleBufferStorage().getBufferList().get(0) - .getRemainSize()); - assertEquals(48 * 1024, this.getDoubleBufferStorage().getBufferList() - .get(1).getRemainSize()); - assertEquals(1, this.getDoubleBufferStorage().getCurrentBufferIndex()); + @DirtiesContext(classMode = ClassMode.AFTER_EACH_TEST_METHOD) + public void testWriteContentLargerThanThree() throws InterruptedException { + doWriteFile(92 * 3 + 2); + while (!this.getDoubleBufferStorage().forTest.isSuccess()) { + Thread.sleep(1000); + } + int resultLength = getResultLength(); + assertEquals(47932 * 3, resultLength); + } + + private int getResultLength() { + int resultLength = 0; + for (int i = 0; i < 4; i++) { + String path = this.getDoubleBufferStorage().regeneratePath( + SAVE_PATH, i); + if (!new File(path).exists()) { + continue; + } + String readContentString = this.getDoubleBufferStorage().readFile( + path); + resultLength += readContentString.length(); + } + return resultLength; + } + + @Test + public void testChangeBuffer() throws Exception { + @SuppressWarnings("unchecked") + List buffers = (List) this.invokePrivateMethod( + "getBufferList", null, null); + buffers.get(0).setCurrentPos(48 * 1024 - 1220); + buffers.get(1).setCurrentPos(0); + this.invokePrivateMethod("setCurrentBufferIndex", + new Class[] { int.class }, new Object[] { 0 }); + this.invokePrivateMethod("changeToTheMaxRemainBuffer", null, null); + + assertEquals(1220, buffers.get(0).getRemainSize()); + assertEquals(48 * 1024, buffers.get(1).getRemainSize()); + assertEquals(1, + this.invokePrivateMethod("getCurrentBufferIndex", null, null)); + } + + public Object invokePrivateMethod(String methodName, + Class[] paramClasses, Object[] params) throws Exception { + Class class1 = this.getDoubleBufferStorage().getClass(); + Method method = class1.getDeclaredMethod(methodName, paramClasses); + method.setAccessible(true); + return method.invoke(this.getDoubleBufferStorage(), params); } } From c4195d93da0649d000f9599d6e0fd76e30e7106a Mon Sep 17 00:00:00 2001 From: coderfengyun Date: Tue, 17 Dec 2013 22:13:29 +0800 Subject: [PATCH 114/196] edit the function of readFile to read files with the specific file prefix, and add the test and pass it. --- StorageTest/test_123.txt | 1 + .../agent/storage/DoubleBufferStorage.java | 38 ++++++++++++++++--- .../test/storage/TestDoubleBufferStorage.java | 22 +++++++---- 3 files changed, 47 insertions(+), 14 deletions(-) create mode 100644 StorageTest/test_123.txt diff --git a/StorageTest/test_123.txt b/StorageTest/test_123.txt new file mode 100644 index 00000000..30d74d25 --- /dev/null +++ b/StorageTest/test_123.txt @@ -0,0 +1 @@ +test \ No newline at end of file diff --git a/src/main/java/org/bench4q/agent/storage/DoubleBufferStorage.java b/src/main/java/org/bench4q/agent/storage/DoubleBufferStorage.java index 1f3c947a..a9c19d66 100644 --- a/src/main/java/org/bench4q/agent/storage/DoubleBufferStorage.java +++ b/src/main/java/org/bench4q/agent/storage/DoubleBufferStorage.java @@ -1,6 +1,8 @@ package org.bench4q.agent.storage; import java.io.ByteArrayInputStream; +import java.io.File; +import java.io.FilenameFilter; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.List; @@ -53,8 +55,28 @@ public class DoubleBufferStorage { this.setCurrentBufferIndex(0); } - public String readFile(String path) { - return this.getLocalStorage().readFile(path); + public String readFiles(String pathPrefix) { + int pos = pathPrefix.lastIndexOf(System.getProperty("file.separator")); + String dirPath = pathPrefix.substring(0, pos); + final String prefix = pathPrefix.substring(pos + 1); + String result = new String(); + + File dirFile = new File(dirPath); + if (!dirFile.exists()) { + return ""; + } + File[] files = dirFile.listFiles(new FilenameFilter() { + public boolean accept(File dir, String name) { + return name.contains(prefix); + } + }); + for (File file : files) { + if (!file.exists()) { + continue; + } + result += this.getLocalStorage().readFile(file.getAbsolutePath()); + } + return result; } public boolean writeFile(String content, String path) { @@ -64,7 +86,7 @@ public class DoubleBufferStorage { byte[] cache = new byte[THRESHOLD]; while ((size = inputStream.read(cache, 0, THRESHOLD)) != -1) { if (isCurrentBufferFull(size)) { - doSave(regeneratePath(path)); + doSave(calculateSavePath(path)); changeToTheMaxRemainBuffer(); } this.getCurrentBuffer().writeToCurrentBuffer(size, cache); @@ -76,12 +98,12 @@ public class DoubleBufferStorage { return getCurrentBuffer().getRemainSize() <= THRESHOLD + size; } - public String regeneratePath(String path, int index) { + public String calculateSavePath(String path, int index) { return path.substring(0, path.lastIndexOf(".")) + "_" + index + ".xml"; } - private String regeneratePath(String path) { - return regeneratePath(path, this.getCurrentBufferIndex()); + private String calculateSavePath(String path) { + return calculateSavePath(path, this.getCurrentBufferIndex()); } private void doSave(final String path) { @@ -128,4 +150,8 @@ public class DoubleBufferStorage { private Buffer getCurrentBuffer() { return this.getBufferList().get(this.getCurrentBufferIndex()); } + + public void flush() { + + } } diff --git a/src/test/java/org/bench4q/agent/test/storage/TestDoubleBufferStorage.java b/src/test/java/org/bench4q/agent/test/storage/TestDoubleBufferStorage.java index 148e6df9..10f85c90 100644 --- a/src/test/java/org/bench4q/agent/test/storage/TestDoubleBufferStorage.java +++ b/src/test/java/org/bench4q/agent/test/storage/TestDoubleBufferStorage.java @@ -6,7 +6,6 @@ import java.io.File; import java.io.IOException; import java.lang.reflect.Method; import java.util.List; - import org.bench4q.agent.storage.Buffer; import org.bench4q.agent.storage.DoubleBufferStorage; import org.junit.After; @@ -59,7 +58,7 @@ public class TestDoubleBufferStorage { } for (int i = 0; i < 4; ++i) { String realSavePathString = this.getDoubleBufferStorage() - .regeneratePath(SAVE_PATH, i); + .calculateSavePath(SAVE_PATH, i); File output = new File(realSavePathString); if (output.exists()) { output.delete(); @@ -86,7 +85,7 @@ public class TestDoubleBufferStorage { @DirtiesContext(classMode = ClassMode.AFTER_EACH_TEST_METHOD) public void testWriteWithJustLargerThanOneBufferContent() throws Exception { String realSavePathString = this.getDoubleBufferStorage() - .regeneratePath( + .calculateSavePath( SAVE_PATH, (Integer) this.invokePrivateMethod( "getCurrentBufferIndex", null, null)); @@ -94,7 +93,7 @@ public class TestDoubleBufferStorage { while (!this.getDoubleBufferStorage().forTest.isSuccess()) { Thread.sleep(1000); } - String readContent = this.getDoubleBufferStorage().readFile( + String readContent = this.getDoubleBufferStorage().readFiles( realSavePathString); assertTrue(readContent.length() <= 48 * 1024); assertTrue(readContent.length() >= 46 * 1024); @@ -108,7 +107,7 @@ public class TestDoubleBufferStorage { } private void doWriteFile(int size) { - String saveContent = this.getDoubleBufferStorage().readFile( + String saveContent = this.getDoubleBufferStorage().readFiles( INPUT_FILE_PATH); for (int i = 0; i < size; i++) { this.getDoubleBufferStorage().writeFile(saveContent, SAVE_PATH); @@ -140,12 +139,12 @@ public class TestDoubleBufferStorage { private int getResultLength() { int resultLength = 0; for (int i = 0; i < 4; i++) { - String path = this.getDoubleBufferStorage().regeneratePath( + String path = this.getDoubleBufferStorage().calculateSavePath( SAVE_PATH, i); if (!new File(path).exists()) { continue; } - String readContentString = this.getDoubleBufferStorage().readFile( + String readContentString = this.getDoubleBufferStorage().readFiles( path); resultLength += readContentString.length(); } @@ -169,11 +168,18 @@ public class TestDoubleBufferStorage { this.invokePrivateMethod("getCurrentBufferIndex", null, null)); } - public Object invokePrivateMethod(String methodName, + private Object invokePrivateMethod(String methodName, Class[] paramClasses, Object[] params) throws Exception { Class class1 = this.getDoubleBufferStorage().getClass(); Method method = class1.getDeclaredMethod(methodName, paramClasses); method.setAccessible(true); return method.invoke(this.getDoubleBufferStorage(), params); } + + @Test + public void testReadFiles() { + String content = this.getDoubleBufferStorage().readFiles( + INPUT_FILE_PATH); + assertEquals(content.length(), 521); + } } From 098fb8a08cd6022549d73287b8fe3dc193e80a2e Mon Sep 17 00:00:00 2001 From: coderfengyun Date: Wed, 18 Dec 2013 15:26:46 +0800 Subject: [PATCH 115/196] add a test case with frame --- .../agent/test/plugin/TestHttpPlugin.java | 32 +++++++++++++++++++ .../test-storage-context.xml | 0 2 files changed, 32 insertions(+) create mode 100644 src/test/java/org/bench4q/agent/test/plugin/TestHttpPlugin.java rename src/test/{java => resources}/test-storage-context.xml (100%) diff --git a/src/test/java/org/bench4q/agent/test/plugin/TestHttpPlugin.java b/src/test/java/org/bench4q/agent/test/plugin/TestHttpPlugin.java new file mode 100644 index 00000000..cd233400 --- /dev/null +++ b/src/test/java/org/bench4q/agent/test/plugin/TestHttpPlugin.java @@ -0,0 +1,32 @@ +package org.bench4q.agent.test.plugin; + +import org.bench4q.agent.plugin.basic.HttpPlugin; +import org.bench4q.agent.plugin.result.PluginReturn; +import org.junit.Test; + +import static org.junit.Assert.*; + +public class TestHttpPlugin { + private HttpPlugin httpPlugin; + + private HttpPlugin getHttpPlugin() { + return httpPlugin; + } + + private void setHttpPlugin(HttpPlugin httpPlugin) { + this.httpPlugin = httpPlugin; + } + + public TestHttpPlugin() { + this.setHttpPlugin(new HttpPlugin()); + } + + @Test + public void testGet() { + PluginReturn return1 = this + .getHttpPlugin() + .get("http://www.baidu.com/su?wd=&cb=window.bdsug.sugPreRequest&sid=4382_1435_4261_4588&t=1387332769213"); + assertTrue(return1.isSuccess()); + } + +} diff --git a/src/test/java/test-storage-context.xml b/src/test/resources/test-storage-context.xml similarity index 100% rename from src/test/java/test-storage-context.xml rename to src/test/resources/test-storage-context.xml From 7d7e213370110f530bd1732b446a37d27f776399 Mon Sep 17 00:00:00 2001 From: coderfengyun Date: Wed, 18 Dec 2013 20:15:12 +0800 Subject: [PATCH 116/196] refacotr --- .../test/storage/TestDoubleBufferStorage.java | 67 ++++++++++++------- 1 file changed, 43 insertions(+), 24 deletions(-) diff --git a/src/test/java/org/bench4q/agent/test/storage/TestDoubleBufferStorage.java b/src/test/java/org/bench4q/agent/test/storage/TestDoubleBufferStorage.java index 10f85c90..f07fe2b2 100644 --- a/src/test/java/org/bench4q/agent/test/storage/TestDoubleBufferStorage.java +++ b/src/test/java/org/bench4q/agent/test/storage/TestDoubleBufferStorage.java @@ -4,10 +4,11 @@ import static org.junit.Assert.*; import java.io.File; import java.io.IOException; -import java.lang.reflect.Method; import java.util.List; + import org.bench4q.agent.storage.Buffer; import org.bench4q.agent.storage.DoubleBufferStorage; +import org.bench4q.share.helper.TestHelper; import org.junit.After; import org.junit.Test; import org.junit.runner.RunWith; @@ -70,13 +71,19 @@ public class TestDoubleBufferStorage { @Test public void testWriteWithLittleContent() throws Exception { this.getDoubleBufferStorage().writeFile("test", SAVE_PATH); - assertEquals(48 * 1024 - 4, ((Buffer) this.invokePrivateMethod( - "getCurrentBuffer", null, null)).getRemainSize()); - List buffers = ((List) this.invokePrivateMethod( - "getBufferList", null, null)); + assertEquals( + 48 * 1024 - 4, + ((Buffer) invokePrivateMethod(this.getDoubleBufferStorage() + .getClass(), this.getDoubleBufferStorage(), + "getCurrentBuffer", null, null)).getRemainSize()); + List buffers = ((List) invokePrivateMethod(this + .getDoubleBufferStorage().getClass(), + this.getDoubleBufferStorage(), "getBufferList", null, null)); for (int i = 0; i < buffers.size() - && i != (Integer) this.invokePrivateMethod( - "getCurrentBufferIndex", null, null); i++) { + && i != (Integer) invokePrivateMethod(this + .getDoubleBufferStorage().getClass(), + this.getDoubleBufferStorage(), "getCurrentBufferIndex", + null, null); i++) { assertEquals(48 * 1024, buffers.get(i).getRemainSize()); } } @@ -87,7 +94,9 @@ public class TestDoubleBufferStorage { String realSavePathString = this.getDoubleBufferStorage() .calculateSavePath( SAVE_PATH, - (Integer) this.invokePrivateMethod( + (Integer) invokePrivateMethod(this + .getDoubleBufferStorage().getClass(), this + .getDoubleBufferStorage(), "getCurrentBufferIndex", null, null)); doWriteFile(95); while (!this.getDoubleBufferStorage().forTest.isSuccess()) { @@ -98,11 +107,15 @@ public class TestDoubleBufferStorage { assertTrue(readContent.length() <= 48 * 1024); assertTrue(readContent.length() >= 46 * 1024); assertTrue(readContent.indexOf("encoding") > 0); - Buffer currentBuffer = (Buffer) this.invokePrivateMethod( - "getCurrentBuffer", null, null); + Buffer currentBuffer = (Buffer) invokePrivateMethod(this + .getDoubleBufferStorage().getClass(), + this.getDoubleBufferStorage(), "getCurrentBuffer", null, null); System.out.println(currentBuffer.getCurrentPos()); - System.out.println((Integer) this.invokePrivateMethod( - "getCurrentBufferIndex", null, null)); + System.out + .println((Integer) invokePrivateMethod(this + .getDoubleBufferStorage().getClass(), this + .getDoubleBufferStorage(), "getCurrentBufferIndex", + null, null)); assertTrue(currentBuffer.getCurrentPos() == 1563); } @@ -154,26 +167,32 @@ public class TestDoubleBufferStorage { @Test public void testChangeBuffer() throws Exception { @SuppressWarnings("unchecked") - List buffers = (List) this.invokePrivateMethod( - "getBufferList", null, null); + List buffers = (List) invokePrivateMethod(this + .getDoubleBufferStorage().getClass(), + this.getDoubleBufferStorage(), "getBufferList", null, null); buffers.get(0).setCurrentPos(48 * 1024 - 1220); buffers.get(1).setCurrentPos(0); - this.invokePrivateMethod("setCurrentBufferIndex", + invokePrivateMethod(getDoubleBufferStorage().getClass(), + this.getDoubleBufferStorage(), "setCurrentBufferIndex", new Class[] { int.class }, new Object[] { 0 }); - this.invokePrivateMethod("changeToTheMaxRemainBuffer", null, null); + invokePrivateMethod(this.getDoubleBufferStorage().getClass(), + this.getDoubleBufferStorage(), "changeToTheMaxRemainBuffer", + null, null); assertEquals(1220, buffers.get(0).getRemainSize()); assertEquals(48 * 1024, buffers.get(1).getRemainSize()); - assertEquals(1, - this.invokePrivateMethod("getCurrentBufferIndex", null, null)); + assertEquals( + 1, + invokePrivateMethod(this.getDoubleBufferStorage().getClass(), + this.getDoubleBufferStorage(), "getCurrentBufferIndex", + null, null)); } - private Object invokePrivateMethod(String methodName, - Class[] paramClasses, Object[] params) throws Exception { - Class class1 = this.getDoubleBufferStorage().getClass(); - Method method = class1.getDeclaredMethod(methodName, paramClasses); - method.setAccessible(true); - return method.invoke(this.getDoubleBufferStorage(), params); + private static Object invokePrivateMethod(Class containerClass, + Object targetObject, String methodName, Class[] paramClasses, + Object[] params) throws Exception { + return TestHelper.invokePrivateMethod(containerClass, targetObject, + methodName, paramClasses, params); } @Test From 9ed66bb71677d0d0fdbd48736cc27c6aab8765da Mon Sep 17 00:00:00 2001 From: coderfengyun Date: Thu, 19 Dec 2013 17:32:38 +0800 Subject: [PATCH 117/196] edit after edit the MarshalHelper --- .../java/org/bench4q/agent/test/TestWithScriptFile.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/test/java/org/bench4q/agent/test/TestWithScriptFile.java b/src/test/java/org/bench4q/agent/test/TestWithScriptFile.java index 9ac96c57..ab97a264 100644 --- a/src/test/java/org/bench4q/agent/test/TestWithScriptFile.java +++ b/src/test/java/org/bench4q/agent/test/TestWithScriptFile.java @@ -121,7 +121,7 @@ public class TestWithScriptFile { this.url + "/stop/" + this.getTestId().toString(), null, null); } - private void brief() throws IOException { + private void brief() throws IOException, JAXBException { System.out.println("Enter brief!"); HttpResponse httpResponse = this.getHttpRequester().sendGet( this.url + "/brief/" + this.getTestId().toString(), null, null); @@ -131,7 +131,7 @@ public class TestWithScriptFile { assertTrue(briefModel.getTimeFrame() > 0); } - private void behaviorsBrief() throws IOException { + private void behaviorsBrief() throws IOException, JAXBException { System.out.println("Enter behaviorsBrief!"); HttpResponse httpResponse = this.getHttpRequester().sendGet( this.url + "/behaviorsBrief/" + this.getTestId().toString(), @@ -142,7 +142,7 @@ public class TestWithScriptFile { assertTrue(behaviorsBriefModel.getBehaviorBriefModels().size() > 0); } - private void behaviorBrief() throws IOException { + private void behaviorBrief() throws IOException, JAXBException { System.out.println("Enter behaviorBrief!"); HttpResponse httpResponse = this.getHttpRequester().sendGet( this.url + "/brief/" + this.getTestId().toString() + "/1", From 00215862ea9d394c0625355e2dd3efb809c3c2ae Mon Sep 17 00:00:00 2001 From: coderfengyun Date: Fri, 20 Dec 2013 17:11:31 +0800 Subject: [PATCH 118/196] use the models in bench4q-share --- .../org/bench4q/agent/api/HomeController.java | 2 +- .../bench4q/agent/api/PluginController.java | 11 +- .../org/bench4q/agent/api/TestController.java | 14 +- .../api/model/AgentBriefStatusModel.java | 163 ------------------ .../agent/api/model/BehaviorBriefModel.java | 43 ----- .../agent/api/model/BehaviorInfoModel.java | 32 ---- .../agent/api/model/BehaviorResultModel.java | 159 ----------------- .../model/BehaviorStatusCodeResultModel.java | 79 --------- .../agent/api/model/CleanTestResultModel.java | 19 -- .../agent/api/model/DataStatisticsModel.java | 5 - .../agent/api/model/ParameterInfoModel.java | 29 ---- .../agent/api/model/PluginInfoListModel.java | 23 --- .../agent/api/model/PluginInfoModel.java | 43 ----- .../api/model/RunScenarioResultModel.java | 21 --- .../agent/api/model/ServerStatusModel.java | 35 ---- .../api/model/StatusCodeResultModel.java | 50 ------ .../agent/api/model/StopTestModel.java | 19 -- .../api/model/TestBehaviorsBriefModel.java | 24 --- .../impl/AbstractDataCollector.java | 2 +- .../impl/AgentResultDataCollector.java | 2 +- .../agent/storage/DoubleBufferStorage.java | 2 +- .../agent/test/DataStatisticsTest.java | 2 +- .../agent/test/TestWithScriptFile.java | 8 +- 23 files changed, 21 insertions(+), 766 deletions(-) delete mode 100644 src/main/java/org/bench4q/agent/api/model/AgentBriefStatusModel.java delete mode 100644 src/main/java/org/bench4q/agent/api/model/BehaviorBriefModel.java delete mode 100644 src/main/java/org/bench4q/agent/api/model/BehaviorInfoModel.java delete mode 100644 src/main/java/org/bench4q/agent/api/model/BehaviorResultModel.java delete mode 100644 src/main/java/org/bench4q/agent/api/model/BehaviorStatusCodeResultModel.java delete mode 100644 src/main/java/org/bench4q/agent/api/model/CleanTestResultModel.java delete mode 100644 src/main/java/org/bench4q/agent/api/model/DataStatisticsModel.java delete mode 100644 src/main/java/org/bench4q/agent/api/model/ParameterInfoModel.java delete mode 100644 src/main/java/org/bench4q/agent/api/model/PluginInfoListModel.java delete mode 100644 src/main/java/org/bench4q/agent/api/model/PluginInfoModel.java delete mode 100644 src/main/java/org/bench4q/agent/api/model/RunScenarioResultModel.java delete mode 100644 src/main/java/org/bench4q/agent/api/model/ServerStatusModel.java delete mode 100644 src/main/java/org/bench4q/agent/api/model/StatusCodeResultModel.java delete mode 100644 src/main/java/org/bench4q/agent/api/model/StopTestModel.java delete mode 100644 src/main/java/org/bench4q/agent/api/model/TestBehaviorsBriefModel.java diff --git a/src/main/java/org/bench4q/agent/api/HomeController.java b/src/main/java/org/bench4q/agent/api/HomeController.java index 4f129404..6c3599cd 100644 --- a/src/main/java/org/bench4q/agent/api/HomeController.java +++ b/src/main/java/org/bench4q/agent/api/HomeController.java @@ -5,9 +5,9 @@ import java.util.HashMap; import java.util.Map; import java.util.UUID; -import org.bench4q.agent.api.model.ServerStatusModel; import org.bench4q.agent.scenario.ScenarioContext; import org.bench4q.agent.scenario.ScenarioEngine; +import org.bench4q.share.models.agent.ServerStatusModel; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; diff --git a/src/main/java/org/bench4q/agent/api/PluginController.java b/src/main/java/org/bench4q/agent/api/PluginController.java index a2ff96b4..244a08ec 100644 --- a/src/main/java/org/bench4q/agent/api/PluginController.java +++ b/src/main/java/org/bench4q/agent/api/PluginController.java @@ -3,14 +3,14 @@ package org.bench4q.agent.api; import java.util.ArrayList; import java.util.List; -import org.bench4q.agent.api.model.BehaviorInfoModel; -import org.bench4q.agent.api.model.ParameterInfoModel; -import org.bench4q.agent.api.model.PluginInfoListModel; -import org.bench4q.agent.api.model.PluginInfoModel; import org.bench4q.agent.plugin.BehaviorInfo; import org.bench4q.agent.plugin.ParameterInfo; import org.bench4q.agent.plugin.PluginInfo; import org.bench4q.agent.plugin.PluginManager; +import org.bench4q.share.models.agent.BehaviorInfoModel; +import org.bench4q.share.models.agent.ParameterInfoModel; +import org.bench4q.share.models.agent.PluginInfoListModel; +import org.bench4q.share.models.agent.PluginInfoModel; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @@ -63,8 +63,7 @@ public class PluginController { private BehaviorInfoModel buildBehaviorInfoModel(BehaviorInfo behaviorInfo) { BehaviorInfoModel behaviorInfoModel = new BehaviorInfoModel(); behaviorInfoModel.setName(behaviorInfo.getName()); - behaviorInfoModel - .setParameters(new ArrayList()); + behaviorInfoModel.setParameters(new ArrayList()); for (ParameterInfo param : behaviorInfo.getParameters()) { ParameterInfoModel model = buildParameterInfoModel(param); behaviorInfoModel.getParameters().add(model); diff --git a/src/main/java/org/bench4q/agent/api/TestController.java b/src/main/java/org/bench4q/agent/api/TestController.java index f9506023..61bfbc56 100644 --- a/src/main/java/org/bench4q/agent/api/TestController.java +++ b/src/main/java/org/bench4q/agent/api/TestController.java @@ -13,13 +13,6 @@ import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import org.apache.log4j.Logger; -import org.bench4q.agent.api.model.AgentBriefStatusModel; -import org.bench4q.agent.api.model.BehaviorBriefModel; -import org.bench4q.agent.api.model.CleanTestResultModel; -import org.bench4q.agent.api.model.BehaviorStatusCodeResultModel; -import org.bench4q.agent.api.model.RunScenarioResultModel; -import org.bench4q.agent.api.model.StopTestModel; -import org.bench4q.agent.api.model.TestBehaviorsBriefModel; import org.bench4q.agent.datacollector.impl.DetailStatusCodeResult; import org.bench4q.agent.scenario.Batch; import org.bench4q.agent.scenario.Parameter; @@ -29,8 +22,15 @@ import org.bench4q.agent.scenario.ScenarioEngine; import org.bench4q.agent.scenario.UsePlugin; import org.bench4q.agent.scenario.behavior.Behavior; import org.bench4q.agent.scenario.behavior.BehaviorFactory; +import org.bench4q.share.models.agent.AgentBriefStatusModel; +import org.bench4q.share.models.agent.BehaviorBriefModel; +import org.bench4q.share.models.agent.BehaviorStatusCodeResultModel; +import org.bench4q.share.models.agent.CleanTestResultModel; import org.bench4q.share.models.agent.ParameterModel; import org.bench4q.share.models.agent.RunScenarioModel; +import org.bench4q.share.models.agent.RunScenarioResultModel; +import org.bench4q.share.models.agent.StopTestModel; +import org.bench4q.share.models.agent.TestBehaviorsBriefModel; import org.bench4q.share.models.agent.scriptrecord.BatchBehavior; import org.bench4q.share.models.agent.scriptrecord.BehaviorBaseModel; import org.bench4q.share.models.agent.scriptrecord.UsePluginModel; diff --git a/src/main/java/org/bench4q/agent/api/model/AgentBriefStatusModel.java b/src/main/java/org/bench4q/agent/api/model/AgentBriefStatusModel.java deleted file mode 100644 index f3559f4a..00000000 --- a/src/main/java/org/bench4q/agent/api/model/AgentBriefStatusModel.java +++ /dev/null @@ -1,163 +0,0 @@ -package org.bench4q.agent.api.model; - -import java.io.ByteArrayInputStream; -import java.lang.reflect.Field; - -import javax.xml.bind.JAXBContext; -import javax.xml.bind.JAXBException; -import javax.xml.bind.Unmarshaller; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; - -@XmlRootElement -public class AgentBriefStatusModel extends DataStatisticsModel { - private long timeFrame; - private long minResponseTime; - private long maxResponseTime; - private long successCountFromBegin; - private long successThroughputThisTime; - private long failCountFromBegin; - private long failThroughputThisTime; - - private long successCountThisTime; - private long failCountThisTime; - private long totalResponseTimeThisTime; - private long totalSqureResponseTimeThisTime; - - @XmlElement - public long getTimeFrame() { - return timeFrame; - } - - public void setTimeFrame(long timeFrame) { - this.timeFrame = timeFrame; - } - - @XmlElement - public long getMinResponseTime() { - return minResponseTime; - } - - public void setMinResponseTime(long minResponseTime) { - this.minResponseTime = minResponseTime; - } - - @XmlElement - public long getMaxResponseTime() { - return maxResponseTime; - } - - public void setMaxResponseTime(long maxResponseTime) { - this.maxResponseTime = maxResponseTime; - } - - @XmlElement - public long getSuccessThroughputThisTime() { - return successThroughputThisTime; - } - - public void setSuccessThroughputThisTime(long successThroughputThisTime) { - this.successThroughputThisTime = successThroughputThisTime; - } - - @XmlElement - public long getSuccessCountFromBegin() { - return successCountFromBegin; - } - - public void setSuccessCountFromBegin(long successCountFromBegin) { - this.successCountFromBegin = successCountFromBegin; - } - - @XmlElement - public long getFailCountFromBegin() { - return failCountFromBegin; - } - - public void setFailCountFromBegin(long failCountFromBegin) { - this.failCountFromBegin = failCountFromBegin; - } - - @XmlElement - public long getFailThroughputThisTime() { - return failThroughputThisTime; - } - - public void setFailThroughputThisTime(long failThroughputThisTime) { - this.failThroughputThisTime = failThroughputThisTime; - } - - @XmlElement - public long getSuccessCountThisTime() { - return successCountThisTime; - } - - public void setSuccessCountThisTime(long successCountThisTime) { - this.successCountThisTime = successCountThisTime; - } - - @XmlElement - public long getFailCountThisTime() { - return failCountThisTime; - } - - public void setFailCountThisTime(long failCountThisTime) { - this.failCountThisTime = failCountThisTime; - } - - @XmlElement - public long getTotalResponseTimeThisTime() { - return totalResponseTimeThisTime; - } - - public void setTotalResponseTimeThisTime(long totalResponseTimeThisTime) { - this.totalResponseTimeThisTime = totalResponseTimeThisTime; - } - - @XmlElement - public long getTotalSqureResponseTimeThisTime() { - return totalSqureResponseTimeThisTime; - } - - public void setTotalSqureResponseTimeThisTime( - long totalSqureResponseTimeThisTime) { - this.totalSqureResponseTimeThisTime = totalSqureResponseTimeThisTime; - } - - // if the all the fields of target object equals with this's except - // timeFrame, - // We call it equals. - @Override - public boolean equals(Object targetObj) { - if (!(targetObj instanceof AgentBriefStatusModel) || targetObj == null) { - return false; - } - boolean result = true; - AgentBriefStatusModel convertedObject = (AgentBriefStatusModel) targetObj; - Field[] fs = this.getClass().getDeclaredFields(); - try { - for (Field field : fs) { - field.setAccessible(true); - if (field.getLong(this) != field.getLong(convertedObject)) { - System.out.println(field.getName() - + " not equals! and the target is " - + field.getLong(convertedObject) + " and this is " - + field.getLong(this)); - result = false; - } - } - } catch (Exception e) { - e.printStackTrace(); - result = false; - } - return result; - } - - public static AgentBriefStatusModel extractBriefStatusModel(String content) - throws JAXBException { - Unmarshaller unmarshaller = JAXBContext.newInstance( - AgentBriefStatusModel.class).createUnmarshaller(); - return (AgentBriefStatusModel) unmarshaller - .unmarshal(new ByteArrayInputStream(content.getBytes())); - } -} diff --git a/src/main/java/org/bench4q/agent/api/model/BehaviorBriefModel.java b/src/main/java/org/bench4q/agent/api/model/BehaviorBriefModel.java deleted file mode 100644 index cd6a0d17..00000000 --- a/src/main/java/org/bench4q/agent/api/model/BehaviorBriefModel.java +++ /dev/null @@ -1,43 +0,0 @@ -package org.bench4q.agent.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 = "BehaviorBriefModel") -public class BehaviorBriefModel { - private int behaviorId; - private String behaviorUrl; - private List detailStatusCodeResultModels; - - @XmlElement - public int getBehaviorId() { - return behaviorId; - } - - public void setBehaviorId(int behaviorId) { - this.behaviorId = behaviorId; - } - - @XmlElement - public String getBehaviorUrl() { - return behaviorUrl; - } - - public void setBehaviorUrl(String behaviorUrl) { - this.behaviorUrl = behaviorUrl; - } - - @XmlElementWrapper(name = "detailStatusCodeResultList") - @XmlElement(name = "detailStatusCodeResult") - public List getDetailStatusCodeResultModels() { - return detailStatusCodeResultModels; - } - - public void setDetailStatusCodeResultModels( - List detailStatusCodeResultModels) { - this.detailStatusCodeResultModels = detailStatusCodeResultModels; - } - -} diff --git a/src/main/java/org/bench4q/agent/api/model/BehaviorInfoModel.java b/src/main/java/org/bench4q/agent/api/model/BehaviorInfoModel.java deleted file mode 100644 index a74eb5b7..00000000 --- a/src/main/java/org/bench4q/agent/api/model/BehaviorInfoModel.java +++ /dev/null @@ -1,32 +0,0 @@ -package org.bench4q.agent.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 = "behaviorInfo") -public class BehaviorInfoModel { - private String name; - private List parameters; - - @XmlElement - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - @XmlElementWrapper(name = "parameters") - @XmlElement(name = "parameter") - public List getParameters() { - return parameters; - } - - public void setParameters(List parameters) { - this.parameters = parameters; - } -} diff --git a/src/main/java/org/bench4q/agent/api/model/BehaviorResultModel.java b/src/main/java/org/bench4q/agent/api/model/BehaviorResultModel.java deleted file mode 100644 index 5d327399..00000000 --- a/src/main/java/org/bench4q/agent/api/model/BehaviorResultModel.java +++ /dev/null @@ -1,159 +0,0 @@ -package org.bench4q.agent.api.model; - -import java.io.ByteArrayOutputStream; -import java.util.Date; -import java.util.UUID; - -import javax.xml.bind.JAXBContext; -import javax.xml.bind.JAXBException; -import javax.xml.bind.Marshaller; -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; - -@XmlRootElement(name = "behaviorResultModel") -public class BehaviorResultModel { - private UUID id; - private String pluginId; - private String pluginName; - private String behaviorName; - private Date startDate; - private Date endDate; - private long responseTime; - private boolean success; - private int behaviorId; - private long contentLength; - private int statusCode; - private String contentType; - private boolean shouldBeCountResponseTime; - - @XmlElement - public UUID getId() { - return id; - } - - public void setId(UUID id) { - this.id = id; - } - - @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; - } - - @XmlElement - public int getBehaviorId() { - return behaviorId; - } - - public void setBehaviorId(int behaviorId) { - this.behaviorId = behaviorId; - } - - @XmlElement - public long getContentLength() { - return contentLength; - } - - public void setContentLength(long contentLength) { - this.contentLength = contentLength; - } - - @XmlElement - public int getStatusCode() { - return statusCode; - } - - public void setStatusCode(int statusCode) { - this.statusCode = statusCode; - } - - @XmlElement - public String getContentType() { - return contentType; - } - - public void setContentType(String contentType) { - this.contentType = contentType; - } - - @XmlElement - public boolean isShouldBeCountResponseTime() { - return shouldBeCountResponseTime; - } - - public void setShouldBeCountResponseTime(boolean shouldBeCountResponseTime) { - this.shouldBeCountResponseTime = shouldBeCountResponseTime; - } - - public String getModelString() { - ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); - Marshaller marshaller; - try { - marshaller = JAXBContext.newInstance(BehaviorResultModel.class) - .createMarshaller(); - marshaller.marshal(this, outputStream); - return outputStream.toString(); - } catch (JAXBException e) { - return ""; - } - - } -} diff --git a/src/main/java/org/bench4q/agent/api/model/BehaviorStatusCodeResultModel.java b/src/main/java/org/bench4q/agent/api/model/BehaviorStatusCodeResultModel.java deleted file mode 100644 index 11d243c8..00000000 --- a/src/main/java/org/bench4q/agent/api/model/BehaviorStatusCodeResultModel.java +++ /dev/null @@ -1,79 +0,0 @@ -package org.bench4q.agent.api.model; - -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; - -@XmlRootElement(name = "BehaviorStatusCodeResultModel") -public class BehaviorStatusCodeResultModel { - private int statusCode; - private long count; - private String contentType; - private long contentLength; - private long minResponseTime; - private long maxResponseTime; - private long totalResponseTimeThisTime; - - @XmlElement - public int getStatusCode() { - return statusCode; - } - - public void setStatusCode(int statusCode) { - this.statusCode = statusCode; - } - - @XmlElement - public long getCount() { - return count; - } - - public void setCount(long count) { - this.count = count; - } - - @XmlElement - public String getContentType() { - return contentType; - } - - public void setContentType(String contentType) { - this.contentType = contentType; - } - - @XmlElement - public long getContentLength() { - return contentLength; - } - - public void setContentLength(long contentLength) { - this.contentLength = contentLength; - } - - @XmlElement - public long getMinResponseTime() { - return minResponseTime; - } - - public void setMinResponseTime(long minResponseTime) { - this.minResponseTime = minResponseTime; - } - - @XmlElement - public long getMaxResponseTime() { - return maxResponseTime; - } - - public void setMaxResponseTime(long maxResponseTime) { - this.maxResponseTime = maxResponseTime; - } - - @XmlElement - public long getTotalResponseTimeThisTime() { - return totalResponseTimeThisTime; - } - - public void setTotalResponseTimeThisTime(long totalResponseTimeThisTime) { - this.totalResponseTimeThisTime = totalResponseTimeThisTime; - } - -} diff --git a/src/main/java/org/bench4q/agent/api/model/CleanTestResultModel.java b/src/main/java/org/bench4q/agent/api/model/CleanTestResultModel.java deleted file mode 100644 index 8358871b..00000000 --- a/src/main/java/org/bench4q/agent/api/model/CleanTestResultModel.java +++ /dev/null @@ -1,19 +0,0 @@ -package org.bench4q.agent.api.model; - -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; - -@XmlRootElement(name = "cleanTestResult") -public class CleanTestResultModel { - private boolean success; - - @XmlElement - public boolean isSuccess() { - return success; - } - - public void setSuccess(boolean success) { - this.success = success; - } - -} diff --git a/src/main/java/org/bench4q/agent/api/model/DataStatisticsModel.java b/src/main/java/org/bench4q/agent/api/model/DataStatisticsModel.java deleted file mode 100644 index 302d70eb..00000000 --- a/src/main/java/org/bench4q/agent/api/model/DataStatisticsModel.java +++ /dev/null @@ -1,5 +0,0 @@ -package org.bench4q.agent.api.model; - -public abstract class DataStatisticsModel { - -} diff --git a/src/main/java/org/bench4q/agent/api/model/ParameterInfoModel.java b/src/main/java/org/bench4q/agent/api/model/ParameterInfoModel.java deleted file mode 100644 index 138b39bf..00000000 --- a/src/main/java/org/bench4q/agent/api/model/ParameterInfoModel.java +++ /dev/null @@ -1,29 +0,0 @@ -package org.bench4q.agent.api.model; - -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; - -@XmlRootElement(name = "parameterInfo") -public class ParameterInfoModel { - private String name; - private String type; - - @XmlElement - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - @XmlElement - public String getType() { - return type; - } - - public void setType(String type) { - this.type = type; - } - -} diff --git a/src/main/java/org/bench4q/agent/api/model/PluginInfoListModel.java b/src/main/java/org/bench4q/agent/api/model/PluginInfoListModel.java deleted file mode 100644 index e927d439..00000000 --- a/src/main/java/org/bench4q/agent/api/model/PluginInfoListModel.java +++ /dev/null @@ -1,23 +0,0 @@ -package org.bench4q.agent.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 = "pluginList") -public class PluginInfoListModel { - private List plugins; - - @XmlElementWrapper(name = "plugins") - @XmlElement(name = "plugin") - public List getPlugins() { - return plugins; - } - - public void setPlugins(List plugins) { - this.plugins = plugins; - } - -} diff --git a/src/main/java/org/bench4q/agent/api/model/PluginInfoModel.java b/src/main/java/org/bench4q/agent/api/model/PluginInfoModel.java deleted file mode 100644 index bdbddb19..00000000 --- a/src/main/java/org/bench4q/agent/api/model/PluginInfoModel.java +++ /dev/null @@ -1,43 +0,0 @@ -package org.bench4q.agent.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 = "pluginInfoItem") -public class PluginInfoModel { - private String name; - private List parameters; - private List behaviors; - - @XmlElement - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - @XmlElementWrapper(name = "parameters") - @XmlElement(name = "parameter") - public List getParameters() { - return parameters; - } - - public void setParameters(List parameters) { - this.parameters = parameters; - } - - @XmlElementWrapper(name = "behaviors") - @XmlElement(name = "behavior") - public List getBehaviors() { - return behaviors; - } - - public void setBehaviors(List behaviors) { - this.behaviors = behaviors; - } -} diff --git a/src/main/java/org/bench4q/agent/api/model/RunScenarioResultModel.java b/src/main/java/org/bench4q/agent/api/model/RunScenarioResultModel.java deleted file mode 100644 index 4f0c177a..00000000 --- a/src/main/java/org/bench4q/agent/api/model/RunScenarioResultModel.java +++ /dev/null @@ -1,21 +0,0 @@ -package org.bench4q.agent.api.model; - -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; - } - -} diff --git a/src/main/java/org/bench4q/agent/api/model/ServerStatusModel.java b/src/main/java/org/bench4q/agent/api/model/ServerStatusModel.java deleted file mode 100644 index 07a1ca7d..00000000 --- a/src/main/java/org/bench4q/agent/api/model/ServerStatusModel.java +++ /dev/null @@ -1,35 +0,0 @@ -package org.bench4q.agent.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 = "serverStatus") -public class ServerStatusModel { - private List runningTests; - private List finishedTests; - - @XmlElementWrapper(name = "runningTests") - @XmlElement(name = "runningTest") - public List getRunningTests() { - return runningTests; - } - - public void setRunningTests(List runningTests) { - this.runningTests = runningTests; - } - - @XmlElementWrapper(name = "finishedTests") - @XmlElement(name = "finishedTest") - public List getFinishedTests() { - return finishedTests; - } - - public void setFinishedTests(List finishedTests) { - this.finishedTests = finishedTests; - } - -} diff --git a/src/main/java/org/bench4q/agent/api/model/StatusCodeResultModel.java b/src/main/java/org/bench4q/agent/api/model/StatusCodeResultModel.java deleted file mode 100644 index 0ce87028..00000000 --- a/src/main/java/org/bench4q/agent/api/model/StatusCodeResultModel.java +++ /dev/null @@ -1,50 +0,0 @@ -package org.bench4q.agent.api.model; - -public class StatusCodeResultModel { - private int statusCode; - private long count; - private long contentLength; - private long maxResponseTime; - private long minResponseTime; - - public int getStatusCode() { - return statusCode; - } - - public void setStatusCode(int statusCode) { - this.statusCode = statusCode; - } - - public long getCount() { - return count; - } - - public void setCount(long count) { - this.count = count; - } - - public long getContentLength() { - return contentLength; - } - - public void setContentLength(long contentLength) { - this.contentLength = contentLength; - } - - public long getMaxResponseTime() { - return maxResponseTime; - } - - public void setMaxResponseTime(long maxResponseTime) { - this.maxResponseTime = maxResponseTime; - } - - public long getMinResponseTime() { - return minResponseTime; - } - - public void setMinResponseTime(long minResponseTime) { - this.minResponseTime = minResponseTime; - } - -} diff --git a/src/main/java/org/bench4q/agent/api/model/StopTestModel.java b/src/main/java/org/bench4q/agent/api/model/StopTestModel.java deleted file mode 100644 index d95e5484..00000000 --- a/src/main/java/org/bench4q/agent/api/model/StopTestModel.java +++ /dev/null @@ -1,19 +0,0 @@ -package org.bench4q.agent.api.model; - -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; - } - -} diff --git a/src/main/java/org/bench4q/agent/api/model/TestBehaviorsBriefModel.java b/src/main/java/org/bench4q/agent/api/model/TestBehaviorsBriefModel.java deleted file mode 100644 index e61dc7c2..00000000 --- a/src/main/java/org/bench4q/agent/api/model/TestBehaviorsBriefModel.java +++ /dev/null @@ -1,24 +0,0 @@ -package org.bench4q.agent.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 = "testBehaviorBriefModel") -public class TestBehaviorsBriefModel extends DataStatisticsModel { - private List behaviorBriefModels; - - @XmlElementWrapper(name = "behaviorBriefList") - @XmlElement(name = "behaviorBrief") - public List getBehaviorBriefModels() { - return behaviorBriefModels; - } - - public void setBehaviorBriefModels( - List behaviorBriefModels) { - this.behaviorBriefModels = behaviorBriefModels; - } - -} diff --git a/src/main/java/org/bench4q/agent/datacollector/impl/AbstractDataCollector.java b/src/main/java/org/bench4q/agent/datacollector/impl/AbstractDataCollector.java index 2b913db2..b65cdbff 100644 --- a/src/main/java/org/bench4q/agent/datacollector/impl/AbstractDataCollector.java +++ b/src/main/java/org/bench4q/agent/datacollector/impl/AbstractDataCollector.java @@ -5,11 +5,11 @@ import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import org.bench4q.agent.Main; -import org.bench4q.agent.api.model.BehaviorResultModel; import org.bench4q.agent.datacollector.interfaces.DataStatistics; import org.bench4q.agent.helper.ApplicationContextHelper; import org.bench4q.agent.scenario.BehaviorResult; import org.bench4q.agent.storage.StorageHelper; +import org.bench4q.share.models.agent.BehaviorResultModel; public abstract class AbstractDataCollector implements DataStatistics { protected StorageHelper storageHelper; diff --git a/src/main/java/org/bench4q/agent/datacollector/impl/AgentResultDataCollector.java b/src/main/java/org/bench4q/agent/datacollector/impl/AgentResultDataCollector.java index 3fca6039..82011bfb 100644 --- a/src/main/java/org/bench4q/agent/datacollector/impl/AgentResultDataCollector.java +++ b/src/main/java/org/bench4q/agent/datacollector/impl/AgentResultDataCollector.java @@ -6,8 +6,8 @@ import java.util.HashMap; import java.util.Map; import java.util.UUID; -import org.bench4q.agent.api.model.AgentBriefStatusModel; import org.bench4q.agent.scenario.BehaviorResult; +import org.bench4q.share.models.agent.AgentBriefStatusModel; /** * This class collect the behavior result and statistic it. diff --git a/src/main/java/org/bench4q/agent/storage/DoubleBufferStorage.java b/src/main/java/org/bench4q/agent/storage/DoubleBufferStorage.java index a9c19d66..b59ff924 100644 --- a/src/main/java/org/bench4q/agent/storage/DoubleBufferStorage.java +++ b/src/main/java/org/bench4q/agent/storage/DoubleBufferStorage.java @@ -9,7 +9,7 @@ import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; -import org.bench4q.agent.api.model.CleanTestResultModel; +import org.bench4q.share.models.agent.CleanTestResultModel; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; diff --git a/src/test/java/org/bench4q/agent/test/DataStatisticsTest.java b/src/test/java/org/bench4q/agent/test/DataStatisticsTest.java index 4de540cd..fb05ae28 100644 --- a/src/test/java/org/bench4q/agent/test/DataStatisticsTest.java +++ b/src/test/java/org/bench4q/agent/test/DataStatisticsTest.java @@ -7,11 +7,11 @@ import java.util.Date; import java.util.List; import java.util.UUID; -import org.bench4q.agent.api.model.AgentBriefStatusModel; import org.bench4q.agent.datacollector.impl.AgentResultDataCollector; import org.bench4q.agent.datacollector.interfaces.DataStatistics; import org.bench4q.agent.scenario.BehaviorResult; import org.bench4q.agent.storage.StorageHelper; +import org.bench4q.share.models.agent.AgentBriefStatusModel; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; diff --git a/src/test/java/org/bench4q/agent/test/TestWithScriptFile.java b/src/test/java/org/bench4q/agent/test/TestWithScriptFile.java index ab97a264..fb707d5a 100644 --- a/src/test/java/org/bench4q/agent/test/TestWithScriptFile.java +++ b/src/test/java/org/bench4q/agent/test/TestWithScriptFile.java @@ -13,12 +13,12 @@ import javax.xml.bind.JAXBException; import javax.xml.bind.Unmarshaller; import org.apache.commons.io.FileUtils; -import org.bench4q.agent.api.model.AgentBriefStatusModel; -import org.bench4q.agent.api.model.BehaviorBriefModel; -import org.bench4q.agent.api.model.RunScenarioResultModel; -import org.bench4q.agent.api.model.TestBehaviorsBriefModel; import org.bench4q.share.helper.MarshalHelper; +import org.bench4q.share.models.agent.AgentBriefStatusModel; +import org.bench4q.share.models.agent.BehaviorBriefModel; import org.bench4q.share.models.agent.RunScenarioModel; +import org.bench4q.share.models.agent.RunScenarioResultModel; +import org.bench4q.share.models.agent.TestBehaviorsBriefModel; import org.junit.Test; import Communication.HttpRequester; From 9df9718dbae9f392c014652a316cdc34426d2c8c Mon Sep 17 00:00:00 2001 From: coderfengyun Date: Mon, 23 Dec 2013 09:15:35 +0800 Subject: [PATCH 119/196] now, i can run the scenario with page in it --- .../org/bench4q/agent/api/TestController.java | 68 ++++++++++++------- .../java/org/bench4q/agent/scenario/Page.java | 13 ++++ .../agent/scenario/ScenarioEngine.java | 31 +++++---- .../bench4q/agent/scenario/ScenarioNew.java | 26 +++++-- .../bench4q/agent/scenario/ScenarioOld.java | 25 ------- .../agent/test/TestWithScriptFile.java | 8 +-- 6 files changed, 97 insertions(+), 74 deletions(-) create mode 100644 src/main/java/org/bench4q/agent/scenario/Page.java delete mode 100644 src/main/java/org/bench4q/agent/scenario/ScenarioOld.java diff --git a/src/main/java/org/bench4q/agent/api/TestController.java b/src/main/java/org/bench4q/agent/api/TestController.java index 61bfbc56..f19d1f9c 100644 --- a/src/main/java/org/bench4q/agent/api/TestController.java +++ b/src/main/java/org/bench4q/agent/api/TestController.java @@ -15,6 +15,7 @@ import javax.xml.bind.Marshaller; import org.apache.log4j.Logger; import org.bench4q.agent.datacollector.impl.DetailStatusCodeResult; import org.bench4q.agent.scenario.Batch; +import org.bench4q.agent.scenario.Page; import org.bench4q.agent.scenario.Parameter; import org.bench4q.agent.scenario.ScenarioNew; import org.bench4q.agent.scenario.ScenarioContext; @@ -33,6 +34,7 @@ import org.bench4q.share.models.agent.StopTestModel; import org.bench4q.share.models.agent.TestBehaviorsBriefModel; import org.bench4q.share.models.agent.scriptrecord.BatchBehavior; import org.bench4q.share.models.agent.scriptrecord.BehaviorBaseModel; +import org.bench4q.share.models.agent.scriptrecord.PageModel; import org.bench4q.share.models.agent.scriptrecord.UsePluginModel; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; @@ -95,31 +97,30 @@ public class TestController { ScenarioNew scenario = new ScenarioNew(); scenario.setUsePlugins(new UsePlugin[runScenarioModel.getUsePlugins() .size()]); - scenario.setBatches(new Batch[runScenarioModel.getBatches().size()]); + scenario.setPages(new Page[runScenarioModel.getPages().size()]); extractUsePlugins(runScenarioModel, scenario); - extractBatches(runScenarioModel, scenario); + extractPages(runScenarioModel, scenario); return scenario; } - private void extractBatches(RunScenarioModel runScenarioModel, + private void extractPages(RunScenarioModel runScenarioModel, ScenarioNew scenario) { - int i; - List batches = runScenarioModel.getBatches(); - for (i = 0; i < runScenarioModel.getBatches().size(); i++) { - BatchBehavior batch = batches.get(i); - scenario.getBatches()[i] = extractBatch(batch); + List pageModels = runScenarioModel.getPages(); + for (int i = 0; i < pageModels.size(); i++) { + PageModel pageModel = pageModels.get(i); + scenario.getPages()[i] = extractPage(pageModel); } } - private void extractUsePlugins(RunScenarioModel runScenarioModel, - ScenarioNew scenario) { - int i; - List usePluginModels = runScenarioModel.getUsePlugins(); - for (i = 0; i < runScenarioModel.getUsePlugins().size(); i++) { - UsePluginModel usePluginModel = usePluginModels.get(i); - UsePlugin usePlugin = extractUsePlugin(usePluginModel); - scenario.getUsePlugins()[i] = usePlugin; + private Page extractPage(PageModel pageModel) { + Page page = new Page(); + page.setBatches(new Batch[pageModel.getBatches().size()]); + List batches = pageModel.getBatches(); + for (int i = 0; i < pageModel.getBatches().size(); i++) { + BatchBehavior batch = batches.get(i); + page.getBatches()[i] = extractBatch(batch); } + return page; } private Batch extractBatch(BatchBehavior batchModel) { @@ -139,6 +140,17 @@ public class TestController { return batch; } + private void extractUsePlugins(RunScenarioModel runScenarioModel, + ScenarioNew scenario) { + int i; + List usePluginModels = runScenarioModel.getUsePlugins(); + for (i = 0; i < runScenarioModel.getUsePlugins().size(); i++) { + UsePluginModel usePluginModel = usePluginModels.get(i); + UsePlugin usePlugin = extractUsePlugin(usePluginModel); + scenario.getUsePlugins()[i] = usePlugin; + } + } + private Behavior extractBehavior(BehaviorBaseModel behaviorModel) { Behavior behavior = BehaviorFactory.getBuisinessObject(behaviorModel); behavior.setName(behaviorModel.getName()); @@ -190,18 +202,22 @@ public class TestController { if (scenarioContext == null || scenarioContext.isFinished()) { return null; } - for (Batch batch : scenarioContext.getScenario().getBatches()) { - for (Behavior behavior : batch.getBehaviors()) { - int behaviorId = behavior.getId(); - Map map = scenarioContext - .getDataStatistics().getDetailStatistics(behaviorId); - if (map == null) { - continue; - } - behaviorBriefModels.add(buildBehaviorBrief(runId, behaviorId, - map)); + for (Page page : scenarioContext.getScenario().getPages()) { + for (Batch batch : page.getBatches()) { + for (Behavior behavior : batch.getBehaviors()) { + int behaviorId = behavior.getId(); + Map map = scenarioContext + .getDataStatistics() + .getDetailStatistics(behaviorId); + if (map == null) { + continue; + } + behaviorBriefModels.add(buildBehaviorBrief(runId, + behaviorId, map)); + } } + } ret.setBehaviorBriefModels(behaviorBriefModels); return ret; diff --git a/src/main/java/org/bench4q/agent/scenario/Page.java b/src/main/java/org/bench4q/agent/scenario/Page.java new file mode 100644 index 00000000..ff19117b --- /dev/null +++ b/src/main/java/org/bench4q/agent/scenario/Page.java @@ -0,0 +1,13 @@ +package org.bench4q.agent.scenario; + +public class Page { + private Batch[] batches; + + public Batch[] getBatches() { + return batches; + } + + public void setBatches(Batch[] batches) { + this.batches = batches; + } +} diff --git a/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java b/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java index e0b51b2a..d757fcb2 100644 --- a/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java +++ b/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java @@ -94,23 +94,26 @@ public class ScenarioEngine { Map plugins = new HashMap(); preparePlugins(context.getScenario(), plugins); - for (Batch batch : context.getScenario().getBatches()) { - for (Behavior behavior : batch.getBehaviors()) { - Object plugin = plugins.get(behavior.getUse()); - Map behaviorParameters = prepareBehaviorParameters(behavior); - Date startDate = new Date(System.currentTimeMillis()); - PluginReturn pluginReturn = (PluginReturn) this - .getPluginManager().doBehavior(plugin, - behavior.getName(), behaviorParameters); - Date endDate = new Date(System.currentTimeMillis()); - if (!behavior.shouldBeCountResponseTime()) { - continue; + for (Page page : context.getScenario().getPages()) { + for (Batch batch : page.getBatches()) { + for (Behavior behavior : batch.getBehaviors()) { + Object plugin = plugins.get(behavior.getUse()); + Map behaviorParameters = prepareBehaviorParameters(behavior); + Date startDate = new Date(System.currentTimeMillis()); + PluginReturn pluginReturn = (PluginReturn) this + .getPluginManager().doBehavior(plugin, + behavior.getName(), behaviorParameters); + Date endDate = new Date(System.currentTimeMillis()); + if (!behavior.shouldBeCountResponseTime()) { + continue; + } + context.getDataStatistics().add( + buildBehaviorResult(behavior, plugin, startDate, + pluginReturn, endDate)); } - context.getDataStatistics().add( - buildBehaviorResult(behavior, plugin, startDate, - pluginReturn, endDate)); } } + } private BehaviorResult buildBehaviorResult(Behavior behavior, diff --git a/src/main/java/org/bench4q/agent/scenario/ScenarioNew.java b/src/main/java/org/bench4q/agent/scenario/ScenarioNew.java index d82366f8..298de914 100644 --- a/src/main/java/org/bench4q/agent/scenario/ScenarioNew.java +++ b/src/main/java/org/bench4q/agent/scenario/ScenarioNew.java @@ -1,9 +1,14 @@ package org.bench4q.agent.scenario; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.bench4q.agent.scenario.behavior.Behavior; public class ScenarioNew { private UsePlugin[] usePlugins; - private Batch[] batches; + private Page[] pages; public UsePlugin[] getUsePlugins() { return usePlugins; @@ -13,12 +18,23 @@ public class ScenarioNew { this.usePlugins = usePlugins; } - public Batch[] getBatches() { - return batches; + public Page[] getPages() { + return pages; } - public void setBatches(Batch[] batches) { - this.batches = batches; + public void setPages(Page[] pages) { + this.pages = pages; } + public List getAllBehaviorsInScenario() { + List behaviors = new ArrayList(); + for (Page page : this.getPages()) { + for (Batch batch : page.getBatches()) { + for (Behavior behavior : batch.getBehaviors()) { + behaviors.add(behavior); + } + } + } + return Collections.unmodifiableList(behaviors); + } } diff --git a/src/main/java/org/bench4q/agent/scenario/ScenarioOld.java b/src/main/java/org/bench4q/agent/scenario/ScenarioOld.java deleted file mode 100644 index 983e4e2e..00000000 --- a/src/main/java/org/bench4q/agent/scenario/ScenarioOld.java +++ /dev/null @@ -1,25 +0,0 @@ -package org.bench4q.agent.scenario; - -import org.bench4q.agent.scenario.behavior.Behavior; - -public class ScenarioOld { - private UsePlugin[] usePlugins; - private Behavior[] behaviors; - - public UsePlugin[] getUsePlugins() { - return usePlugins; - } - - public void setUsePlugins(UsePlugin[] usePlugins) { - this.usePlugins = usePlugins; - } - - public Behavior[] getBehaviors() { - return behaviors; - } - - public void setBehaviors(Behavior[] behaviors) { - this.behaviors = behaviors; - } - -} diff --git a/src/test/java/org/bench4q/agent/test/TestWithScriptFile.java b/src/test/java/org/bench4q/agent/test/TestWithScriptFile.java index fb707d5a..fe511ae2 100644 --- a/src/test/java/org/bench4q/agent/test/TestWithScriptFile.java +++ b/src/test/java/org/bench4q/agent/test/TestWithScriptFile.java @@ -57,7 +57,7 @@ public class TestWithScriptFile { public TestWithScriptFile() { this.setFilePath("Scripts" + System.getProperty("file.separator") - + "goodForBatch.xml"); + + "goodForPage.xml"); this.setHttpRequester(new HttpRequester()); } @@ -75,9 +75,9 @@ public class TestWithScriptFile { System.out.println("can't execute an unvalid script"); return; } - assertTrue(runScenarioModel.getBatches().size() > 0); - assertTrue(runScenarioModel.getBatches().get(0).getBehaviors() - .size() > 0); + assertTrue(runScenarioModel.getPages().size() > 0); + assertTrue(runScenarioModel.getPages().get(0).getBatches().get(0) + .getBehaviors().size() > 0); runScenarioModel.setPoolSize(load); HttpResponse httpResponse = this.getHttpRequester().sendPostXml( From 45e27bcc35a012a5926ebbdd5ce5d07514b05e98 Mon Sep 17 00:00:00 2001 From: coderfengyun Date: Mon, 23 Dec 2013 09:18:28 +0800 Subject: [PATCH 120/196] refactor and add test scenario --- Scripts/goodForPage.xml | 1 + .../java/org/bench4q/agent/api/TestController.java | 12 ++++++------ .../scenario/{ScenarioNew.java => Scenario.java} | 2 +- .../org/bench4q/agent/scenario/ScenarioContext.java | 8 ++++---- .../org/bench4q/agent/scenario/ScenarioEngine.java | 4 ++-- 5 files changed, 14 insertions(+), 13 deletions(-) create mode 100644 Scripts/goodForPage.xml rename src/main/java/org/bench4q/agent/scenario/{ScenarioNew.java => Scenario.java} (92%) diff --git a/Scripts/goodForPage.xml b/Scripts/goodForPage.xml new file mode 100644 index 00000000..ecc99da3 --- /dev/null +++ b/Scripts/goodForPage.xml @@ -0,0 +1 @@ +0Geturlhttp://133.133.12.3:8080/Bench4QTestCase/testcase.htmlparametershttp20-10Sleeptime267timer-11-11Geturlhttp://133.133.12.3:8080/Bench4QTestCase/script/base.jsparametershttp2Geturlhttp://133.133.12.3:8080/Bench4QTestCase/images/3.jpgparametershttp3Geturlhttp://133.133.12.3:8080/Bench4QTestCase/images/2.jpgparametershttp4Geturlhttp://133.133.12.3:8080/Bench4QTestCase/script/agentTable.jsparametershttp5Geturlhttp://133.133.12.3:8080/Bench4QTestCase/images/1.jpgparametershttp-1200Sleeptime42timer-13-10Sleeptime10timer-14-10Sleeptime5timer-15-10Sleeptime10timer-16-10httpHttptimerConstantTimer \ No newline at end of file diff --git a/src/main/java/org/bench4q/agent/api/TestController.java b/src/main/java/org/bench4q/agent/api/TestController.java index f19d1f9c..cfa7b4a4 100644 --- a/src/main/java/org/bench4q/agent/api/TestController.java +++ b/src/main/java/org/bench4q/agent/api/TestController.java @@ -17,7 +17,7 @@ import org.bench4q.agent.datacollector.impl.DetailStatusCodeResult; import org.bench4q.agent.scenario.Batch; import org.bench4q.agent.scenario.Page; import org.bench4q.agent.scenario.Parameter; -import org.bench4q.agent.scenario.ScenarioNew; +import org.bench4q.agent.scenario.Scenario; import org.bench4q.agent.scenario.ScenarioContext; import org.bench4q.agent.scenario.ScenarioEngine; import org.bench4q.agent.scenario.UsePlugin; @@ -68,7 +68,7 @@ public class TestController { public RunScenarioResultModel run( @RequestBody RunScenarioModel runScenarioModel) throws UnknownHostException { - ScenarioNew scenario = extractScenario(runScenarioModel); + Scenario scenario = extractScenario(runScenarioModel); UUID runId = UUID.randomUUID(); System.out.println(runScenarioModel.getPoolSize()); this.getLogger().info(marshalRunScenarioModel(runScenarioModel)); @@ -93,8 +93,8 @@ public class TestController { } - private ScenarioNew extractScenario(RunScenarioModel runScenarioModel) { - ScenarioNew scenario = new ScenarioNew(); + private Scenario extractScenario(RunScenarioModel runScenarioModel) { + Scenario scenario = new Scenario(); scenario.setUsePlugins(new UsePlugin[runScenarioModel.getUsePlugins() .size()]); scenario.setPages(new Page[runScenarioModel.getPages().size()]); @@ -104,7 +104,7 @@ public class TestController { } private void extractPages(RunScenarioModel runScenarioModel, - ScenarioNew scenario) { + Scenario scenario) { List pageModels = runScenarioModel.getPages(); for (int i = 0; i < pageModels.size(); i++) { PageModel pageModel = pageModels.get(i); @@ -141,7 +141,7 @@ public class TestController { } private void extractUsePlugins(RunScenarioModel runScenarioModel, - ScenarioNew scenario) { + Scenario scenario) { int i; List usePluginModels = runScenarioModel.getUsePlugins(); for (i = 0; i < runScenarioModel.getUsePlugins().size(); i++) { diff --git a/src/main/java/org/bench4q/agent/scenario/ScenarioNew.java b/src/main/java/org/bench4q/agent/scenario/Scenario.java similarity index 92% rename from src/main/java/org/bench4q/agent/scenario/ScenarioNew.java rename to src/main/java/org/bench4q/agent/scenario/Scenario.java index 298de914..eb932df9 100644 --- a/src/main/java/org/bench4q/agent/scenario/ScenarioNew.java +++ b/src/main/java/org/bench4q/agent/scenario/Scenario.java @@ -6,7 +6,7 @@ import java.util.List; import org.bench4q.agent.scenario.behavior.Behavior; -public class ScenarioNew { +public class Scenario { private UsePlugin[] usePlugins; private Page[] pages; diff --git a/src/main/java/org/bench4q/agent/scenario/ScenarioContext.java b/src/main/java/org/bench4q/agent/scenario/ScenarioContext.java index 23c7bd37..1e407e10 100644 --- a/src/main/java/org/bench4q/agent/scenario/ScenarioContext.java +++ b/src/main/java/org/bench4q/agent/scenario/ScenarioContext.java @@ -11,7 +11,7 @@ public class ScenarioContext { private Date startDate; private Date endDate; private ExecutorService executorService; - private ScenarioNew scenario; + private Scenario scenario; private boolean finished; private DataStatistics dataStatistics; @@ -39,11 +39,11 @@ public class ScenarioContext { this.executorService = executorService; } - public ScenarioNew getScenario() { + public Scenario getScenario() { return scenario; } - public void setScenario(ScenarioNew scenario) { + public void setScenario(Scenario scenario) { this.scenario = scenario; } @@ -64,7 +64,7 @@ public class ScenarioContext { } public static ScenarioContext buildScenarioContext(UUID testId, - final ScenarioNew scenario, int poolSize, + final Scenario scenario, int poolSize, ExecutorService executorService) { ScenarioContext scenarioContext = new ScenarioContext(); scenarioContext.setScenario(scenario); diff --git a/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java b/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java index d757fcb2..be60a69d 100644 --- a/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java +++ b/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java @@ -64,7 +64,7 @@ public class ScenarioEngine { this.runningTests = runningTests; } - public void runScenario(UUID runId, final ScenarioNew scenario, int poolSize) { + public void runScenario(UUID runId, final Scenario scenario, int poolSize) { try { ExecutorService executorService = Executors .newFixedThreadPool(poolSize); @@ -148,7 +148,7 @@ public class ScenarioEngine { return behaviorParameters; } - private void preparePlugins(ScenarioNew scenario, + private void preparePlugins(Scenario scenario, Map plugins) { for (UsePlugin usePlugin : scenario.getUsePlugins()) { String pluginId = usePlugin.getId(); From 0cbffbc270b562f99fe00034f03e6b17ccd1c97b Mon Sep 17 00:00:00 2001 From: coderfengyun Date: Mon, 23 Dec 2013 09:19:59 +0800 Subject: [PATCH 121/196] refactor --- src/main/java/org/bench4q/agent/api/TestController.java | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/main/java/org/bench4q/agent/api/TestController.java b/src/main/java/org/bench4q/agent/api/TestController.java index cfa7b4a4..0b786edd 100644 --- a/src/main/java/org/bench4q/agent/api/TestController.java +++ b/src/main/java/org/bench4q/agent/api/TestController.java @@ -32,7 +32,7 @@ import org.bench4q.share.models.agent.RunScenarioModel; import org.bench4q.share.models.agent.RunScenarioResultModel; import org.bench4q.share.models.agent.StopTestModel; import org.bench4q.share.models.agent.TestBehaviorsBriefModel; -import org.bench4q.share.models.agent.scriptrecord.BatchBehavior; +import org.bench4q.share.models.agent.scriptrecord.BatchModel; import org.bench4q.share.models.agent.scriptrecord.BehaviorBaseModel; import org.bench4q.share.models.agent.scriptrecord.PageModel; import org.bench4q.share.models.agent.scriptrecord.UsePluginModel; @@ -115,15 +115,15 @@ public class TestController { private Page extractPage(PageModel pageModel) { Page page = new Page(); page.setBatches(new Batch[pageModel.getBatches().size()]); - List batches = pageModel.getBatches(); + List batches = pageModel.getBatches(); for (int i = 0; i < pageModel.getBatches().size(); i++) { - BatchBehavior batch = batches.get(i); + BatchModel batch = batches.get(i); page.getBatches()[i] = extractBatch(batch); } return page; } - private Batch extractBatch(BatchBehavior batchModel) { + private Batch extractBatch(BatchModel batchModel) { Batch batch = new Batch(); batch.setBehaviors(new Behavior[batchModel.getBehaviors().size()]); batch.setId(batchModel.getId()); From acca5e1cbd1a7cfe9291d0c679464a05fd241216 Mon Sep 17 00:00:00 2001 From: coderfengyun Date: Mon, 23 Dec 2013 09:29:26 +0800 Subject: [PATCH 122/196] refactor --- .../org/bench4q/agent/api/TestController.java | 30 ++++++++-------- .../agent/scenario/ScenarioEngine.java | 35 ++++++++----------- 2 files changed, 29 insertions(+), 36 deletions(-) diff --git a/src/main/java/org/bench4q/agent/api/TestController.java b/src/main/java/org/bench4q/agent/api/TestController.java index 0b786edd..aad36353 100644 --- a/src/main/java/org/bench4q/agent/api/TestController.java +++ b/src/main/java/org/bench4q/agent/api/TestController.java @@ -202,23 +202,23 @@ public class TestController { if (scenarioContext == null || scenarioContext.isFinished()) { return null; } - for (Page page : scenarioContext.getScenario().getPages()) { - for (Batch batch : page.getBatches()) { - for (Behavior behavior : batch.getBehaviors()) { - int behaviorId = behavior.getId(); - Map map = scenarioContext - .getDataStatistics() - .getDetailStatistics(behaviorId); - if (map == null) { - continue; - } - behaviorBriefModels.add(buildBehaviorBrief(runId, - behaviorId, map)); - - } + // for (Page page : scenarioContext.getScenario().getPages()) { + // for (Batch batch : page.getBatches()) { + // for (Behavior behavior : batch.getBehaviors()) { + for (Behavior behavior : scenarioContext.getScenario() + .getAllBehaviorsInScenario()) { + int behaviorId = behavior.getId(); + Map map = scenarioContext + .getDataStatistics().getDetailStatistics(behaviorId); + if (map == null) { + continue; } - + behaviorBriefModels.add(buildBehaviorBrief(runId, behaviorId, map)); } + // } + // } + // + // } ret.setBehaviorBriefModels(behaviorBriefModels); return ret; } diff --git a/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java b/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java index be60a69d..dd149a1e 100644 --- a/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java +++ b/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java @@ -93,27 +93,21 @@ public class ScenarioEngine { public void doRunScenario(ScenarioContext context) { Map plugins = new HashMap(); preparePlugins(context.getScenario(), plugins); - - for (Page page : context.getScenario().getPages()) { - for (Batch batch : page.getBatches()) { - for (Behavior behavior : batch.getBehaviors()) { - Object plugin = plugins.get(behavior.getUse()); - Map behaviorParameters = prepareBehaviorParameters(behavior); - Date startDate = new Date(System.currentTimeMillis()); - PluginReturn pluginReturn = (PluginReturn) this - .getPluginManager().doBehavior(plugin, - behavior.getName(), behaviorParameters); - Date endDate = new Date(System.currentTimeMillis()); - if (!behavior.shouldBeCountResponseTime()) { - continue; - } - context.getDataStatistics().add( - buildBehaviorResult(behavior, plugin, startDate, - pluginReturn, endDate)); - } + for (Behavior behavior : context.getScenario() + .getAllBehaviorsInScenario()) { + Object plugin = plugins.get(behavior.getUse()); + Map behaviorParameters = prepareBehaviorParameters(behavior); + Date startDate = new Date(System.currentTimeMillis()); + PluginReturn pluginReturn = (PluginReturn) this.getPluginManager() + .doBehavior(plugin, behavior.getName(), behaviorParameters); + Date endDate = new Date(System.currentTimeMillis()); + if (!behavior.shouldBeCountResponseTime()) { + continue; } + context.getDataStatistics().add( + buildBehaviorResult(behavior, plugin, startDate, + pluginReturn, endDate)); } - } private BehaviorResult buildBehaviorResult(Behavior behavior, @@ -148,8 +142,7 @@ public class ScenarioEngine { return behaviorParameters; } - private void preparePlugins(Scenario scenario, - Map plugins) { + private void preparePlugins(Scenario scenario, Map plugins) { for (UsePlugin usePlugin : scenario.getUsePlugins()) { String pluginId = usePlugin.getId(); Class pluginClass = this.getPluginManager().getPlugins() From 460fe86324ea5595ca17d15900e0d4cfdd62511c Mon Sep 17 00:00:00 2001 From: coderfengyun Date: Mon, 23 Dec 2013 09:36:12 +0800 Subject: [PATCH 123/196] refactor, let the scenario extract behaviors for pages only once --- .../org/bench4q/agent/scenario/Scenario.java | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/src/main/java/org/bench4q/agent/scenario/Scenario.java b/src/main/java/org/bench4q/agent/scenario/Scenario.java index eb932df9..198b96cb 100644 --- a/src/main/java/org/bench4q/agent/scenario/Scenario.java +++ b/src/main/java/org/bench4q/agent/scenario/Scenario.java @@ -9,6 +9,7 @@ import org.bench4q.agent.scenario.behavior.Behavior; public class Scenario { private UsePlugin[] usePlugins; private Page[] pages; + private List behaviors; public UsePlugin[] getUsePlugins() { return usePlugins; @@ -26,7 +27,22 @@ public class Scenario { this.pages = pages; } + private List getBehaviors() { + return behaviors; + } + + private void setBehaviors(List behaviors) { + this.behaviors = behaviors; + } + + public Scenario() { + this.setBehaviors(new ArrayList()); + } + public List getAllBehaviorsInScenario() { + if (this.getBehaviors().size() > 0) { + return Collections.unmodifiableList(this.getBehaviors()); + } List behaviors = new ArrayList(); for (Page page : this.getPages()) { for (Batch batch : page.getBatches()) { From beb5cd1973921733e6757c450e598b7de6d66c17 Mon Sep 17 00:00:00 2001 From: coderfengyun Date: Mon, 23 Dec 2013 10:19:51 +0800 Subject: [PATCH 124/196] refactor --- .../java/org/bench4q/agent/api/TestController.java | 11 ++--------- .../datacollector/impl/AgentResultDataCollector.java | 7 ++++--- .../bench4q/agent/scenario/behavior/Behavior.java | 7 +++++++ .../agent/scenario/behavior/TimerBehavior.java | 11 +++++++++++ .../agent/scenario/behavior/UserBehavior.java | 12 ++++++++++++ 5 files changed, 36 insertions(+), 12 deletions(-) diff --git a/src/main/java/org/bench4q/agent/api/TestController.java b/src/main/java/org/bench4q/agent/api/TestController.java index aad36353..0ff6608a 100644 --- a/src/main/java/org/bench4q/agent/api/TestController.java +++ b/src/main/java/org/bench4q/agent/api/TestController.java @@ -202,23 +202,16 @@ public class TestController { if (scenarioContext == null || scenarioContext.isFinished()) { return null; } - // for (Page page : scenarioContext.getScenario().getPages()) { - // for (Batch batch : page.getBatches()) { - // for (Behavior behavior : batch.getBehaviors()) { for (Behavior behavior : scenarioContext.getScenario() .getAllBehaviorsInScenario()) { int behaviorId = behavior.getId(); - Map map = scenarioContext - .getDataStatistics().getDetailStatistics(behaviorId); + Map map = behavior + .getBehaviorBriefResult(scenarioContext.getDataStatistics()); if (map == null) { continue; } behaviorBriefModels.add(buildBehaviorBrief(runId, behaviorId, map)); } - // } - // } - // - // } ret.setBehaviorBriefModels(behaviorBriefModels); return ret; } diff --git a/src/main/java/org/bench4q/agent/datacollector/impl/AgentResultDataCollector.java b/src/main/java/org/bench4q/agent/datacollector/impl/AgentResultDataCollector.java index 82011bfb..31b062e6 100644 --- a/src/main/java/org/bench4q/agent/datacollector/impl/AgentResultDataCollector.java +++ b/src/main/java/org/bench4q/agent/datacollector/impl/AgentResultDataCollector.java @@ -244,11 +244,12 @@ public class AgentResultDataCollector extends AbstractDataCollector { } @Override - public Map getDetailStatistics(int id) { - if (!this.detailMap.containsKey(id)) { + public Map getDetailStatistics( + int behaviorId) { + if (!this.detailMap.containsKey(behaviorId)) { return null; } - return this.detailMap.get(id); + return this.detailMap.get(behaviorId); } } diff --git a/src/main/java/org/bench4q/agent/scenario/behavior/Behavior.java b/src/main/java/org/bench4q/agent/scenario/behavior/Behavior.java index bd1c06cf..eacdb628 100644 --- a/src/main/java/org/bench4q/agent/scenario/behavior/Behavior.java +++ b/src/main/java/org/bench4q/agent/scenario/behavior/Behavior.java @@ -1,5 +1,9 @@ package org.bench4q.agent.scenario.behavior; +import java.util.Map; + +import org.bench4q.agent.datacollector.impl.DetailStatusCodeResult; +import org.bench4q.agent.datacollector.interfaces.DataStatistics; import org.bench4q.agent.scenario.Parameter; public abstract class Behavior { @@ -41,4 +45,7 @@ public abstract class Behavior { } public abstract boolean shouldBeCountResponseTime(); + + public abstract Map getBehaviorBriefResult( + DataStatistics dataStatistics); } diff --git a/src/main/java/org/bench4q/agent/scenario/behavior/TimerBehavior.java b/src/main/java/org/bench4q/agent/scenario/behavior/TimerBehavior.java index 645f904f..7a3aa008 100644 --- a/src/main/java/org/bench4q/agent/scenario/behavior/TimerBehavior.java +++ b/src/main/java/org/bench4q/agent/scenario/behavior/TimerBehavior.java @@ -1,5 +1,10 @@ package org.bench4q.agent.scenario.behavior; +import java.util.Map; + +import org.bench4q.agent.datacollector.impl.DetailStatusCodeResult; +import org.bench4q.agent.datacollector.interfaces.DataStatistics; + public class TimerBehavior extends Behavior { @Override @@ -7,4 +12,10 @@ public class TimerBehavior extends Behavior { return false; } + @Override + public Map getBehaviorBriefResult( + DataStatistics dataStatistics) { + return null; + } + } diff --git a/src/main/java/org/bench4q/agent/scenario/behavior/UserBehavior.java b/src/main/java/org/bench4q/agent/scenario/behavior/UserBehavior.java index 4100bceb..6a0442d1 100644 --- a/src/main/java/org/bench4q/agent/scenario/behavior/UserBehavior.java +++ b/src/main/java/org/bench4q/agent/scenario/behavior/UserBehavior.java @@ -1,8 +1,20 @@ package org.bench4q.agent.scenario.behavior; +import java.util.Map; + +import org.bench4q.agent.datacollector.impl.DetailStatusCodeResult; +import org.bench4q.agent.datacollector.interfaces.DataStatistics; + public class UserBehavior extends Behavior { @Override public boolean shouldBeCountResponseTime() { return true; } + + @Override + public Map getBehaviorBriefResult( + DataStatistics dataStatistics) { + return dataStatistics.getDetailStatistics(this.getId()); + } + } From 112d8f1949d32e359e0a7492975e3dbb93fe7772 Mon Sep 17 00:00:00 2001 From: coderfengyun Date: Mon, 23 Dec 2013 10:26:12 +0800 Subject: [PATCH 125/196] refactor --- .../org/bench4q/agent/api/TestController.java | 14 +++---- .../impl/AbstractDataCollector.java | 4 +- .../impl/AgentResultDataCollector.java | 27 ++++++------- ...ult.java => BehaviorStatusCodeResult.java} | 4 +- .../interfaces/DataStatistics.java | 7 ++-- .../agent/scenario/behavior/Behavior.java | 4 +- .../scenario/behavior/TimerBehavior.java | 4 +- .../agent/scenario/behavior/UserBehavior.java | 6 +-- .../agent/test/DataStatisticsTest.java | 6 +-- .../agent/test/DetailStatisticsTest.java | 38 +++++++++---------- 10 files changed, 58 insertions(+), 56 deletions(-) rename src/main/java/org/bench4q/agent/datacollector/impl/{DetailStatusCodeResult.java => BehaviorStatusCodeResult.java} (89%) diff --git a/src/main/java/org/bench4q/agent/api/TestController.java b/src/main/java/org/bench4q/agent/api/TestController.java index 0ff6608a..ba1a1f1b 100644 --- a/src/main/java/org/bench4q/agent/api/TestController.java +++ b/src/main/java/org/bench4q/agent/api/TestController.java @@ -13,7 +13,7 @@ import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import org.apache.log4j.Logger; -import org.bench4q.agent.datacollector.impl.DetailStatusCodeResult; +import org.bench4q.agent.datacollector.impl.BehaviorStatusCodeResult; import org.bench4q.agent.scenario.Batch; import org.bench4q.agent.scenario.Page; import org.bench4q.agent.scenario.Parameter; @@ -205,7 +205,7 @@ public class TestController { for (Behavior behavior : scenarioContext.getScenario() .getAllBehaviorsInScenario()) { int behaviorId = behavior.getId(); - Map map = behavior + Map map = behavior .getBehaviorBriefResult(scenarioContext.getDataStatistics()); if (map == null) { continue; @@ -225,17 +225,17 @@ public class TestController { if (scenarioContext == null) { return null; } - Map map = scenarioContext - .getDataStatistics().getDetailStatistics(behaviorId); + Map map = scenarioContext + .getDataStatistics().getBehaviorBriefStatistics(behaviorId); return buildBehaviorBrief(runId, behaviorId, map); } private BehaviorBriefModel buildBehaviorBrief(UUID runId, int behaviorId, - Map map) { + Map map) { List detailStatusCodeResultModels = new ArrayList(); for (int statusCode : map.keySet()) { BehaviorStatusCodeResultModel behaviorStatusCodeResultModel = new BehaviorStatusCodeResultModel(); - DetailStatusCodeResult detailStatusCodeResult = map.get(statusCode); + BehaviorStatusCodeResult detailStatusCodeResult = map.get(statusCode); behaviorStatusCodeResultModel.setStatusCode(statusCode); behaviorStatusCodeResultModel .setCount(detailStatusCodeResult.count); @@ -267,7 +267,7 @@ public class TestController { return null; } return (AgentBriefStatusModel) scenarioContext.getDataStatistics() - .getBriefStatistics(); + .getScenarioBriefStatistics(); } @RequestMapping(value = "/stop/{runId}", method = { RequestMethod.GET, diff --git a/src/main/java/org/bench4q/agent/datacollector/impl/AbstractDataCollector.java b/src/main/java/org/bench4q/agent/datacollector/impl/AbstractDataCollector.java index b65cdbff..ca71e11f 100644 --- a/src/main/java/org/bench4q/agent/datacollector/impl/AbstractDataCollector.java +++ b/src/main/java/org/bench4q/agent/datacollector/impl/AbstractDataCollector.java @@ -66,9 +66,9 @@ public abstract class AbstractDataCollector implements DataStatistics { protected abstract String calculateSavePath(BehaviorResult behaviorResult); - public abstract Object getBriefStatistics(); + public abstract Object getScenarioBriefStatistics(); - public abstract Map getDetailStatistics( + public abstract Map getBehaviorBriefStatistics( int id); } diff --git a/src/main/java/org/bench4q/agent/datacollector/impl/AgentResultDataCollector.java b/src/main/java/org/bench4q/agent/datacollector/impl/AgentResultDataCollector.java index 31b062e6..67cb0167 100644 --- a/src/main/java/org/bench4q/agent/datacollector/impl/AgentResultDataCollector.java +++ b/src/main/java/org/bench4q/agent/datacollector/impl/AgentResultDataCollector.java @@ -1,6 +1,7 @@ package org.bench4q.agent.datacollector.impl; import java.text.SimpleDateFormat; +import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.Map; @@ -29,7 +30,7 @@ public class AgentResultDataCollector extends AbstractDataCollector { private UUID testID; // The first integer is the behavior's id, and the second integer is // the StatusCode of this behaviorResult. - private Map> detailMap; + private Map> detailMap; private void setTimeOfPreviousCall(long timeOfPreviousCall) { this.timeOfPreviousCall = timeOfPreviousCall; @@ -89,7 +90,7 @@ public class AgentResultDataCollector extends AbstractDataCollector { } private void setDetailMap( - Map> detailMap) { + Map> detailMap) { this.detailMap = detailMap; } @@ -103,7 +104,7 @@ public class AgentResultDataCollector extends AbstractDataCollector { reset(); this.setCumulativeFailCount(0); this.setCumulativeSucessfulCount(0); - this.setDetailMap(new HashMap>()); + this.setDetailMap(new HashMap>()); } private void reset() { @@ -120,7 +121,7 @@ public class AgentResultDataCollector extends AbstractDataCollector { // DataStatistics Interface start // /////////////////////////////// - public AgentBriefStatusModel getBriefStatistics() { + public AgentBriefStatusModel getScenarioBriefStatistics() { AgentBriefStatusModel result = new AgentBriefStatusModel(); result.setTimeFrame(System.currentTimeMillis() - this.timeOfPreviousCall); @@ -188,17 +189,17 @@ public class AgentResultDataCollector extends AbstractDataCollector { private void dealWithDetailResult(BehaviorResult behaviorResult) { insertWhenNotExist(behaviorResult); - Map detailStatusMap = this.detailMap + Map detailStatusMap = this.detailMap .get(behaviorResult.getBehaviorId()); if (!detailStatusMap.containsKey(behaviorResult.getStatusCode())) { - detailStatusMap - .put(new Integer(behaviorResult.getStatusCode()), - new DetailStatusCodeResult(behaviorResult - .getContentType())); + detailStatusMap.put( + new Integer(behaviorResult.getStatusCode()), + new BehaviorStatusCodeResult(behaviorResult + .getContentType())); } - DetailStatusCodeResult detailResult = detailStatusMap + BehaviorStatusCodeResult detailResult = detailStatusMap .get(behaviorResult.getStatusCode()); detailResult.count++; if (!behaviorResult.isSuccess()) { @@ -222,7 +223,7 @@ public class AgentResultDataCollector extends AbstractDataCollector { private void insertWhenNotExist(BehaviorResult behaviorResult) { if (!this.detailMap.containsKey(behaviorResult.getBehaviorId())) { this.detailMap.put(new Integer(behaviorResult.getBehaviorId()), - new HashMap()); + new HashMap()); } } @@ -244,12 +245,12 @@ public class AgentResultDataCollector extends AbstractDataCollector { } @Override - public Map getDetailStatistics( + public Map getBehaviorBriefStatistics( int behaviorId) { if (!this.detailMap.containsKey(behaviorId)) { return null; } - return this.detailMap.get(behaviorId); + return Collections.unmodifiableMap(this.detailMap.get(behaviorId)); } } diff --git a/src/main/java/org/bench4q/agent/datacollector/impl/DetailStatusCodeResult.java b/src/main/java/org/bench4q/agent/datacollector/impl/BehaviorStatusCodeResult.java similarity index 89% rename from src/main/java/org/bench4q/agent/datacollector/impl/DetailStatusCodeResult.java rename to src/main/java/org/bench4q/agent/datacollector/impl/BehaviorStatusCodeResult.java index 759964f6..771aaaa0 100644 --- a/src/main/java/org/bench4q/agent/datacollector/impl/DetailStatusCodeResult.java +++ b/src/main/java/org/bench4q/agent/datacollector/impl/BehaviorStatusCodeResult.java @@ -2,7 +2,7 @@ package org.bench4q.agent.datacollector.impl; import java.lang.reflect.Field; -public class DetailStatusCodeResult { +public class BehaviorStatusCodeResult { public long count; public long contentLength; public long minResponseTime; @@ -10,7 +10,7 @@ public class DetailStatusCodeResult { public long totalResponseTimeThisTime; public String contentType; - public DetailStatusCodeResult(String contentType) { + public BehaviorStatusCodeResult(String contentType) { this.totalResponseTimeThisTime = 0; this.contentType = contentType; this.count = 0; diff --git a/src/main/java/org/bench4q/agent/datacollector/interfaces/DataStatistics.java b/src/main/java/org/bench4q/agent/datacollector/interfaces/DataStatistics.java index 0040b142..081e0abd 100644 --- a/src/main/java/org/bench4q/agent/datacollector/interfaces/DataStatistics.java +++ b/src/main/java/org/bench4q/agent/datacollector/interfaces/DataStatistics.java @@ -2,13 +2,14 @@ package org.bench4q.agent.datacollector.interfaces; import java.util.Map; -import org.bench4q.agent.datacollector.impl.DetailStatusCodeResult; +import org.bench4q.agent.datacollector.impl.BehaviorStatusCodeResult; import org.bench4q.agent.scenario.BehaviorResult; public interface DataStatistics { public void add(BehaviorResult behaviorResult); - public Object getBriefStatistics(); + public Object getScenarioBriefStatistics(); - public Map getDetailStatistics(int id); + public Map getBehaviorBriefStatistics( + int id); } diff --git a/src/main/java/org/bench4q/agent/scenario/behavior/Behavior.java b/src/main/java/org/bench4q/agent/scenario/behavior/Behavior.java index eacdb628..84825471 100644 --- a/src/main/java/org/bench4q/agent/scenario/behavior/Behavior.java +++ b/src/main/java/org/bench4q/agent/scenario/behavior/Behavior.java @@ -2,7 +2,7 @@ package org.bench4q.agent.scenario.behavior; import java.util.Map; -import org.bench4q.agent.datacollector.impl.DetailStatusCodeResult; +import org.bench4q.agent.datacollector.impl.BehaviorStatusCodeResult; import org.bench4q.agent.datacollector.interfaces.DataStatistics; import org.bench4q.agent.scenario.Parameter; @@ -46,6 +46,6 @@ public abstract class Behavior { public abstract boolean shouldBeCountResponseTime(); - public abstract Map getBehaviorBriefResult( + public abstract Map getBehaviorBriefResult( DataStatistics dataStatistics); } diff --git a/src/main/java/org/bench4q/agent/scenario/behavior/TimerBehavior.java b/src/main/java/org/bench4q/agent/scenario/behavior/TimerBehavior.java index 7a3aa008..32397c99 100644 --- a/src/main/java/org/bench4q/agent/scenario/behavior/TimerBehavior.java +++ b/src/main/java/org/bench4q/agent/scenario/behavior/TimerBehavior.java @@ -2,7 +2,7 @@ package org.bench4q.agent.scenario.behavior; import java.util.Map; -import org.bench4q.agent.datacollector.impl.DetailStatusCodeResult; +import org.bench4q.agent.datacollector.impl.BehaviorStatusCodeResult; import org.bench4q.agent.datacollector.interfaces.DataStatistics; public class TimerBehavior extends Behavior { @@ -13,7 +13,7 @@ public class TimerBehavior extends Behavior { } @Override - public Map getBehaviorBriefResult( + public Map getBehaviorBriefResult( DataStatistics dataStatistics) { return null; } diff --git a/src/main/java/org/bench4q/agent/scenario/behavior/UserBehavior.java b/src/main/java/org/bench4q/agent/scenario/behavior/UserBehavior.java index 6a0442d1..851a2c98 100644 --- a/src/main/java/org/bench4q/agent/scenario/behavior/UserBehavior.java +++ b/src/main/java/org/bench4q/agent/scenario/behavior/UserBehavior.java @@ -2,7 +2,7 @@ package org.bench4q.agent.scenario.behavior; import java.util.Map; -import org.bench4q.agent.datacollector.impl.DetailStatusCodeResult; +import org.bench4q.agent.datacollector.impl.BehaviorStatusCodeResult; import org.bench4q.agent.datacollector.interfaces.DataStatistics; public class UserBehavior extends Behavior { @@ -12,9 +12,9 @@ public class UserBehavior extends Behavior { } @Override - public Map getBehaviorBriefResult( + public Map getBehaviorBriefResult( DataStatistics dataStatistics) { - return dataStatistics.getDetailStatistics(this.getId()); + return dataStatistics.getBehaviorBriefStatistics(this.getId()); } } diff --git a/src/test/java/org/bench4q/agent/test/DataStatisticsTest.java b/src/test/java/org/bench4q/agent/test/DataStatisticsTest.java index fb05ae28..ec070ee6 100644 --- a/src/test/java/org/bench4q/agent/test/DataStatisticsTest.java +++ b/src/test/java/org/bench4q/agent/test/DataStatisticsTest.java @@ -49,7 +49,7 @@ public class DataStatisticsTest { } AgentBriefStatusModel model = (AgentBriefStatusModel) this - .getDataStatistics().getBriefStatistics(); + .getDataStatistics().getScenarioBriefStatistics(); AgentBriefStatusModel modelExpect = makeAllZeroModel(); modelExpect.setTimeFrame(model.getTimeFrame()); assertTrue(model.equals(modelExpect)); @@ -63,7 +63,7 @@ public class DataStatisticsTest { Thread.sleep(100); AgentBriefStatusModel model = (AgentBriefStatusModel) this - .getDataStatistics().getBriefStatistics(); + .getDataStatistics().getScenarioBriefStatistics(); AgentBriefStatusModel modelExpect = new AgentBriefStatusModel(); modelExpect.setTimeFrame(model.getTimeFrame()); makeUpStatusModelForOneBehavior(modelExpect); @@ -77,7 +77,7 @@ public class DataStatisticsTest { } Thread.sleep(100); AgentBriefStatusModel model = (AgentBriefStatusModel) this - .getDataStatistics().getBriefStatistics(); + .getDataStatistics().getScenarioBriefStatistics(); AgentBriefStatusModel modelExpect = makeUpStatusModelForTwoBehavior(model .getTimeFrame()); assertTrue(model.equals(modelExpect)); diff --git a/src/test/java/org/bench4q/agent/test/DetailStatisticsTest.java b/src/test/java/org/bench4q/agent/test/DetailStatisticsTest.java index fb099c07..d1558b7d 100644 --- a/src/test/java/org/bench4q/agent/test/DetailStatisticsTest.java +++ b/src/test/java/org/bench4q/agent/test/DetailStatisticsTest.java @@ -7,7 +7,7 @@ import java.util.Map; import java.util.UUID; import org.bench4q.agent.datacollector.impl.AgentResultDataCollector; -import org.bench4q.agent.datacollector.impl.DetailStatusCodeResult; +import org.bench4q.agent.datacollector.impl.BehaviorStatusCodeResult; import org.bench4q.agent.datacollector.interfaces.DataStatistics; import org.bench4q.agent.scenario.BehaviorResult; import org.bench4q.agent.storage.StorageHelper; @@ -48,7 +48,7 @@ public class DetailStatisticsTest { this.getDetailStatistics().add(behaviorResult); } - Object object = this.detailStatistics.getDetailStatistics(0); + Object object = this.detailStatistics.getBehaviorBriefStatistics(0); assertEquals(null, object); } @@ -58,15 +58,15 @@ public class DetailStatisticsTest { .makeBehaviorResultList(1)) { this.getDetailStatistics().add(behaviorResult); } - Map map = this.detailStatistics - .getDetailStatistics(1); + Map map = this.detailStatistics + .getBehaviorBriefStatistics(1); - DetailStatusCodeResult actualResult = map.get(200); + BehaviorStatusCodeResult actualResult = map.get(200); actualResult.equals(makeExpectedResultForOne()); } - private DetailStatusCodeResult makeExpectedResultForOne() { - DetailStatusCodeResult ret = new DetailStatusCodeResult(""); + private BehaviorStatusCodeResult makeExpectedResultForOne() { + BehaviorStatusCodeResult ret = new BehaviorStatusCodeResult(""); ret.contentLength = 20; ret.count = 1; ret.maxResponseTime = 200; @@ -80,23 +80,23 @@ public class DetailStatisticsTest { .makeBehaviorResultList(2)) { this.getDetailStatistics().add(behaviorResult); } - Map map = this.detailStatistics - .getDetailStatistics(1); + Map map = this.detailStatistics + .getBehaviorBriefStatistics(1); assertTrue(mapEquals(map, makeExpectedMapForTwo())); // DetailResult ex } - private Map makeExpectedMapForTwo() { - Map ret = new HashMap(); + private Map makeExpectedMapForTwo() { + Map ret = new HashMap(); ret.put(new Integer(200), buildCodeResult(20, 1, 200, 200, 200)); ret.put(new Integer(400), buildCodeResult(0, 1, 0, 0, 0)); return ret; } - private DetailStatusCodeResult buildCodeResult(long contentLength, + private BehaviorStatusCodeResult buildCodeResult(long contentLength, long count, long maxResponseTime, long minResponseTime, long totalResponseTimeThisTime) { - DetailStatusCodeResult ret = new DetailStatusCodeResult(""); + BehaviorStatusCodeResult ret = new BehaviorStatusCodeResult(""); ret.contentLength = contentLength; ret.count = count; ret.maxResponseTime = maxResponseTime; @@ -105,8 +105,8 @@ public class DetailStatisticsTest { return ret; } - private boolean mapEquals(Map mapActual, - Map mapExpected) { + private boolean mapEquals(Map mapActual, + Map mapExpected) { boolean equal = true; if (mapActual.size() != mapExpected.size()) { return false; @@ -125,13 +125,13 @@ public class DetailStatisticsTest { .makeBehaviorResultList(3)) { this.getDetailStatistics().add(behaviorResult); } - Map mapActual = this - .getDetailStatistics().getDetailStatistics(1); + Map mapActual = this + .getDetailStatistics().getBehaviorBriefStatistics(1); assertTrue(mapEquals(mapActual, makeExpectedMapForThree())); } - private Map makeExpectedMapForThree() { - Map retMap = new HashMap(); + private Map makeExpectedMapForThree() { + Map retMap = new HashMap(); retMap.put(200, buildCodeResult(40, 2, 220, 200, 420)); retMap.put(400, buildCodeResult(0, 1, 0, 0, 0)); return retMap; From a2e06ca18ca16d48a803dfd33134d81970b7875f Mon Sep 17 00:00:00 2001 From: coderfengyun Date: Mon, 23 Dec 2013 11:28:48 +0800 Subject: [PATCH 126/196] refactor --- .../org/bench4q/agent/api/TestController.java | 92 ++++++++++--------- .../impl/AgentResultDataCollector.java | 38 +++++--- 2 files changed, 73 insertions(+), 57 deletions(-) diff --git a/src/main/java/org/bench4q/agent/api/TestController.java b/src/main/java/org/bench4q/agent/api/TestController.java index ba1a1f1b..88c9c46d 100644 --- a/src/main/java/org/bench4q/agent/api/TestController.java +++ b/src/main/java/org/bench4q/agent/api/TestController.java @@ -27,6 +27,7 @@ import org.bench4q.share.models.agent.AgentBriefStatusModel; import org.bench4q.share.models.agent.BehaviorBriefModel; import org.bench4q.share.models.agent.BehaviorStatusCodeResultModel; import org.bench4q.share.models.agent.CleanTestResultModel; +import org.bench4q.share.models.agent.PageBriefModel; import org.bench4q.share.models.agent.ParameterModel; import org.bench4q.share.models.agent.RunScenarioModel; import org.bench4q.share.models.agent.RunScenarioResultModel; @@ -192,6 +193,55 @@ public class TestController { return parameter; } + @RequestMapping(value = "/brief/{runId}/{behaviorId}", method = RequestMethod.GET) + @ResponseBody + public BehaviorBriefModel behaviorBrief(@PathVariable UUID runId, + @PathVariable int behaviorId) { + ScenarioContext scenarioContext = this.getScenarioEngine() + .getRunningTests().get(runId); + if (scenarioContext == null) { + return null; + } + Map map = scenarioContext + .getDataStatistics().getBehaviorBriefStatistics(behaviorId); + return buildBehaviorBrief(runId, behaviorId, map); + } + + private BehaviorBriefModel buildBehaviorBrief(UUID runId, int behaviorId, + Map map) { + List detailStatusCodeResultModels = new ArrayList(); + for (int statusCode : map.keySet()) { + BehaviorStatusCodeResultModel behaviorStatusCodeResultModel = new BehaviorStatusCodeResultModel(); + BehaviorStatusCodeResult detailStatusCodeResult = map + .get(statusCode); + behaviorStatusCodeResultModel.setStatusCode(statusCode); + behaviorStatusCodeResultModel + .setCount(detailStatusCodeResult.count); + behaviorStatusCodeResultModel + .setContentLength(detailStatusCodeResult.contentLength); + behaviorStatusCodeResultModel + .setMinResponseTime(detailStatusCodeResult.minResponseTime); + behaviorStatusCodeResultModel + .setMaxResponseTime(detailStatusCodeResult.maxResponseTime); + behaviorStatusCodeResultModel + .setContentType(detailStatusCodeResult.contentType); + behaviorStatusCodeResultModel + .setTotalResponseTimeThisTime(detailStatusCodeResult.totalResponseTimeThisTime); + detailStatusCodeResultModels.add(behaviorStatusCodeResultModel); + } + BehaviorBriefModel behaviorBriefModel = new BehaviorBriefModel(); + behaviorBriefModel.setBehaviorId(behaviorId); + behaviorBriefModel + .setDetailStatusCodeResultModels(detailStatusCodeResultModels); + return behaviorBriefModel; + } + + @RequestMapping(value = "/pageBrief/{pageId}") + public PageBriefModel pageBrief(@PathVariable int pageId) { + + return null; + } + @RequestMapping(value = "/behaviorsBrief/{runId}") @ResponseBody public TestBehaviorsBriefModel behaviorsBrief(@PathVariable UUID runId) { @@ -216,48 +266,6 @@ public class TestController { return ret; } - @RequestMapping(value = "/brief/{runId}/{behaviorId}", method = RequestMethod.GET) - @ResponseBody - public BehaviorBriefModel behaviorBrief(@PathVariable UUID runId, - @PathVariable int behaviorId) { - ScenarioContext scenarioContext = this.getScenarioEngine() - .getRunningTests().get(runId); - if (scenarioContext == null) { - return null; - } - Map map = scenarioContext - .getDataStatistics().getBehaviorBriefStatistics(behaviorId); - return buildBehaviorBrief(runId, behaviorId, map); - } - - private BehaviorBriefModel buildBehaviorBrief(UUID runId, int behaviorId, - Map map) { - List detailStatusCodeResultModels = new ArrayList(); - for (int statusCode : map.keySet()) { - BehaviorStatusCodeResultModel behaviorStatusCodeResultModel = new BehaviorStatusCodeResultModel(); - BehaviorStatusCodeResult detailStatusCodeResult = map.get(statusCode); - behaviorStatusCodeResultModel.setStatusCode(statusCode); - behaviorStatusCodeResultModel - .setCount(detailStatusCodeResult.count); - behaviorStatusCodeResultModel - .setContentLength(detailStatusCodeResult.contentLength); - behaviorStatusCodeResultModel - .setMinResponseTime(detailStatusCodeResult.minResponseTime); - behaviorStatusCodeResultModel - .setMaxResponseTime(detailStatusCodeResult.maxResponseTime); - behaviorStatusCodeResultModel - .setContentType(detailStatusCodeResult.contentType); - behaviorStatusCodeResultModel - .setTotalResponseTimeThisTime(detailStatusCodeResult.totalResponseTimeThisTime); - detailStatusCodeResultModels.add(behaviorStatusCodeResultModel); - } - BehaviorBriefModel behaviorBriefModel = new BehaviorBriefModel(); - behaviorBriefModel.setBehaviorId(behaviorId); - behaviorBriefModel - .setDetailStatusCodeResultModels(detailStatusCodeResultModels); - return behaviorBriefModel; - } - @RequestMapping(value = "/brief/{runId}", method = RequestMethod.GET) @ResponseBody public AgentBriefStatusModel brief(@PathVariable UUID runId) { diff --git a/src/main/java/org/bench4q/agent/datacollector/impl/AgentResultDataCollector.java b/src/main/java/org/bench4q/agent/datacollector/impl/AgentResultDataCollector.java index 67cb0167..a778ae5a 100644 --- a/src/main/java/org/bench4q/agent/datacollector/impl/AgentResultDataCollector.java +++ b/src/main/java/org/bench4q/agent/datacollector/impl/AgentResultDataCollector.java @@ -164,6 +164,12 @@ public class AgentResultDataCollector extends AbstractDataCollector { * @param behaviorResult */ private void addItem(BehaviorResult behaviorResult) { + statisticScenarioBriefResult(behaviorResult); + statisticPageBriefResult(behaviorResult); + statisticBehaviorBriefResult(behaviorResult); + } + + private void statisticScenarioBriefResult(BehaviorResult behaviorResult) { if (behaviorResult.isSuccess()) { this.successCountOfThisCall++; this.totalResponseTimeOfThisCall += behaviorResult @@ -183,11 +189,13 @@ public class AgentResultDataCollector extends AbstractDataCollector { } else { this.failCountOfThisCall++; } - - dealWithDetailResult(behaviorResult); } - private void dealWithDetailResult(BehaviorResult behaviorResult) { + private void statisticPageBriefResult(BehaviorResult behaviorResult) { + + } + + private void statisticBehaviorBriefResult(BehaviorResult behaviorResult) { insertWhenNotExist(behaviorResult); Map detailStatusMap = this.detailMap .get(behaviorResult.getBehaviorId()); @@ -199,24 +207,24 @@ public class AgentResultDataCollector extends AbstractDataCollector { .getContentType())); } - BehaviorStatusCodeResult detailResult = detailStatusMap + BehaviorStatusCodeResult statusCodeResult = detailStatusMap .get(behaviorResult.getStatusCode()); - detailResult.count++; + statusCodeResult.count++; if (!behaviorResult.isSuccess()) { - detailResult.maxResponseTime = 0; - detailResult.minResponseTime = 0; - detailResult.contentLength = 0; - detailResult.totalResponseTimeThisTime = 0; + statusCodeResult.maxResponseTime = 0; + statusCodeResult.minResponseTime = 0; + statusCodeResult.contentLength = 0; + statusCodeResult.totalResponseTimeThisTime = 0; return; } - detailResult.contentLength += behaviorResult.getContentLength(); - detailResult.totalResponseTimeThisTime += behaviorResult + statusCodeResult.contentLength += behaviorResult.getContentLength(); + statusCodeResult.totalResponseTimeThisTime += behaviorResult .getResponseTime(); - if (behaviorResult.getResponseTime() > detailResult.maxResponseTime) { - detailResult.maxResponseTime = behaviorResult.getResponseTime(); + if (behaviorResult.getResponseTime() > statusCodeResult.maxResponseTime) { + statusCodeResult.maxResponseTime = behaviorResult.getResponseTime(); } - if (behaviorResult.getResponseTime() < detailResult.minResponseTime) { - detailResult.minResponseTime = behaviorResult.getResponseTime(); + if (behaviorResult.getResponseTime() < statusCodeResult.minResponseTime) { + statusCodeResult.minResponseTime = behaviorResult.getResponseTime(); } } From 346653c6efa135ec6fddbf4020572f1713a9d19d Mon Sep 17 00:00:00 2001 From: coderfengyun Date: Mon, 23 Dec 2013 14:44:32 +0800 Subject: [PATCH 127/196] now, i can get the VUserCount --- .../org/bench4q/agent/api/TestController.java | 12 ++--- .../agent/scenario/ScenarioContext.java | 16 +++---- .../agent/scenario/ScenarioEngine.java | 45 ++++++++++++------- 3 files changed, 44 insertions(+), 29 deletions(-) diff --git a/src/main/java/org/bench4q/agent/api/TestController.java b/src/main/java/org/bench4q/agent/api/TestController.java index 88c9c46d..286921a5 100644 --- a/src/main/java/org/bench4q/agent/api/TestController.java +++ b/src/main/java/org/bench4q/agent/api/TestController.java @@ -238,7 +238,6 @@ public class TestController { @RequestMapping(value = "/pageBrief/{pageId}") public PageBriefModel pageBrief(@PathVariable int pageId) { - return null; } @@ -274,8 +273,11 @@ public class TestController { if (scenarioContext == null) { return null; } - return (AgentBriefStatusModel) scenarioContext.getDataStatistics() - .getScenarioBriefStatistics(); + AgentBriefStatusModel agentStatusModel = (AgentBriefStatusModel) scenarioContext + .getDataStatistics().getScenarioBriefStatistics(); + agentStatusModel.setvUserCount(scenarioContext.getExecutor() + .getActiveCount()); + return agentStatusModel; } @RequestMapping(value = "/stop/{runId}", method = { RequestMethod.GET, @@ -289,7 +291,7 @@ public class TestController { return null; } scenarioContext.setEndDate(new Date(System.currentTimeMillis())); - scenarioContext.getExecutorService().shutdownNow(); + scenarioContext.getExecutor().shutdownNow(); scenarioContext.setFinished(true); StopTestModel stopTestModel = new StopTestModel(); stopTestModel.setSuccess(true); @@ -304,7 +306,7 @@ public class TestController { if (scenarioContext == null) { return null; } - scenarioContext.getExecutorService().shutdownNow(); + scenarioContext.getExecutor().shutdownNow(); this.getScenarioEngine().getRunningTests().remove(runId); System.gc(); CleanTestResultModel cleanTestResultModel = new CleanTestResultModel(); diff --git a/src/main/java/org/bench4q/agent/scenario/ScenarioContext.java b/src/main/java/org/bench4q/agent/scenario/ScenarioContext.java index 1e407e10..ed040571 100644 --- a/src/main/java/org/bench4q/agent/scenario/ScenarioContext.java +++ b/src/main/java/org/bench4q/agent/scenario/ScenarioContext.java @@ -2,7 +2,7 @@ package org.bench4q.agent.scenario; import java.util.Date; import java.util.UUID; -import java.util.concurrent.ExecutorService; +import java.util.concurrent.ThreadPoolExecutor; import org.bench4q.agent.datacollector.impl.AgentResultDataCollector; import org.bench4q.agent.datacollector.interfaces.DataStatistics; @@ -10,7 +10,7 @@ import org.bench4q.agent.datacollector.interfaces.DataStatistics; public class ScenarioContext { private Date startDate; private Date endDate; - private ExecutorService executorService; + private ThreadPoolExecutor executor; private Scenario scenario; private boolean finished; private DataStatistics dataStatistics; @@ -31,12 +31,12 @@ public class ScenarioContext { this.endDate = endDate; } - public ExecutorService getExecutorService() { - return executorService; + public ThreadPoolExecutor getExecutor() { + return executor; } - public void setExecutorService(ExecutorService executorService) { - this.executorService = executorService; + public void setExecutorService(ThreadPoolExecutor executor) { + this.executor = executor; } public Scenario getScenario() { @@ -65,11 +65,11 @@ public class ScenarioContext { public static ScenarioContext buildScenarioContext(UUID testId, final Scenario scenario, int poolSize, - ExecutorService executorService) { + ThreadPoolExecutor executor) { ScenarioContext scenarioContext = new ScenarioContext(); scenarioContext.setScenario(scenario); scenarioContext.setStartDate(new Date(System.currentTimeMillis())); - scenarioContext.setExecutorService(executorService); + scenarioContext.setExecutorService(executor); // TODO:remove this direct dependency scenarioContext.setDataStatistics(new AgentResultDataCollector(testId)); return scenarioContext; diff --git a/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java b/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java index dd149a1e..79243d3c 100644 --- a/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java +++ b/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java @@ -6,6 +6,10 @@ import java.util.Map; import java.util.UUID; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; +import java.util.concurrent.SynchronousQueue; +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.plugin.Plugin; @@ -19,6 +23,7 @@ import org.springframework.stereotype.Component; @Component public class ScenarioEngine { + private static final long keepAliveTime = 10; private PluginManager pluginManager; private Map runningTests; private StorageHelper storageHelper; @@ -66,30 +71,38 @@ public class ScenarioEngine { public void runScenario(UUID runId, final Scenario scenario, int poolSize) { try { - ExecutorService executorService = Executors - .newFixedThreadPool(poolSize); + final SynchronousQueue workQueue = new SynchronousQueue(); + ThreadPoolExecutor executor = new ThreadPoolExecutor( + poolSize, poolSize, keepAliveTime, TimeUnit.MINUTES, + workQueue, new DiscardPolicy()); final ScenarioContext scenarioContext = ScenarioContext .buildScenarioContext(runId, scenario, poolSize, - executorService); - System.out.println(poolSize); - int i; + executor); this.getRunningTests().put(runId, scenarioContext); - Runnable runnable = new Runnable() { - public void run() { - while (!scenarioContext.getExecutorService().isShutdown()) { - doRunScenario(scenarioContext); - System.out.println("End for once"); - } - } - }; - for (i = 0; i < poolSize; i++) { - executorService.execute(runnable); - } + System.out.println(poolSize); + executeTasks(executor, scenarioContext); } catch (Exception e) { e.printStackTrace(); } } + private void executeTasks(final ExecutorService executorService, + final ScenarioContext scenarioContext) { + ExecutorService taskMaker = Executors.newSingleThreadExecutor(); + taskMaker.execute(new Runnable() { + public void run() { + while (true) { + executorService.execute(new Runnable() { + public void run() { + doRunScenario(scenarioContext); + System.out.println("end for once"); + } + }); + } + } + }); + } + public void doRunScenario(ScenarioContext context) { Map plugins = new HashMap(); preparePlugins(context.getScenario(), plugins); From 98544683ccbb5b2b8cf17671d6e971d887a78707 Mon Sep 17 00:00:00 2001 From: coderfengyun Date: Mon, 23 Dec 2013 14:48:02 +0800 Subject: [PATCH 128/196] refactor --- src/main/java/org/bench4q/agent/scenario/ScenarioContext.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/bench4q/agent/scenario/ScenarioContext.java b/src/main/java/org/bench4q/agent/scenario/ScenarioContext.java index ed040571..d28912a8 100644 --- a/src/main/java/org/bench4q/agent/scenario/ScenarioContext.java +++ b/src/main/java/org/bench4q/agent/scenario/ScenarioContext.java @@ -64,8 +64,7 @@ public class ScenarioContext { } public static ScenarioContext buildScenarioContext(UUID testId, - final Scenario scenario, int poolSize, - ThreadPoolExecutor executor) { + final Scenario scenario, int poolSize, ThreadPoolExecutor executor) { ScenarioContext scenarioContext = new ScenarioContext(); scenarioContext.setScenario(scenario); scenarioContext.setStartDate(new Date(System.currentTimeMillis())); @@ -74,4 +73,5 @@ public class ScenarioContext { scenarioContext.setDataStatistics(new AgentResultDataCollector(testId)); return scenarioContext; } + } From 6b5f9ce20686e50104af030a12ead91ad05fd85b Mon Sep 17 00:00:00 2001 From: coderfengyun Date: Mon, 23 Dec 2013 17:27:45 +0800 Subject: [PATCH 129/196] support for the behaviorBaseModel not abstract --- Scripts/goodForPage.xml | 2 +- .../org/bench4q/agent/api/TestController.java | 209 +++++++++--------- .../impl/AbstractDataCollector.java | 14 +- .../impl/AgentResultDataCollector.java | 36 ++- ...DataStatistics.java => DataCollector.java} | 5 +- .../bench4q/agent/scenario/PageResult.java | 40 ++++ .../org/bench4q/agent/scenario/Scenario.java | 111 ++++++++++ .../agent/scenario/ScenarioContext.java | 8 +- .../agent/scenario/behavior/Behavior.java | 4 +- .../scenario/behavior/BehaviorFactory.java | 6 +- .../scenario/behavior/TimerBehavior.java | 4 +- .../agent/scenario/behavior/UserBehavior.java | 4 +- .../agent/test/DataStatisticsTest.java | 26 +-- .../agent/test/DetailStatisticsTest.java | 37 ++-- .../agent/test/ExtractScenarioTest.java | 27 +++ .../agent/test/PageBriefStatisticsTest.java | 13 ++ .../agent/test/TestWithScriptFile.java | 2 +- .../bench4q/agent/test/model/ModelTest.java | 30 +-- .../test/model/UserBehaviorModelTest.java | 18 +- 19 files changed, 377 insertions(+), 219 deletions(-) rename src/main/java/org/bench4q/agent/datacollector/interfaces/{DataStatistics.java => DataCollector.java} (73%) create mode 100644 src/main/java/org/bench4q/agent/scenario/PageResult.java create mode 100644 src/test/java/org/bench4q/agent/test/ExtractScenarioTest.java create mode 100644 src/test/java/org/bench4q/agent/test/PageBriefStatisticsTest.java diff --git a/Scripts/goodForPage.xml b/Scripts/goodForPage.xml index ecc99da3..635a1995 100644 --- a/Scripts/goodForPage.xml +++ b/Scripts/goodForPage.xml @@ -1 +1 @@ -0Geturlhttp://133.133.12.3:8080/Bench4QTestCase/testcase.htmlparametershttp20-10Sleeptime267timer-11-11Geturlhttp://133.133.12.3:8080/Bench4QTestCase/script/base.jsparametershttp2Geturlhttp://133.133.12.3:8080/Bench4QTestCase/images/3.jpgparametershttp3Geturlhttp://133.133.12.3:8080/Bench4QTestCase/images/2.jpgparametershttp4Geturlhttp://133.133.12.3:8080/Bench4QTestCase/script/agentTable.jsparametershttp5Geturlhttp://133.133.12.3:8080/Bench4QTestCase/images/1.jpgparametershttp-1200Sleeptime42timer-13-10Sleeptime10timer-14-10Sleeptime5timer-15-10Sleeptime10timer-16-10httpHttptimerConstantTimer \ No newline at end of file +0Geturlhttp://133.133.12.3:8080/Bench4QTestCase/testcase.htmlparametersUSERBEHAVIORhttp20-10Sleeptime230TIMERBEHAVIORtimer-11-11Geturlhttp://133.133.12.3:8080/Bench4QTestCase/script/agentTable.jsparametersUSERBEHAVIORhttp2Geturlhttp://133.133.12.3:8080/Bench4QTestCase/images/3.jpgparametersUSERBEHAVIORhttp3Geturlhttp://133.133.12.3:8080/Bench4QTestCase/script/base.jsparametersUSERBEHAVIORhttp4Geturlhttp://133.133.12.3:8080/Bench4QTestCase/images/1.jpgparametersUSERBEHAVIORhttp5Geturlhttp://133.133.12.3:8080/Bench4QTestCase/images/2.jpgparametersUSERBEHAVIORhttp-1200Sleeptime96TIMERBEHAVIORtimer-13-10Sleeptime3TIMERBEHAVIORtimer-14-10Sleeptime10TIMERBEHAVIORtimer-15-10Sleeptime6TIMERBEHAVIORtimer-16-10httpHttptimerConstantTimer \ No newline at end of file diff --git a/src/main/java/org/bench4q/agent/api/TestController.java b/src/main/java/org/bench4q/agent/api/TestController.java index 286921a5..42c7847b 100644 --- a/src/main/java/org/bench4q/agent/api/TestController.java +++ b/src/main/java/org/bench4q/agent/api/TestController.java @@ -14,29 +14,19 @@ import javax.xml.bind.Marshaller; import org.apache.log4j.Logger; import org.bench4q.agent.datacollector.impl.BehaviorStatusCodeResult; -import org.bench4q.agent.scenario.Batch; -import org.bench4q.agent.scenario.Page; -import org.bench4q.agent.scenario.Parameter; import org.bench4q.agent.scenario.Scenario; import org.bench4q.agent.scenario.ScenarioContext; import org.bench4q.agent.scenario.ScenarioEngine; -import org.bench4q.agent.scenario.UsePlugin; import org.bench4q.agent.scenario.behavior.Behavior; -import org.bench4q.agent.scenario.behavior.BehaviorFactory; import org.bench4q.share.models.agent.AgentBriefStatusModel; import org.bench4q.share.models.agent.BehaviorBriefModel; import org.bench4q.share.models.agent.BehaviorStatusCodeResultModel; import org.bench4q.share.models.agent.CleanTestResultModel; import org.bench4q.share.models.agent.PageBriefModel; -import org.bench4q.share.models.agent.ParameterModel; import org.bench4q.share.models.agent.RunScenarioModel; import org.bench4q.share.models.agent.RunScenarioResultModel; import org.bench4q.share.models.agent.StopTestModel; import org.bench4q.share.models.agent.TestBehaviorsBriefModel; -import org.bench4q.share.models.agent.scriptrecord.BatchModel; -import org.bench4q.share.models.agent.scriptrecord.BehaviorBaseModel; -import org.bench4q.share.models.agent.scriptrecord.PageModel; -import org.bench4q.share.models.agent.scriptrecord.UsePluginModel; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; @@ -69,7 +59,8 @@ public class TestController { public RunScenarioResultModel run( @RequestBody RunScenarioModel runScenarioModel) throws UnknownHostException { - Scenario scenario = extractScenario(runScenarioModel); + // Scenario scenario = extractScenario(runScenarioModel); + Scenario scenario = Scenario.scenarioBuilder(runScenarioModel); UUID runId = UUID.randomUUID(); System.out.println(runScenarioModel.getPoolSize()); this.getLogger().info(marshalRunScenarioModel(runScenarioModel)); @@ -94,104 +85,104 @@ public class TestController { } - private Scenario extractScenario(RunScenarioModel runScenarioModel) { - Scenario scenario = new Scenario(); - scenario.setUsePlugins(new UsePlugin[runScenarioModel.getUsePlugins() - .size()]); - scenario.setPages(new Page[runScenarioModel.getPages().size()]); - extractUsePlugins(runScenarioModel, scenario); - extractPages(runScenarioModel, scenario); - return scenario; - } - - private void extractPages(RunScenarioModel runScenarioModel, - Scenario scenario) { - List pageModels = runScenarioModel.getPages(); - for (int i = 0; i < pageModels.size(); i++) { - PageModel pageModel = pageModels.get(i); - scenario.getPages()[i] = extractPage(pageModel); - } - } - - private Page extractPage(PageModel pageModel) { - Page page = new Page(); - page.setBatches(new Batch[pageModel.getBatches().size()]); - List batches = pageModel.getBatches(); - for (int i = 0; i < pageModel.getBatches().size(); i++) { - BatchModel batch = batches.get(i); - page.getBatches()[i] = extractBatch(batch); - } - return page; - } - - private Batch extractBatch(BatchModel batchModel) { - Batch batch = new Batch(); - batch.setBehaviors(new Behavior[batchModel.getBehaviors().size()]); - batch.setId(batchModel.getId()); - batch.setParentId(batchModel.getParentId()); - batch.setChildId(batchModel.getChildId()); - if (batchModel.getBehaviors() == null) { - return batch; - } - batch.setBehaviors(new Behavior[batchModel.getBehaviors().size()]); - for (int i = 0; i < batchModel.getBehaviors().size(); ++i) { - batch.getBehaviors()[i] = extractBehavior(batchModel.getBehaviors() - .get(i)); - } - return batch; - } - - private void extractUsePlugins(RunScenarioModel runScenarioModel, - Scenario scenario) { - int i; - List usePluginModels = runScenarioModel.getUsePlugins(); - for (i = 0; i < runScenarioModel.getUsePlugins().size(); i++) { - UsePluginModel usePluginModel = usePluginModels.get(i); - UsePlugin usePlugin = extractUsePlugin(usePluginModel); - scenario.getUsePlugins()[i] = usePlugin; - } - } - - private Behavior extractBehavior(BehaviorBaseModel behaviorModel) { - Behavior behavior = BehaviorFactory.getBuisinessObject(behaviorModel); - behavior.setName(behaviorModel.getName()); - behavior.setUse(behaviorModel.getUse()); - behavior.setId(behaviorModel.getId()); - behavior.setParameters(new Parameter[behaviorModel.getParameters() - .size()]); - - int k = 0; - for (k = 0; k < behaviorModel.getParameters().size(); k++) { - ParameterModel parameterModel = behaviorModel.getParameters() - .get(k); - Parameter parameter = extractParameter(parameterModel); - behavior.getParameters()[k] = parameter; - } - return behavior; - } - - private UsePlugin extractUsePlugin(UsePluginModel usePluginModel) { - UsePlugin usePlugin = new UsePlugin(); - usePlugin.setId(usePluginModel.getId()); - usePlugin.setName(usePluginModel.getName()); - usePlugin.setParameters(new Parameter[usePluginModel.getParameters() - .size()]); - int k = 0; - for (k = 0; k < usePluginModel.getParameters().size(); k++) { - ParameterModel parameterModel = usePluginModel.getParameters().get( - k); - Parameter parameter = extractParameter(parameterModel); - usePlugin.getParameters()[k] = parameter; - } - return usePlugin; - } - - private Parameter extractParameter(ParameterModel parameterModel) { - Parameter parameter = new Parameter(); - parameter.setKey(parameterModel.getKey()); - parameter.setValue(parameterModel.getValue()); - return parameter; - } + // private Scenario extractScenario(RunScenarioModel runScenarioModel) { + // Scenario scenario = new Scenario(); + // scenario.setUsePlugins(new UsePlugin[runScenarioModel.getUsePlugins() + // .size()]); + // scenario.setPages(new Page[runScenarioModel.getPages().size()]); + // extractUsePlugins(runScenarioModel, scenario); + // extractPages(runScenarioModel, scenario); + // return scenario; + // } + // + // private void extractPages(RunScenarioModel runScenarioModel, + // Scenario scenario) { + // List pageModels = runScenarioModel.getPages(); + // for (int i = 0; i < pageModels.size(); i++) { + // PageModel pageModel = pageModels.get(i); + // scenario.getPages()[i] = extractPage(pageModel); + // } + // } + // + // private Page extractPage(PageModel pageModel) { + // Page page = new Page(); + // page.setBatches(new Batch[pageModel.getBatches().size()]); + // List batches = pageModel.getBatches(); + // for (int i = 0; i < pageModel.getBatches().size(); i++) { + // BatchModel batch = batches.get(i); + // page.getBatches()[i] = extractBatch(batch); + // } + // return page; + // } + // + // private Batch extractBatch(BatchModel batchModel) { + // Batch batch = new Batch(); + // batch.setBehaviors(new Behavior[batchModel.getBehaviors().size()]); + // batch.setId(batchModel.getId()); + // batch.setParentId(batchModel.getParentId()); + // batch.setChildId(batchModel.getChildId()); + // if (batchModel.getBehaviors() == null) { + // return batch; + // } + // batch.setBehaviors(new Behavior[batchModel.getBehaviors().size()]); + // for (int i = 0; i < batchModel.getBehaviors().size(); ++i) { + // batch.getBehaviors()[i] = extractBehavior(batchModel.getBehaviors() + // .get(i)); + // } + // return batch; + // } + // + // private void extractUsePlugins(RunScenarioModel runScenarioModel, + // Scenario scenario) { + // int i; + // List usePluginModels = runScenarioModel.getUsePlugins(); + // for (i = 0; i < runScenarioModel.getUsePlugins().size(); i++) { + // UsePluginModel usePluginModel = usePluginModels.get(i); + // UsePlugin usePlugin = extractUsePlugin(usePluginModel); + // scenario.getUsePlugins()[i] = usePlugin; + // } + // } + // + // private Behavior extractBehavior(BehaviorBaseModel behaviorModel) { + // Behavior behavior = BehaviorFactory.getBuisinessObject(behaviorModel); + // behavior.setName(behaviorModel.getName()); + // behavior.setUse(behaviorModel.getUse()); + // behavior.setId(behaviorModel.getId()); + // behavior.setParameters(new Parameter[behaviorModel.getParameters() + // .size()]); + // + // int k = 0; + // for (k = 0; k < behaviorModel.getParameters().size(); k++) { + // ParameterModel parameterModel = behaviorModel.getParameters() + // .get(k); + // Parameter parameter = extractParameter(parameterModel); + // behavior.getParameters()[k] = parameter; + // } + // return behavior; + // } + // + // private UsePlugin extractUsePlugin(UsePluginModel usePluginModel) { + // UsePlugin usePlugin = new UsePlugin(); + // usePlugin.setId(usePluginModel.getId()); + // usePlugin.setName(usePluginModel.getName()); + // usePlugin.setParameters(new Parameter[usePluginModel.getParameters() + // .size()]); + // int k = 0; + // for (k = 0; k < usePluginModel.getParameters().size(); k++) { + // ParameterModel parameterModel = usePluginModel.getParameters().get( + // k); + // Parameter parameter = extractParameter(parameterModel); + // usePlugin.getParameters()[k] = parameter; + // } + // return usePlugin; + // } + // + // private Parameter extractParameter(ParameterModel parameterModel) { + // Parameter parameter = new Parameter(); + // parameter.setKey(parameterModel.getKey()); + // parameter.setValue(parameterModel.getValue()); + // return parameter; + // } @RequestMapping(value = "/brief/{runId}/{behaviorId}", method = RequestMethod.GET) @ResponseBody diff --git a/src/main/java/org/bench4q/agent/datacollector/impl/AbstractDataCollector.java b/src/main/java/org/bench4q/agent/datacollector/impl/AbstractDataCollector.java index ca71e11f..b15b60fe 100644 --- a/src/main/java/org/bench4q/agent/datacollector/impl/AbstractDataCollector.java +++ b/src/main/java/org/bench4q/agent/datacollector/impl/AbstractDataCollector.java @@ -5,13 +5,14 @@ import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import org.bench4q.agent.Main; -import org.bench4q.agent.datacollector.interfaces.DataStatistics; +import org.bench4q.agent.datacollector.interfaces.DataCollector; import org.bench4q.agent.helper.ApplicationContextHelper; import org.bench4q.agent.scenario.BehaviorResult; +import org.bench4q.agent.scenario.PageResult; import org.bench4q.agent.storage.StorageHelper; import org.bench4q.share.models.agent.BehaviorResultModel; -public abstract class AbstractDataCollector implements DataStatistics { +public abstract class AbstractDataCollector implements DataCollector { protected StorageHelper storageHelper; protected StorageHelper getStorageHelper() { @@ -40,11 +41,18 @@ public abstract class AbstractDataCollector implements DataStatistics { calculateSavePath(behaviorResult)); } }; - ExecutorService executorService = Executors.newCachedThreadPool(); + ExecutorService executorService = Executors + .newSingleThreadScheduledExecutor(); executorService.execute(runnable); executorService.shutdown(); } + public void add(final PageResult pageResult) { + for (BehaviorResult behaviorResult : pageResult.getBehaviorResults()) { + add(behaviorResult); + } + } + private BehaviorResultModel buildBehaviorResultModel( BehaviorResult behaviorResult) { BehaviorResultModel resultModel = new BehaviorResultModel(); diff --git a/src/main/java/org/bench4q/agent/datacollector/impl/AgentResultDataCollector.java b/src/main/java/org/bench4q/agent/datacollector/impl/AgentResultDataCollector.java index a778ae5a..0aeab000 100644 --- a/src/main/java/org/bench4q/agent/datacollector/impl/AgentResultDataCollector.java +++ b/src/main/java/org/bench4q/agent/datacollector/impl/AgentResultDataCollector.java @@ -8,6 +8,7 @@ import java.util.Map; import java.util.UUID; import org.bench4q.agent.scenario.BehaviorResult; +import org.bench4q.agent.scenario.PageResult; import org.bench4q.share.models.agent.AgentBriefStatusModel; /** @@ -163,11 +164,6 @@ public class AgentResultDataCollector extends AbstractDataCollector { * * @param behaviorResult */ - private void addItem(BehaviorResult behaviorResult) { - statisticScenarioBriefResult(behaviorResult); - statisticPageBriefResult(behaviorResult); - statisticBehaviorBriefResult(behaviorResult); - } private void statisticScenarioBriefResult(BehaviorResult behaviorResult) { if (behaviorResult.isSuccess()) { @@ -191,7 +187,7 @@ public class AgentResultDataCollector extends AbstractDataCollector { } } - private void statisticPageBriefResult(BehaviorResult behaviorResult) { + private void statisticPageBriefResult(PageResult pageResult) { } @@ -235,11 +231,11 @@ public class AgentResultDataCollector extends AbstractDataCollector { } } - @Override - public void add(BehaviorResult behaviorResult) { - super.add(behaviorResult); - addItem(behaviorResult); - } + // @Override + // public void add(BehaviorResult behaviorResult) { + // super.add(behaviorResult); + // addItem(behaviorResult); + // } @Override protected String calculateSavePath(BehaviorResult behaviorResult) { @@ -252,6 +248,24 @@ public class AgentResultDataCollector extends AbstractDataCollector { + new SimpleDateFormat("hhmm") + ".txt"; } + @Override + public void add(PageResult pageResult) { + super.add(pageResult); + statisticPageBriefResult(pageResult); + for (BehaviorResult behaviorResult : pageResult.getBehaviorResults()) { + statisticScenarioBriefResult(behaviorResult); + statisticBehaviorBriefResult(behaviorResult); + } + } + + // TODO: delete this + @Override + public void add(BehaviorResult behaviorResult) { + super.add(behaviorResult); + statisticScenarioBriefResult(behaviorResult); + statisticBehaviorBriefResult(behaviorResult); + } + @Override public Map getBehaviorBriefStatistics( int behaviorId) { diff --git a/src/main/java/org/bench4q/agent/datacollector/interfaces/DataStatistics.java b/src/main/java/org/bench4q/agent/datacollector/interfaces/DataCollector.java similarity index 73% rename from src/main/java/org/bench4q/agent/datacollector/interfaces/DataStatistics.java rename to src/main/java/org/bench4q/agent/datacollector/interfaces/DataCollector.java index 081e0abd..6f15ef40 100644 --- a/src/main/java/org/bench4q/agent/datacollector/interfaces/DataStatistics.java +++ b/src/main/java/org/bench4q/agent/datacollector/interfaces/DataCollector.java @@ -4,10 +4,13 @@ import java.util.Map; import org.bench4q.agent.datacollector.impl.BehaviorStatusCodeResult; import org.bench4q.agent.scenario.BehaviorResult; +import org.bench4q.agent.scenario.PageResult; -public interface DataStatistics { +public interface DataCollector { public void add(BehaviorResult behaviorResult); + public void add(PageResult pageResult); + public Object getScenarioBriefStatistics(); public Map getBehaviorBriefStatistics( diff --git a/src/main/java/org/bench4q/agent/scenario/PageResult.java b/src/main/java/org/bench4q/agent/scenario/PageResult.java new file mode 100644 index 00000000..01fb9c68 --- /dev/null +++ b/src/main/java/org/bench4q/agent/scenario/PageResult.java @@ -0,0 +1,40 @@ +package org.bench4q.agent.scenario; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +public class PageResult { + private int pageId; + private List behaviorResults; + + public int getPageId() { + return pageId; + } + + private void setPageId(int pageId) { + this.pageId = pageId; + } + + public List getBehaviorResults() { + return Collections.unmodifiableList(behaviorResults); + } + + private void setBehaviorResults(List behaviorResults) { + this.behaviorResults = behaviorResults; + } + + private PageResult() { + } + + public static PageResult buildPageResult(int pageId, + List behaviorResults) { + PageResult result = new PageResult(); + result.setPageId(pageId); + if (behaviorResults == null) { + behaviorResults = new ArrayList(); + } + result.setBehaviorResults(behaviorResults); + return result; + } +} diff --git a/src/main/java/org/bench4q/agent/scenario/Scenario.java b/src/main/java/org/bench4q/agent/scenario/Scenario.java index 198b96cb..56bd58aa 100644 --- a/src/main/java/org/bench4q/agent/scenario/Scenario.java +++ b/src/main/java/org/bench4q/agent/scenario/Scenario.java @@ -5,6 +5,13 @@ import java.util.Collections; import java.util.List; import org.bench4q.agent.scenario.behavior.Behavior; +import org.bench4q.agent.scenario.behavior.BehaviorFactory; +import org.bench4q.share.models.agent.ParameterModel; +import org.bench4q.share.models.agent.RunScenarioModel; +import org.bench4q.share.models.agent.scriptrecord.BatchModel; +import org.bench4q.share.models.agent.scriptrecord.BehaviorBaseModel; +import org.bench4q.share.models.agent.scriptrecord.PageModel; +import org.bench4q.share.models.agent.scriptrecord.UsePluginModel; public class Scenario { private UsePlugin[] usePlugins; @@ -53,4 +60,108 @@ public class Scenario { } return Collections.unmodifiableList(behaviors); } + + public static Scenario scenarioBuilder(RunScenarioModel scenarioModel) { + Scenario scenario = extractScenario(scenarioModel); + return scenario; + } + + private static Scenario extractScenario(RunScenarioModel runScenarioModel) { + Scenario scenario = new Scenario(); + scenario.setUsePlugins(new UsePlugin[runScenarioModel.getUsePlugins() + .size()]); + scenario.setPages(new Page[runScenarioModel.getPages().size()]); + extractUsePlugins(runScenarioModel, scenario); + extractPages(runScenarioModel, scenario); + return scenario; + } + + private static void extractPages(RunScenarioModel runScenarioModel, + Scenario scenario) { + List pageModels = runScenarioModel.getPages(); + for (int i = 0; i < pageModels.size(); i++) { + PageModel pageModel = pageModels.get(i); + scenario.getPages()[i] = extractPage(pageModel); + } + } + + private static Page extractPage(PageModel pageModel) { + Page page = new Page(); + page.setBatches(new Batch[pageModel.getBatches().size()]); + List batches = pageModel.getBatches(); + for (int i = 0; i < pageModel.getBatches().size(); i++) { + BatchModel batch = batches.get(i); + page.getBatches()[i] = extractBatch(batch); + } + return page; + } + + private static Batch extractBatch(BatchModel batchModel) { + Batch batch = new Batch(); + batch.setBehaviors(new Behavior[batchModel.getBehaviors().size()]); + batch.setId(batchModel.getId()); + batch.setParentId(batchModel.getParentId()); + batch.setChildId(batchModel.getChildId()); + if (batchModel.getBehaviors() == null) { + return batch; + } + batch.setBehaviors(new Behavior[batchModel.getBehaviors().size()]); + for (int i = 0; i < batchModel.getBehaviors().size(); ++i) { + batch.getBehaviors()[i] = extractBehavior(batchModel.getBehaviors() + .get(i)); + } + return batch; + } + + private static void extractUsePlugins(RunScenarioModel runScenarioModel, + Scenario scenario) { + int i; + List usePluginModels = runScenarioModel.getUsePlugins(); + for (i = 0; i < runScenarioModel.getUsePlugins().size(); i++) { + UsePluginModel usePluginModel = usePluginModels.get(i); + UsePlugin usePlugin = extractUsePlugin(usePluginModel); + scenario.getUsePlugins()[i] = usePlugin; + } + } + + private static Behavior extractBehavior(BehaviorBaseModel behaviorModel) { + Behavior behavior = BehaviorFactory.getBuisinessObject(behaviorModel); + behavior.setName(behaviorModel.getName()); + behavior.setUse(behaviorModel.getUse()); + behavior.setId(behaviorModel.getId()); + behavior.setParameters(new Parameter[behaviorModel.getParameters() + .size()]); + + int k = 0; + for (k = 0; k < behaviorModel.getParameters().size(); k++) { + ParameterModel parameterModel = behaviorModel.getParameters() + .get(k); + Parameter parameter = extractParameter(parameterModel); + behavior.getParameters()[k] = parameter; + } + return behavior; + } + + private static UsePlugin extractUsePlugin(UsePluginModel usePluginModel) { + UsePlugin usePlugin = new UsePlugin(); + usePlugin.setId(usePluginModel.getId()); + usePlugin.setName(usePluginModel.getName()); + usePlugin.setParameters(new Parameter[usePluginModel.getParameters() + .size()]); + int k = 0; + for (k = 0; k < usePluginModel.getParameters().size(); k++) { + ParameterModel parameterModel = usePluginModel.getParameters().get( + k); + Parameter parameter = extractParameter(parameterModel); + usePlugin.getParameters()[k] = parameter; + } + return usePlugin; + } + + private static Parameter extractParameter(ParameterModel parameterModel) { + Parameter parameter = new Parameter(); + parameter.setKey(parameterModel.getKey()); + parameter.setValue(parameterModel.getValue()); + return parameter; + } } diff --git a/src/main/java/org/bench4q/agent/scenario/ScenarioContext.java b/src/main/java/org/bench4q/agent/scenario/ScenarioContext.java index d28912a8..a919e007 100644 --- a/src/main/java/org/bench4q/agent/scenario/ScenarioContext.java +++ b/src/main/java/org/bench4q/agent/scenario/ScenarioContext.java @@ -5,7 +5,7 @@ import java.util.UUID; import java.util.concurrent.ThreadPoolExecutor; import org.bench4q.agent.datacollector.impl.AgentResultDataCollector; -import org.bench4q.agent.datacollector.interfaces.DataStatistics; +import org.bench4q.agent.datacollector.interfaces.DataCollector; public class ScenarioContext { private Date startDate; @@ -13,7 +13,7 @@ public class ScenarioContext { private ThreadPoolExecutor executor; private Scenario scenario; private boolean finished; - private DataStatistics dataStatistics; + private DataCollector dataStatistics; public Date getStartDate() { return startDate; @@ -55,11 +55,11 @@ public class ScenarioContext { this.finished = finished; } - public DataStatistics getDataStatistics() { + public DataCollector getDataStatistics() { return dataStatistics; } - private void setDataStatistics(DataStatistics dataStatistics) { + private void setDataStatistics(DataCollector dataStatistics) { this.dataStatistics = dataStatistics; } diff --git a/src/main/java/org/bench4q/agent/scenario/behavior/Behavior.java b/src/main/java/org/bench4q/agent/scenario/behavior/Behavior.java index 84825471..c94b6acc 100644 --- a/src/main/java/org/bench4q/agent/scenario/behavior/Behavior.java +++ b/src/main/java/org/bench4q/agent/scenario/behavior/Behavior.java @@ -3,7 +3,7 @@ package org.bench4q.agent.scenario.behavior; import java.util.Map; import org.bench4q.agent.datacollector.impl.BehaviorStatusCodeResult; -import org.bench4q.agent.datacollector.interfaces.DataStatistics; +import org.bench4q.agent.datacollector.interfaces.DataCollector; import org.bench4q.agent.scenario.Parameter; public abstract class Behavior { @@ -47,5 +47,5 @@ public abstract class Behavior { public abstract boolean shouldBeCountResponseTime(); public abstract Map getBehaviorBriefResult( - DataStatistics dataStatistics); + DataCollector dataStatistics); } diff --git a/src/main/java/org/bench4q/agent/scenario/behavior/BehaviorFactory.java b/src/main/java/org/bench4q/agent/scenario/behavior/BehaviorFactory.java index a8724867..be82e11e 100644 --- a/src/main/java/org/bench4q/agent/scenario/behavior/BehaviorFactory.java +++ b/src/main/java/org/bench4q/agent/scenario/behavior/BehaviorFactory.java @@ -1,14 +1,12 @@ package org.bench4q.agent.scenario.behavior; import org.bench4q.share.models.agent.scriptrecord.BehaviorBaseModel; -import org.bench4q.share.models.agent.scriptrecord.TimerBehaviorModel; -import org.bench4q.share.models.agent.scriptrecord.UserBehaviorModel; public class BehaviorFactory { public static Behavior getBuisinessObject(BehaviorBaseModel modelInput) { - if (modelInput instanceof TimerBehaviorModel) { + if (modelInput.getType().equalsIgnoreCase("TIMERBEHAVIOR")) { return new TimerBehavior(); - } else if (modelInput instanceof UserBehaviorModel) { + } else if (modelInput.getType().equalsIgnoreCase("USERBEHAVIOR")) { return new UserBehavior(); } return null; diff --git a/src/main/java/org/bench4q/agent/scenario/behavior/TimerBehavior.java b/src/main/java/org/bench4q/agent/scenario/behavior/TimerBehavior.java index 32397c99..25414e28 100644 --- a/src/main/java/org/bench4q/agent/scenario/behavior/TimerBehavior.java +++ b/src/main/java/org/bench4q/agent/scenario/behavior/TimerBehavior.java @@ -3,7 +3,7 @@ package org.bench4q.agent.scenario.behavior; import java.util.Map; import org.bench4q.agent.datacollector.impl.BehaviorStatusCodeResult; -import org.bench4q.agent.datacollector.interfaces.DataStatistics; +import org.bench4q.agent.datacollector.interfaces.DataCollector; public class TimerBehavior extends Behavior { @@ -14,7 +14,7 @@ public class TimerBehavior extends Behavior { @Override public Map getBehaviorBriefResult( - DataStatistics dataStatistics) { + DataCollector dataStatistics) { return null; } diff --git a/src/main/java/org/bench4q/agent/scenario/behavior/UserBehavior.java b/src/main/java/org/bench4q/agent/scenario/behavior/UserBehavior.java index 851a2c98..5b6490c9 100644 --- a/src/main/java/org/bench4q/agent/scenario/behavior/UserBehavior.java +++ b/src/main/java/org/bench4q/agent/scenario/behavior/UserBehavior.java @@ -3,7 +3,7 @@ package org.bench4q.agent.scenario.behavior; import java.util.Map; import org.bench4q.agent.datacollector.impl.BehaviorStatusCodeResult; -import org.bench4q.agent.datacollector.interfaces.DataStatistics; +import org.bench4q.agent.datacollector.interfaces.DataCollector; public class UserBehavior extends Behavior { @Override @@ -13,7 +13,7 @@ public class UserBehavior extends Behavior { @Override public Map getBehaviorBriefResult( - DataStatistics dataStatistics) { + DataCollector dataStatistics) { return dataStatistics.getBehaviorBriefStatistics(this.getId()); } diff --git a/src/test/java/org/bench4q/agent/test/DataStatisticsTest.java b/src/test/java/org/bench4q/agent/test/DataStatisticsTest.java index ec070ee6..739e88b5 100644 --- a/src/test/java/org/bench4q/agent/test/DataStatisticsTest.java +++ b/src/test/java/org/bench4q/agent/test/DataStatisticsTest.java @@ -8,8 +8,9 @@ import java.util.List; import java.util.UUID; import org.bench4q.agent.datacollector.impl.AgentResultDataCollector; -import org.bench4q.agent.datacollector.interfaces.DataStatistics; +import org.bench4q.agent.datacollector.interfaces.DataCollector; import org.bench4q.agent.scenario.BehaviorResult; +import org.bench4q.agent.scenario.PageResult; import org.bench4q.agent.storage.StorageHelper; import org.bench4q.share.models.agent.AgentBriefStatusModel; import org.junit.Test; @@ -17,13 +18,13 @@ import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class DataStatisticsTest { - private DataStatistics dataStatistics; + private DataCollector dataStatistics; - private DataStatistics getDataStatistics() { + protected DataCollector getDataStatistics() { return dataStatistics; } - private void setDataStatistics(DataStatistics dataStatistics) { + private void setDataStatistics(DataCollector dataStatistics) { this.dataStatistics = dataStatistics; } @@ -44,9 +45,7 @@ public class DataStatisticsTest { @Test public void addZeroBriefTest() { - for (BehaviorResult behaviorResult : makeBehaviorResultList(0)) { - this.getDataStatistics().add(behaviorResult); - } + this.getDataStatistics().add(makePageResultWithBehaviorResult(0)); AgentBriefStatusModel model = (AgentBriefStatusModel) this .getDataStatistics().getScenarioBriefStatistics(); @@ -57,9 +56,7 @@ public class DataStatisticsTest { @Test public void addOneBriefTest() throws InterruptedException { - for (BehaviorResult behaviorResult : makeBehaviorResultList(1)) { - this.getDataStatistics().add(behaviorResult); - } + this.getDataStatistics().add(makePageResultWithBehaviorResult(1)); Thread.sleep(100); AgentBriefStatusModel model = (AgentBriefStatusModel) this @@ -72,9 +69,7 @@ public class DataStatisticsTest { @Test public void addTwoBriefTest() throws InterruptedException { - for (BehaviorResult behaviorResult : makeBehaviorResultList(2)) { - this.getDataStatistics().add(behaviorResult); - } + this.getDataStatistics().add(makePageResultWithBehaviorResult(2)); Thread.sleep(100); AgentBriefStatusModel model = (AgentBriefStatusModel) this .getDataStatistics().getScenarioBriefStatistics(); @@ -130,14 +125,15 @@ public class DataStatisticsTest { return model; } - public static List makeBehaviorResultList(int count) { + public static PageResult makePageResultWithBehaviorResult(int count) { + List behaviorResults = new ArrayList(); for (int i = 0; i < count; i++) { int statusCode = i % 2 == 0 ? 200 : 400; behaviorResults.add(buildBehaviorResult(200 + 10 * i, i % 2 == 0, statusCode, 1)); } - return behaviorResults; + return PageResult.buildPageResult(2, behaviorResults); } public static BehaviorResult buildBehaviorResult(long responseTime, diff --git a/src/test/java/org/bench4q/agent/test/DetailStatisticsTest.java b/src/test/java/org/bench4q/agent/test/DetailStatisticsTest.java index d1558b7d..665d085d 100644 --- a/src/test/java/org/bench4q/agent/test/DetailStatisticsTest.java +++ b/src/test/java/org/bench4q/agent/test/DetailStatisticsTest.java @@ -8,21 +8,20 @@ import java.util.UUID; import org.bench4q.agent.datacollector.impl.AgentResultDataCollector; import org.bench4q.agent.datacollector.impl.BehaviorStatusCodeResult; -import org.bench4q.agent.datacollector.interfaces.DataStatistics; -import org.bench4q.agent.scenario.BehaviorResult; +import org.bench4q.agent.datacollector.interfaces.DataCollector; import org.bench4q.agent.storage.StorageHelper; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class DetailStatisticsTest { - private DataStatistics detailStatistics; + private DataCollector detailStatistics; - private DataStatistics getDetailStatistics() { + private DataCollector getDetailStatistics() { return detailStatistics; } - private void setDetailStatistics(DataStatistics detailStatistics) { + private void setDetailStatistics(DataCollector detailStatistics) { this.detailStatistics = detailStatistics; } @@ -43,10 +42,8 @@ public class DetailStatisticsTest { @Test public void addZeroTest() { - for (BehaviorResult behaviorResult : DataStatisticsTest - .makeBehaviorResultList(0)) { - this.getDetailStatistics().add(behaviorResult); - } + this.getDetailStatistics().add( + DataStatisticsTest.makePageResultWithBehaviorResult(0)); Object object = this.detailStatistics.getBehaviorBriefStatistics(0); assertEquals(null, object); @@ -54,15 +51,13 @@ public class DetailStatisticsTest { @Test public void addOneDetailTest() { - for (BehaviorResult behaviorResult : DataStatisticsTest - .makeBehaviorResultList(1)) { - this.getDetailStatistics().add(behaviorResult); - } + this.getDetailStatistics().add( + DataStatisticsTest.makePageResultWithBehaviorResult(1)); Map map = this.detailStatistics .getBehaviorBriefStatistics(1); BehaviorStatusCodeResult actualResult = map.get(200); - actualResult.equals(makeExpectedResultForOne()); + assertTrue(actualResult.equals(makeExpectedResultForOne())); } private BehaviorStatusCodeResult makeExpectedResultForOne() { @@ -71,19 +66,17 @@ public class DetailStatisticsTest { ret.count = 1; ret.maxResponseTime = 200; ret.minResponseTime = 200; + ret.totalResponseTimeThisTime = 200; return ret; } @Test public void addTwoDetailTest() { - for (BehaviorResult behaviorResult : DataStatisticsTest - .makeBehaviorResultList(2)) { - this.getDetailStatistics().add(behaviorResult); - } + this.getDetailStatistics().add( + DataStatisticsTest.makePageResultWithBehaviorResult(2)); Map map = this.detailStatistics .getBehaviorBriefStatistics(1); assertTrue(mapEquals(map, makeExpectedMapForTwo())); - // DetailResult ex } private Map makeExpectedMapForTwo() { @@ -121,10 +114,8 @@ public class DetailStatisticsTest { @Test public void addThreeTest() { - for (BehaviorResult behaviorResult : DataStatisticsTest - .makeBehaviorResultList(3)) { - this.getDetailStatistics().add(behaviorResult); - } + this.getDetailStatistics().add( + DataStatisticsTest.makePageResultWithBehaviorResult(3)); Map mapActual = this .getDetailStatistics().getBehaviorBriefStatistics(1); assertTrue(mapEquals(mapActual, makeExpectedMapForThree())); diff --git a/src/test/java/org/bench4q/agent/test/ExtractScenarioTest.java b/src/test/java/org/bench4q/agent/test/ExtractScenarioTest.java new file mode 100644 index 00000000..f6e137e8 --- /dev/null +++ b/src/test/java/org/bench4q/agent/test/ExtractScenarioTest.java @@ -0,0 +1,27 @@ +package org.bench4q.agent.test; + +import static org.junit.Assert.*; + +import java.io.File; +import java.io.IOException; + +import javax.xml.bind.JAXBException; + +import org.apache.commons.io.FileUtils; +import org.bench4q.agent.scenario.Scenario; +import org.bench4q.share.helper.MarshalHelper; +import org.bench4q.share.models.agent.RunScenarioModel; +import org.junit.Test; + +public class ExtractScenarioTest { + + @Test + public void test() throws JAXBException, IOException { + RunScenarioModel runScenarioModel = (RunScenarioModel) MarshalHelper + .unmarshal(RunScenarioModel.class, FileUtils + .readFileToString(new File("Scripts/goodForPage.xml"))); + Scenario scenario = Scenario.scenarioBuilder(runScenarioModel); + + assertTrue(scenario.getPages().length > 0); + } +} diff --git a/src/test/java/org/bench4q/agent/test/PageBriefStatisticsTest.java b/src/test/java/org/bench4q/agent/test/PageBriefStatisticsTest.java new file mode 100644 index 00000000..8cee3b07 --- /dev/null +++ b/src/test/java/org/bench4q/agent/test/PageBriefStatisticsTest.java @@ -0,0 +1,13 @@ +package org.bench4q.agent.test; + +import static org.junit.Assert.*; + +import org.junit.Test; + +public class PageBriefStatisticsTest extends DataStatisticsTest { + @Test + public void testAddPageResultWithZeroBehaviorResult() { + // this.getDataStatistics().add(); + fail(); + } +} diff --git a/src/test/java/org/bench4q/agent/test/TestWithScriptFile.java b/src/test/java/org/bench4q/agent/test/TestWithScriptFile.java index fe511ae2..e6d29e9b 100644 --- a/src/test/java/org/bench4q/agent/test/TestWithScriptFile.java +++ b/src/test/java/org/bench4q/agent/test/TestWithScriptFile.java @@ -145,7 +145,7 @@ public class TestWithScriptFile { private void behaviorBrief() throws IOException, JAXBException { System.out.println("Enter behaviorBrief!"); HttpResponse httpResponse = this.getHttpRequester().sendGet( - this.url + "/brief/" + this.getTestId().toString() + "/1", + this.url + "/brief/" + this.getTestId().toString() + "/0", null, null); BehaviorBriefModel behaviorBriefModel = (BehaviorBriefModel) MarshalHelper .unmarshal(BehaviorBriefModel.class, httpResponse.getContent()); diff --git a/src/test/java/org/bench4q/agent/test/model/ModelTest.java b/src/test/java/org/bench4q/agent/test/model/ModelTest.java index 31dc3ed5..cf404057 100644 --- a/src/test/java/org/bench4q/agent/test/model/ModelTest.java +++ b/src/test/java/org/bench4q/agent/test/model/ModelTest.java @@ -1,6 +1,5 @@ package org.bench4q.agent.test.model; -import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; @@ -14,39 +13,18 @@ import org.junit.Test; import static org.junit.Assert.*; @XmlRootElement(name = "modelTest") -public class ModelTest extends BehaviorBaseModel { - public String getModelString() { - ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); - try { - JAXBContext.newInstance(this.getClass()).createMarshaller() - .marshal(this, outputStream); - } catch (JAXBException e) { - e.printStackTrace(); - - } - System.out.println(outputStream.toString()); - return outputStream.toString(); - } - - @Test - public void modelVerify() { - this.setName("test"); - this.setUse("xml"); - this.setParameters(null); - this.getModelString(); - } +public class ModelTest { @Test public void unmarshalVerify() throws IOException, JAXBException { Object object = JAXBContext - .newInstance(this.getClass()) + .newInstance(BehaviorBaseModel.class) .createUnmarshaller() .unmarshal( new File("Scripts" + System.getProperty("file.separator") - + "behaviorModel.txt")); - - assertTrue(object instanceof ModelTest); + + "behaviorModel.xml")); + assertTrue(object instanceof BehaviorBaseModel); } } diff --git a/src/test/java/org/bench4q/agent/test/model/UserBehaviorModelTest.java b/src/test/java/org/bench4q/agent/test/model/UserBehaviorModelTest.java index 9db6836f..b7cbbf2d 100644 --- a/src/test/java/org/bench4q/agent/test/model/UserBehaviorModelTest.java +++ b/src/test/java/org/bench4q/agent/test/model/UserBehaviorModelTest.java @@ -9,30 +9,18 @@ import javax.xml.bind.JAXBException; import javax.xml.bind.Unmarshaller; import org.bench4q.share.models.agent.scriptrecord.BehaviorBaseModel; -import org.bench4q.share.models.agent.scriptrecord.UserBehaviorModel; import org.junit.Test; public class UserBehaviorModelTest { - @Test - public void testMarshal() throws JAXBException { - UserBehaviorModel ub = new UserBehaviorModel(); - ub.setUse("xml"); - ub.setName("test"); - ub.setParameters(null); - System.out.println(ub.getModelString()); - } - @Test public void testUnmarshal() throws JAXBException { Unmarshaller unmarshaller = JAXBContext.newInstance( - UserBehaviorModel.class).createUnmarshaller(); + BehaviorBaseModel.class).createUnmarshaller(); Object object = unmarshaller.unmarshal(new File("Scripts" - + System.getProperty("file.separator") - + "UserBehaviorModel.txt")); - UserBehaviorModel userBehaviorModel = (UserBehaviorModel) object; + + System.getProperty("file.separator") + "behaviorModel.xml")); + BehaviorBaseModel userBehaviorModel = (BehaviorBaseModel) object; System.out.println(userBehaviorModel.getUse()); - assertTrue(object instanceof UserBehaviorModel); assertTrue(object instanceof BehaviorBaseModel); } } From 50b5e7e96905c9901c450c44e6c01d76c3bc9def Mon Sep 17 00:00:00 2001 From: coderfengyun Date: Mon, 23 Dec 2013 17:28:10 +0800 Subject: [PATCH 130/196] add test model --- Scripts/behaviorModel.xml | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 Scripts/behaviorModel.xml diff --git a/Scripts/behaviorModel.xml b/Scripts/behaviorModel.xml new file mode 100644 index 00000000..22f09364 --- /dev/null +++ b/Scripts/behaviorModel.xml @@ -0,0 +1,17 @@ + + 0 + Get + + + url + http://133.133.12.3:8080/Bench4QTestCase/testcase.html + + + + parameters + + + + USERBEHAVIOR + http + \ No newline at end of file From 260c8282e34d9ebdea5bd46dede10afbb9e27e50 Mon Sep 17 00:00:00 2001 From: coderfengyun Date: Mon, 23 Dec 2013 17:30:02 +0800 Subject: [PATCH 131/196] refactor --- src/main/java/org/bench4q/agent/scenario/Scenario.java | 4 ++-- .../bench4q/agent/scenario/behavior/BehaviorFactory.java | 4 ++-- src/test/java/org/bench4q/agent/test/model/ModelTest.java | 6 +++--- .../bench4q/agent/test/model/UserBehaviorModelTest.java | 8 ++++---- 4 files changed, 11 insertions(+), 11 deletions(-) diff --git a/src/main/java/org/bench4q/agent/scenario/Scenario.java b/src/main/java/org/bench4q/agent/scenario/Scenario.java index 56bd58aa..01a1a272 100644 --- a/src/main/java/org/bench4q/agent/scenario/Scenario.java +++ b/src/main/java/org/bench4q/agent/scenario/Scenario.java @@ -9,7 +9,7 @@ import org.bench4q.agent.scenario.behavior.BehaviorFactory; import org.bench4q.share.models.agent.ParameterModel; import org.bench4q.share.models.agent.RunScenarioModel; import org.bench4q.share.models.agent.scriptrecord.BatchModel; -import org.bench4q.share.models.agent.scriptrecord.BehaviorBaseModel; +import org.bench4q.share.models.agent.scriptrecord.BehaviorModel; import org.bench4q.share.models.agent.scriptrecord.PageModel; import org.bench4q.share.models.agent.scriptrecord.UsePluginModel; @@ -124,7 +124,7 @@ public class Scenario { } } - private static Behavior extractBehavior(BehaviorBaseModel behaviorModel) { + private static Behavior extractBehavior(BehaviorModel behaviorModel) { Behavior behavior = BehaviorFactory.getBuisinessObject(behaviorModel); behavior.setName(behaviorModel.getName()); behavior.setUse(behaviorModel.getUse()); diff --git a/src/main/java/org/bench4q/agent/scenario/behavior/BehaviorFactory.java b/src/main/java/org/bench4q/agent/scenario/behavior/BehaviorFactory.java index be82e11e..9c050110 100644 --- a/src/main/java/org/bench4q/agent/scenario/behavior/BehaviorFactory.java +++ b/src/main/java/org/bench4q/agent/scenario/behavior/BehaviorFactory.java @@ -1,9 +1,9 @@ package org.bench4q.agent.scenario.behavior; -import org.bench4q.share.models.agent.scriptrecord.BehaviorBaseModel; +import org.bench4q.share.models.agent.scriptrecord.BehaviorModel; public class BehaviorFactory { - public static Behavior getBuisinessObject(BehaviorBaseModel modelInput) { + public static Behavior getBuisinessObject(BehaviorModel modelInput) { if (modelInput.getType().equalsIgnoreCase("TIMERBEHAVIOR")) { return new TimerBehavior(); } else if (modelInput.getType().equalsIgnoreCase("USERBEHAVIOR")) { diff --git a/src/test/java/org/bench4q/agent/test/model/ModelTest.java b/src/test/java/org/bench4q/agent/test/model/ModelTest.java index cf404057..698d2df9 100644 --- a/src/test/java/org/bench4q/agent/test/model/ModelTest.java +++ b/src/test/java/org/bench4q/agent/test/model/ModelTest.java @@ -7,7 +7,7 @@ import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.annotation.XmlRootElement; -import org.bench4q.share.models.agent.scriptrecord.BehaviorBaseModel; +import org.bench4q.share.models.agent.scriptrecord.BehaviorModel; import org.junit.Test; import static org.junit.Assert.*; @@ -18,13 +18,13 @@ public class ModelTest { @Test public void unmarshalVerify() throws IOException, JAXBException { Object object = JAXBContext - .newInstance(BehaviorBaseModel.class) + .newInstance(BehaviorModel.class) .createUnmarshaller() .unmarshal( new File("Scripts" + System.getProperty("file.separator") + "behaviorModel.xml")); - assertTrue(object instanceof BehaviorBaseModel); + assertTrue(object instanceof BehaviorModel); } } diff --git a/src/test/java/org/bench4q/agent/test/model/UserBehaviorModelTest.java b/src/test/java/org/bench4q/agent/test/model/UserBehaviorModelTest.java index b7cbbf2d..6be857b2 100644 --- a/src/test/java/org/bench4q/agent/test/model/UserBehaviorModelTest.java +++ b/src/test/java/org/bench4q/agent/test/model/UserBehaviorModelTest.java @@ -8,7 +8,7 @@ import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Unmarshaller; -import org.bench4q.share.models.agent.scriptrecord.BehaviorBaseModel; +import org.bench4q.share.models.agent.scriptrecord.BehaviorModel; import org.junit.Test; public class UserBehaviorModelTest { @@ -16,11 +16,11 @@ public class UserBehaviorModelTest { @Test public void testUnmarshal() throws JAXBException { Unmarshaller unmarshaller = JAXBContext.newInstance( - BehaviorBaseModel.class).createUnmarshaller(); + BehaviorModel.class).createUnmarshaller(); Object object = unmarshaller.unmarshal(new File("Scripts" + System.getProperty("file.separator") + "behaviorModel.xml")); - BehaviorBaseModel userBehaviorModel = (BehaviorBaseModel) object; + BehaviorModel userBehaviorModel = (BehaviorModel) object; System.out.println(userBehaviorModel.getUse()); - assertTrue(object instanceof BehaviorBaseModel); + assertTrue(object instanceof BehaviorModel); } } From b434fb97dcf03646371af75586874d721e9dfdd6 Mon Sep 17 00:00:00 2001 From: coderfengyun Date: Tue, 24 Dec 2013 15:35:23 +0800 Subject: [PATCH 132/196] add test about pageBrief, and pass them --- .../org/bench4q/agent/api/TestController.java | 1 + .../impl/AbstractDataCollector.java | 14 +- .../impl/BehaviorResultCollector.java | 5 + .../impl/PageResultCollector.java | 106 ++++++++++++++ ...ctor.java => ScenarioResultCollector.java} | 40 +++--- .../interfaces/DataCollector.java | 4 +- .../java/org/bench4q/agent/scenario/Page.java | 9 ++ .../bench4q/agent/scenario/PageResult.java | 51 ++++++- .../agent/scenario/ScenarioContext.java | 4 +- .../agent/scenario/ScenarioEngine.java | 45 ++++-- .../agent/test/PageBriefStatisticsTest.java | 13 -- .../DataStatisticsTest.java | 31 +++-- .../DetailStatisticsTest.java | 31 +++-- .../PageResultStatisticsTest.java | 129 ++++++++++++++++++ .../test/storage/TestDoubleBufferStorage.java | 2 +- src/test/resources/test-storage-context.xml | 3 +- 16 files changed, 402 insertions(+), 86 deletions(-) create mode 100644 src/main/java/org/bench4q/agent/datacollector/impl/BehaviorResultCollector.java create mode 100644 src/main/java/org/bench4q/agent/datacollector/impl/PageResultCollector.java rename src/main/java/org/bench4q/agent/datacollector/impl/{AgentResultDataCollector.java => ScenarioResultCollector.java} (90%) delete mode 100644 src/test/java/org/bench4q/agent/test/PageBriefStatisticsTest.java rename src/test/java/org/bench4q/agent/test/{ => datastatistics}/DataStatisticsTest.java (82%) rename src/test/java/org/bench4q/agent/test/{ => datastatistics}/DetailStatisticsTest.java (79%) create mode 100644 src/test/java/org/bench4q/agent/test/datastatistics/PageResultStatisticsTest.java diff --git a/src/main/java/org/bench4q/agent/api/TestController.java b/src/main/java/org/bench4q/agent/api/TestController.java index 42c7847b..4bb97ba9 100644 --- a/src/main/java/org/bench4q/agent/api/TestController.java +++ b/src/main/java/org/bench4q/agent/api/TestController.java @@ -286,6 +286,7 @@ public class TestController { scenarioContext.setFinished(true); StopTestModel stopTestModel = new StopTestModel(); stopTestModel.setSuccess(true); + // System.gc(); return stopTestModel; } diff --git a/src/main/java/org/bench4q/agent/datacollector/impl/AbstractDataCollector.java b/src/main/java/org/bench4q/agent/datacollector/impl/AbstractDataCollector.java index b15b60fe..2cad4b59 100644 --- a/src/main/java/org/bench4q/agent/datacollector/impl/AbstractDataCollector.java +++ b/src/main/java/org/bench4q/agent/datacollector/impl/AbstractDataCollector.java @@ -8,7 +8,6 @@ import org.bench4q.agent.Main; import org.bench4q.agent.datacollector.interfaces.DataCollector; import org.bench4q.agent.helper.ApplicationContextHelper; import org.bench4q.agent.scenario.BehaviorResult; -import org.bench4q.agent.scenario.PageResult; import org.bench4q.agent.storage.StorageHelper; import org.bench4q.share.models.agent.BehaviorResultModel; @@ -23,6 +22,10 @@ public abstract class AbstractDataCollector implements DataCollector { this.storageHelper = storageHelper; } + public AbstractDataCollector() { + mustDoWhenIniti(); + } + // Each sub class should call this in their constructor protected void mustDoWhenIniti() { this.setStorageHelper(ApplicationContextHelper.getContext().getBean( @@ -33,6 +36,9 @@ public abstract class AbstractDataCollector implements DataCollector { if (!Main.IS_TO_SAVE_DETAIL) { return; } + if (behaviorResult == null) { + return; + } Runnable runnable = new Runnable() { public void run() { storageHelper.getLocalStorage().writeFile( @@ -47,12 +53,6 @@ public abstract class AbstractDataCollector implements DataCollector { executorService.shutdown(); } - public void add(final PageResult pageResult) { - for (BehaviorResult behaviorResult : pageResult.getBehaviorResults()) { - add(behaviorResult); - } - } - private BehaviorResultModel buildBehaviorResultModel( BehaviorResult behaviorResult) { BehaviorResultModel resultModel = new BehaviorResultModel(); diff --git a/src/main/java/org/bench4q/agent/datacollector/impl/BehaviorResultCollector.java b/src/main/java/org/bench4q/agent/datacollector/impl/BehaviorResultCollector.java new file mode 100644 index 00000000..82db2c4b --- /dev/null +++ b/src/main/java/org/bench4q/agent/datacollector/impl/BehaviorResultCollector.java @@ -0,0 +1,5 @@ +package org.bench4q.agent.datacollector.impl; + +public class BehaviorResultCollector { + +} diff --git a/src/main/java/org/bench4q/agent/datacollector/impl/PageResultCollector.java b/src/main/java/org/bench4q/agent/datacollector/impl/PageResultCollector.java new file mode 100644 index 00000000..8ac13f13 --- /dev/null +++ b/src/main/java/org/bench4q/agent/datacollector/impl/PageResultCollector.java @@ -0,0 +1,106 @@ +package org.bench4q.agent.datacollector.impl; + +import java.util.Date; +import java.util.HashMap; +import java.util.Map; + +import org.bench4q.agent.scenario.BehaviorResult; +import org.bench4q.agent.scenario.PageResult; +import org.bench4q.share.models.agent.PageBriefModel; + +public class PageResultCollector extends AbstractDataCollector { + Map pageBriefMap; + + private Map getPageBriefMap() { + return pageBriefMap; + } + + private void setPageBriefMap(Map pageBriefMap) { + this.pageBriefMap = pageBriefMap; + } + + public PageResultCollector() { + this.setPageBriefMap(new HashMap()); + } + + public void add(PageResult pageResult) { + if (pageResult == null || pageResult.getPageId() < 0) { + return; + } + PageBrief pageBrief = guardTheValueOfThePageIdExists(pageResult + .getPageId()); + pageBrief.countThisTime++; + pageBrief.countFromBegin++; + pageBrief.totalResponseTimeThisTime += pageResult.getExecuteRange(); + if (pageResult.getExecuteRange() > pageBrief.maxResponseTimeFromBegin) { + pageBrief.maxResponseTimeFromBegin = pageResult.getExecuteRange(); + } + if (pageResult.getExecuteRange() < pageBrief.minResponseTimeFromBegin) { + pageBrief.minResponseTimeFromBegin = pageResult.getExecuteRange(); + } + } + + private PageBrief guardTheValueOfThePageIdExists(int pageId) { + if (!this.getPageBriefMap().containsKey(pageId)) { + this.getPageBriefMap().put(pageId, new PageBrief()); + } + return this.getPageBriefMap().get(pageId); + } + + public Object getPageBriefStatistics(int pageId) { + PageBrief pageBrief = guardTheValueOfThePageIdExists(pageId); + PageBriefModel result = new PageBriefModel(); + result.setCountFromBegin(pageBrief.countFromBegin); + result.setCountThisTime(pageBrief.countThisTime); + result.setMaxResponseTimeFromBegin(pageBrief.maxResponseTimeFromBegin); + result.setMinResponseTimeFromBegin(pageBrief.minResponseTimeFromBegin); + result.setTotalResponseTimeThisTime(pageBrief.totalResponseTimeThisTime); + result.setPageId(pageId); + long nowTime = new Date().getTime(); + result.setTimeFrame(nowTime - pageBrief.lastSampleTime); + pageBrief.resetTemperatyField(); + return result; + } + + @Override + public void add(BehaviorResult behaviorResult) { + } + + @Override + protected String calculateSavePath(BehaviorResult behaviorResult) { + return null; + } + + @Override + public Object getScenarioBriefStatistics() { + return null; + } + + @Override + public Map getBehaviorBriefStatistics( + int id) { + return null; + } + + public class PageBrief { + public long lastSampleTime; + public long countThisTime; + public long totalResponseTimeThisTime; + public long maxResponseTimeFromBegin; + public long minResponseTimeFromBegin; + public long countFromBegin; + + public PageBrief() { + resetTemperatyField(); + this.maxResponseTimeFromBegin = Long.MIN_VALUE; + this.minResponseTimeFromBegin = Long.MAX_VALUE; + this.countFromBegin = 0; + } + + public void resetTemperatyField() { + this.lastSampleTime = new Date().getTime(); + this.countThisTime = 0; + this.totalResponseTimeThisTime = 0; + } + } +} diff --git a/src/main/java/org/bench4q/agent/datacollector/impl/AgentResultDataCollector.java b/src/main/java/org/bench4q/agent/datacollector/impl/ScenarioResultCollector.java similarity index 90% rename from src/main/java/org/bench4q/agent/datacollector/impl/AgentResultDataCollector.java rename to src/main/java/org/bench4q/agent/datacollector/impl/ScenarioResultCollector.java index 0aeab000..856bec78 100644 --- a/src/main/java/org/bench4q/agent/datacollector/impl/AgentResultDataCollector.java +++ b/src/main/java/org/bench4q/agent/datacollector/impl/ScenarioResultCollector.java @@ -17,7 +17,7 @@ import org.bench4q.share.models.agent.AgentBriefStatusModel; * @author coderfengyun * */ -public class AgentResultDataCollector extends AbstractDataCollector { +public class ScenarioResultCollector extends AbstractDataCollector { private long timeOfPreviousCall; private long failCountOfThisCall; private long successCountOfThisCall; @@ -29,6 +29,7 @@ public class AgentResultDataCollector extends AbstractDataCollector { private long cumulativeFailCount; private static long TIME_UNIT = 1000; private UUID testID; + private PageResultCollector pageResultCollector; // The first integer is the behavior's id, and the second integer is // the StatusCode of this behaviorResult. private Map> detailMap; @@ -95,9 +96,17 @@ public class AgentResultDataCollector extends AbstractDataCollector { this.detailMap = detailMap; } - public AgentResultDataCollector(UUID testId) { - super.mustDoWhenIniti(); + private PageResultCollector getPageResultCollector() { + return pageResultCollector; + } + + private void setPageResultCollector(PageResultCollector pageResultCollector) { + this.pageResultCollector = pageResultCollector; + } + + public ScenarioResultCollector(UUID testId) { this.setTestID(testId); + this.setPageResultCollector(new PageResultCollector()); init(); } @@ -132,7 +141,6 @@ public class AgentResultDataCollector extends AbstractDataCollector { } else { result.setMinResponseTime(this.minResponseTimeOfThisCall); result.setMaxResponseTime(this.maxResponseTimeOfThisCall); - } this.cumulativeSucessfulCount += this.successCountOfThisCall; result.setSuccessCountFromBegin(this.cumulativeSucessfulCount); @@ -187,10 +195,6 @@ public class AgentResultDataCollector extends AbstractDataCollector { } } - private void statisticPageBriefResult(PageResult pageResult) { - - } - private void statisticBehaviorBriefResult(BehaviorResult behaviorResult) { insertWhenNotExist(behaviorResult); Map detailStatusMap = this.detailMap @@ -231,12 +235,6 @@ public class AgentResultDataCollector extends AbstractDataCollector { } } - // @Override - // public void add(BehaviorResult behaviorResult) { - // super.add(behaviorResult); - // addItem(behaviorResult); - // } - @Override protected String calculateSavePath(BehaviorResult behaviorResult) { Date now = new Date(); @@ -248,17 +246,10 @@ public class AgentResultDataCollector extends AbstractDataCollector { + new SimpleDateFormat("hhmm") + ".txt"; } - @Override public void add(PageResult pageResult) { - super.add(pageResult); - statisticPageBriefResult(pageResult); - for (BehaviorResult behaviorResult : pageResult.getBehaviorResults()) { - statisticScenarioBriefResult(behaviorResult); - statisticBehaviorBriefResult(behaviorResult); - } + this.getPageResultCollector().add(pageResult); } - // TODO: delete this @Override public void add(BehaviorResult behaviorResult) { super.add(behaviorResult); @@ -275,4 +266,9 @@ public class AgentResultDataCollector extends AbstractDataCollector { return Collections.unmodifiableMap(this.detailMap.get(behaviorId)); } + public Object getPageBriefStatistics(int pageId) { + // TODO Auto-generated method stub + return null; + } + } diff --git a/src/main/java/org/bench4q/agent/datacollector/interfaces/DataCollector.java b/src/main/java/org/bench4q/agent/datacollector/interfaces/DataCollector.java index 6f15ef40..95a6f3fa 100644 --- a/src/main/java/org/bench4q/agent/datacollector/interfaces/DataCollector.java +++ b/src/main/java/org/bench4q/agent/datacollector/interfaces/DataCollector.java @@ -14,5 +14,7 @@ public interface DataCollector { public Object getScenarioBriefStatistics(); public Map getBehaviorBriefStatistics( - int id); + int behaviorId); + + public Object getPageBriefStatistics(int pageId); } diff --git a/src/main/java/org/bench4q/agent/scenario/Page.java b/src/main/java/org/bench4q/agent/scenario/Page.java index ff19117b..2814652b 100644 --- a/src/main/java/org/bench4q/agent/scenario/Page.java +++ b/src/main/java/org/bench4q/agent/scenario/Page.java @@ -1,7 +1,11 @@ package org.bench4q.agent.scenario; +import org.bench4q.agent.datacollector.impl.PageResultCollector; +import org.bench4q.agent.datacollector.interfaces.DataCollector; + public class Page { private Batch[] batches; + final private DataCollector dataCollector = new PageResultCollector(); public Batch[] getBatches() { return batches; @@ -10,4 +14,9 @@ public class Page { public void setBatches(Batch[] batches) { this.batches = batches; } + + public DataCollector getDataCollector() { + return dataCollector; + } + } diff --git a/src/main/java/org/bench4q/agent/scenario/PageResult.java b/src/main/java/org/bench4q/agent/scenario/PageResult.java index 01fb9c68..e9572c94 100644 --- a/src/main/java/org/bench4q/agent/scenario/PageResult.java +++ b/src/main/java/org/bench4q/agent/scenario/PageResult.java @@ -1,12 +1,13 @@ package org.bench4q.agent.scenario; import java.util.ArrayList; -import java.util.Collections; import java.util.List; public class PageResult { private int pageId; - private List behaviorResults; + private long pageStartTime; + private long pageEndTime; + private long executeRange; public int getPageId() { return pageId; @@ -16,15 +17,38 @@ public class PageResult { this.pageId = pageId; } - public List getBehaviorResults() { - return Collections.unmodifiableList(behaviorResults); + public long getPageStartTime() { + return pageStartTime; } - private void setBehaviorResults(List behaviorResults) { - this.behaviorResults = behaviorResults; + private void setPageStartTime(long pageStartTime) { + this.pageStartTime = pageStartTime; + } + + public long getPageEndTime() { + return pageEndTime; + } + + private void setPageEndTime(long pageEndTime) { + this.pageEndTime = pageEndTime; + } + + public long getExecuteRange() { + return executeRange; + } + + private void setExecuteRange(long executeRange) { + this.executeRange = executeRange; } private PageResult() { + init(); + } + + private void init() { + this.setPageStartTime(Long.MAX_VALUE); + this.setPageEndTime(Long.MIN_VALUE); + this.setExecuteRange(0); } public static PageResult buildPageResult(int pageId, @@ -34,7 +58,20 @@ public class PageResult { if (behaviorResults == null) { behaviorResults = new ArrayList(); } - result.setBehaviorResults(behaviorResults); + for (BehaviorResult behaviorResult : behaviorResults) { + if (behaviorResult.getStartDate().getTime() < result + .getPageStartTime()) { + result.setPageStartTime(behaviorResult.getStartDate().getTime()); + } + if (behaviorResult.getEndDate().getTime() > result.getPageEndTime()) { + result.setPageEndTime(behaviorResult.getEndDate().getTime()); + } + // Page excuteRange rely on the behaviors' execute way, if it's + // executed in batch, i should take the longest behavior in batch + // to calculate this One. + } + result.setExecuteRange(result.getPageEndTime() + - result.getPageStartTime()); return result; } } diff --git a/src/main/java/org/bench4q/agent/scenario/ScenarioContext.java b/src/main/java/org/bench4q/agent/scenario/ScenarioContext.java index a919e007..24087583 100644 --- a/src/main/java/org/bench4q/agent/scenario/ScenarioContext.java +++ b/src/main/java/org/bench4q/agent/scenario/ScenarioContext.java @@ -4,7 +4,7 @@ import java.util.Date; import java.util.UUID; import java.util.concurrent.ThreadPoolExecutor; -import org.bench4q.agent.datacollector.impl.AgentResultDataCollector; +import org.bench4q.agent.datacollector.impl.ScenarioResultCollector; import org.bench4q.agent.datacollector.interfaces.DataCollector; public class ScenarioContext { @@ -70,7 +70,7 @@ public class ScenarioContext { scenarioContext.setStartDate(new Date(System.currentTimeMillis())); scenarioContext.setExecutorService(executor); // TODO:remove this direct dependency - scenarioContext.setDataStatistics(new AgentResultDataCollector(testId)); + scenarioContext.setDataStatistics(new ScenarioResultCollector(testId)); return scenarioContext; } diff --git a/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java b/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java index 79243d3c..c3979438 100644 --- a/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java +++ b/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java @@ -1,7 +1,9 @@ package org.bench4q.agent.scenario; +import java.util.ArrayList; import java.util.Date; import java.util.HashMap; +import java.util.List; import java.util.Map; import java.util.UUID; import java.util.concurrent.ExecutorService; @@ -12,6 +14,7 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.ThreadPoolExecutor.DiscardPolicy; import org.apache.log4j.Logger; +import org.bench4q.agent.datacollector.interfaces.DataCollector; import org.bench4q.agent.plugin.Plugin; import org.bench4q.agent.plugin.PluginManager; import org.bench4q.agent.plugin.result.HttpReturn; @@ -72,12 +75,11 @@ public class ScenarioEngine { public void runScenario(UUID runId, final Scenario scenario, int poolSize) { try { final SynchronousQueue workQueue = new SynchronousQueue(); - ThreadPoolExecutor executor = new ThreadPoolExecutor( - poolSize, poolSize, keepAliveTime, TimeUnit.MINUTES, - workQueue, new DiscardPolicy()); + ThreadPoolExecutor executor = new ThreadPoolExecutor(poolSize, + poolSize, keepAliveTime, TimeUnit.MINUTES, workQueue, + new DiscardPolicy()); final ScenarioContext scenarioContext = ScenarioContext - .buildScenarioContext(runId, scenario, poolSize, - executor); + .buildScenarioContext(runId, scenario, poolSize, executor); this.getRunningTests().put(runId, scenarioContext); System.out.println(poolSize); executeTasks(executor, scenarioContext); @@ -106,8 +108,29 @@ public class ScenarioEngine { public void doRunScenario(ScenarioContext context) { Map plugins = new HashMap(); preparePlugins(context.getScenario(), plugins); - for (Behavior behavior : context.getScenario() - .getAllBehaviorsInScenario()) { + for (int i = 0; i < context.getScenario().getPages().length; i++) { + Page page = context.getScenario().getPages()[i]; + context.getDataStatistics().add( + PageResult.buildPageResult( + i, + doRunBatchesInPage(plugins, page, + context.getDataStatistics()))); + } + } + + private List doRunBatchesInPage( + Map plugins, Page page, DataCollector dataCollector) { + List results = new ArrayList(); + for (Batch batch : page.getBatches()) { + results.addAll(doRunBatch(plugins, batch, dataCollector)); + } + return results; + } + + private List doRunBatch(Map plugins, + Batch batch, DataCollector dataCollector) { + List results = new ArrayList(); + for (Behavior behavior : batch.getBehaviors()) { Object plugin = plugins.get(behavior.getUse()); Map behaviorParameters = prepareBehaviorParameters(behavior); Date startDate = new Date(System.currentTimeMillis()); @@ -117,10 +140,12 @@ public class ScenarioEngine { if (!behavior.shouldBeCountResponseTime()) { continue; } - context.getDataStatistics().add( - buildBehaviorResult(behavior, plugin, startDate, - pluginReturn, endDate)); + BehaviorResult behaviorResult = buildBehaviorResult(behavior, + plugin, startDate, pluginReturn, endDate); + dataCollector.add(behaviorResult); + results.add(behaviorResult); } + return results; } private BehaviorResult buildBehaviorResult(Behavior behavior, diff --git a/src/test/java/org/bench4q/agent/test/PageBriefStatisticsTest.java b/src/test/java/org/bench4q/agent/test/PageBriefStatisticsTest.java deleted file mode 100644 index 8cee3b07..00000000 --- a/src/test/java/org/bench4q/agent/test/PageBriefStatisticsTest.java +++ /dev/null @@ -1,13 +0,0 @@ -package org.bench4q.agent.test; - -import static org.junit.Assert.*; - -import org.junit.Test; - -public class PageBriefStatisticsTest extends DataStatisticsTest { - @Test - public void testAddPageResultWithZeroBehaviorResult() { - // this.getDataStatistics().add(); - fail(); - } -} diff --git a/src/test/java/org/bench4q/agent/test/DataStatisticsTest.java b/src/test/java/org/bench4q/agent/test/datastatistics/DataStatisticsTest.java similarity index 82% rename from src/test/java/org/bench4q/agent/test/DataStatisticsTest.java rename to src/test/java/org/bench4q/agent/test/datastatistics/DataStatisticsTest.java index 739e88b5..151aa51f 100644 --- a/src/test/java/org/bench4q/agent/test/DataStatisticsTest.java +++ b/src/test/java/org/bench4q/agent/test/datastatistics/DataStatisticsTest.java @@ -1,4 +1,4 @@ -package org.bench4q.agent.test; +package org.bench4q.agent.test.datastatistics; import static org.junit.Assert.*; @@ -7,7 +7,7 @@ import java.util.Date; import java.util.List; import java.util.UUID; -import org.bench4q.agent.datacollector.impl.AgentResultDataCollector; +import org.bench4q.agent.datacollector.impl.ScenarioResultCollector; import org.bench4q.agent.datacollector.interfaces.DataCollector; import org.bench4q.agent.scenario.BehaviorResult; import org.bench4q.agent.scenario.PageResult; @@ -36,7 +36,7 @@ public class DataStatisticsTest { @SuppressWarnings("resource") ApplicationContext context = new ClassPathXmlApplicationContext( "classpath*:/org/bench4q/agent/config/application-context.xml"); - AgentResultDataCollector agentResultDataCollector = new AgentResultDataCollector( + ScenarioResultCollector agentResultDataCollector = new ScenarioResultCollector( UUID.randomUUID()); agentResultDataCollector.setStorageHelper((StorageHelper) context .getBean(StorageHelper.class)); @@ -45,8 +45,9 @@ public class DataStatisticsTest { @Test public void addZeroBriefTest() { - this.getDataStatistics().add(makePageResultWithBehaviorResult(0)); - + for (BehaviorResult behaviorResult : makeBehaviorList(0)) { + this.getDataStatistics().add(behaviorResult); + } AgentBriefStatusModel model = (AgentBriefStatusModel) this .getDataStatistics().getScenarioBriefStatistics(); AgentBriefStatusModel modelExpect = makeAllZeroModel(); @@ -56,7 +57,9 @@ public class DataStatisticsTest { @Test public void addOneBriefTest() throws InterruptedException { - this.getDataStatistics().add(makePageResultWithBehaviorResult(1)); + for (BehaviorResult behaviorResult : makeBehaviorList(1)) { + this.getDataStatistics().add(behaviorResult); + } Thread.sleep(100); AgentBriefStatusModel model = (AgentBriefStatusModel) this @@ -69,7 +72,9 @@ public class DataStatisticsTest { @Test public void addTwoBriefTest() throws InterruptedException { - this.getDataStatistics().add(makePageResultWithBehaviorResult(2)); + for (BehaviorResult behaviorResult : makeBehaviorList(2)) { + this.getDataStatistics().add(behaviorResult); + } Thread.sleep(100); AgentBriefStatusModel model = (AgentBriefStatusModel) this .getDataStatistics().getScenarioBriefStatistics(); @@ -126,19 +131,23 @@ public class DataStatisticsTest { } public static PageResult makePageResultWithBehaviorResult(int count) { + List behaviorResults = makeBehaviorList(count); + return PageResult.buildPageResult(2, behaviorResults); + } + public static List makeBehaviorList(int count) { List behaviorResults = new ArrayList(); for (int i = 0; i < count; i++) { int statusCode = i % 2 == 0 ? 200 : 400; behaviorResults.add(buildBehaviorResult(200 + 10 * i, i % 2 == 0, - statusCode, 1)); + statusCode, 1, 200 + 10 * i)); } - return PageResult.buildPageResult(2, behaviorResults); + return behaviorResults; } public static BehaviorResult buildBehaviorResult(long responseTime, - boolean success, int statusCode, int behaviorId) { - Date date = new Date(); + boolean success, int statusCode, int behaviorId, long startDateTime) { + Date date = new Date(startDateTime); BehaviorResult result = new BehaviorResult(); result.setBehaviorName(""); result.setEndDate(new Date(date.getTime() + responseTime)); diff --git a/src/test/java/org/bench4q/agent/test/DetailStatisticsTest.java b/src/test/java/org/bench4q/agent/test/datastatistics/DetailStatisticsTest.java similarity index 79% rename from src/test/java/org/bench4q/agent/test/DetailStatisticsTest.java rename to src/test/java/org/bench4q/agent/test/datastatistics/DetailStatisticsTest.java index 665d085d..c0e83e25 100644 --- a/src/test/java/org/bench4q/agent/test/DetailStatisticsTest.java +++ b/src/test/java/org/bench4q/agent/test/datastatistics/DetailStatisticsTest.java @@ -1,4 +1,4 @@ -package org.bench4q.agent.test; +package org.bench4q.agent.test.datastatistics; import static org.junit.Assert.*; @@ -6,9 +6,10 @@ import java.util.HashMap; import java.util.Map; import java.util.UUID; -import org.bench4q.agent.datacollector.impl.AgentResultDataCollector; +import org.bench4q.agent.datacollector.impl.ScenarioResultCollector; import org.bench4q.agent.datacollector.impl.BehaviorStatusCodeResult; import org.bench4q.agent.datacollector.interfaces.DataCollector; +import org.bench4q.agent.scenario.BehaviorResult; import org.bench4q.agent.storage.StorageHelper; import org.junit.Test; import org.springframework.context.ApplicationContext; @@ -33,7 +34,7 @@ public class DetailStatisticsTest { @SuppressWarnings("resource") ApplicationContext context = new ClassPathXmlApplicationContext( "classpath*:/org/bench4q/agent/config/application-context.xml"); - AgentResultDataCollector agentResultDataCollector = new AgentResultDataCollector( + ScenarioResultCollector agentResultDataCollector = new ScenarioResultCollector( UUID.randomUUID()); agentResultDataCollector.setStorageHelper((StorageHelper) context .getBean(StorageHelper.class)); @@ -42,8 +43,10 @@ public class DetailStatisticsTest { @Test public void addZeroTest() { - this.getDetailStatistics().add( - DataStatisticsTest.makePageResultWithBehaviorResult(0)); + for (BehaviorResult behaviorResult : DataStatisticsTest + .makeBehaviorList(0)) { + this.getDetailStatistics().add(behaviorResult); + } Object object = this.detailStatistics.getBehaviorBriefStatistics(0); assertEquals(null, object); @@ -51,8 +54,10 @@ public class DetailStatisticsTest { @Test public void addOneDetailTest() { - this.getDetailStatistics().add( - DataStatisticsTest.makePageResultWithBehaviorResult(1)); + for (BehaviorResult behaviorResult : DataStatisticsTest + .makeBehaviorList(1)) { + this.getDetailStatistics().add(behaviorResult); + } Map map = this.detailStatistics .getBehaviorBriefStatistics(1); @@ -72,8 +77,10 @@ public class DetailStatisticsTest { @Test public void addTwoDetailTest() { - this.getDetailStatistics().add( - DataStatisticsTest.makePageResultWithBehaviorResult(2)); + for (BehaviorResult behaviorResult : DataStatisticsTest + .makeBehaviorList(2)) { + this.getDetailStatistics().add(behaviorResult); + } Map map = this.detailStatistics .getBehaviorBriefStatistics(1); assertTrue(mapEquals(map, makeExpectedMapForTwo())); @@ -114,8 +121,10 @@ public class DetailStatisticsTest { @Test public void addThreeTest() { - this.getDetailStatistics().add( - DataStatisticsTest.makePageResultWithBehaviorResult(3)); + for (BehaviorResult behaviorResult : DataStatisticsTest + .makeBehaviorList(3)) { + this.getDetailStatistics().add(behaviorResult); + } Map mapActual = this .getDetailStatistics().getBehaviorBriefStatistics(1); assertTrue(mapEquals(mapActual, makeExpectedMapForThree())); diff --git a/src/test/java/org/bench4q/agent/test/datastatistics/PageResultStatisticsTest.java b/src/test/java/org/bench4q/agent/test/datastatistics/PageResultStatisticsTest.java new file mode 100644 index 00000000..16d0fdad --- /dev/null +++ b/src/test/java/org/bench4q/agent/test/datastatistics/PageResultStatisticsTest.java @@ -0,0 +1,129 @@ +package org.bench4q.agent.test.datastatistics; + +import org.bench4q.agent.datacollector.impl.PageResultCollector; +import org.bench4q.agent.datacollector.interfaces.DataCollector; +import org.bench4q.agent.scenario.PageResult; +import org.bench4q.share.models.agent.PageBriefModel; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.context.support.ClassPathXmlApplicationContext; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import static org.junit.Assert.*; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(locations = { "classpath:test-storage-context.xml", + "classpath*:/org/bench4q/agent/config/application-context.xml" }) +public class PageResultStatisticsTest { + private DataCollector dataCollector; + + private DataCollector getDataCollector() { + return dataCollector; + } + + private void setDataCollector(DataCollector dataCollector) { + this.dataCollector = dataCollector; + } + + @SuppressWarnings("resource") + public PageResultStatisticsTest() { + new ClassPathXmlApplicationContext( + "classpath*:/org/bench4q/agent/config/application-context.xml"); + this.setDataCollector(new PageResultCollector()); + } + + @Test + public void pageResultTest() { + PageResult pageResult = PageResult.buildPageResult(2, + DataStatisticsTest.makeBehaviorList(1)); + assertEquals(2, pageResult.getPageId()); + assertEquals(200, pageResult.getExecuteRange()); + assertTrue(pageResult.getPageStartTime() > 0); + } + + @Test + public void pageResultWithTwoBehaviorTest() { + PageResult pageResult = PageResult.buildPageResult(2, + DataStatisticsTest.makeBehaviorList(2)); + assertEquals(2, pageResult.getPageId()); + assertEquals(220, pageResult.getExecuteRange()); + assertEquals(200, pageResult.getPageStartTime()); + assertEquals(420, pageResult.getPageEndTime()); + } + + @Test + public void testNull() { + this.getDataCollector().add((PageResult) null); + assertNotNull(dataCollector.getPageBriefStatistics(0)); + } + + @Test + public void testOnePaegWithOneBehaviorResult() { + this.getDataCollector().add( + PageResult.buildPageResult(2, + DataStatisticsTest.makeBehaviorList(1))); + PageBriefModel pageBriefModel = (PageBriefModel) this + .getDataCollector().getPageBriefStatistics(2); + assertEquals(2, pageBriefModel.getPageId()); + assertEquals(1, pageBriefModel.getCountFromBegin()); + assertEquals(1, pageBriefModel.getCountThisTime()); + assertEquals(200, pageBriefModel.getMaxResponseTimeFromBegin()); + assertEquals(200, pageBriefModel.getMinResponseTimeFromBegin()); + assertTrue(pageBriefModel.getTimeFrame() >= 0); + assertEquals(200, pageBriefModel.getTotalResponseTimeThisTime()); + } + + @Test + public void testOnePageWithTwoBehaviorResult() { + this.getDataCollector().add( + PageResult.buildPageResult(2, + DataStatisticsTest.makeBehaviorList(2))); + PageBriefModel pageBriefModel = (PageBriefModel) this + .getDataCollector().getPageBriefStatistics(2); + System.out.println(pageBriefModel.getCountFromBegin()); + assertEquals(2, pageBriefModel.getPageId()); + assertEquals(1, pageBriefModel.getCountFromBegin()); + assertEquals(1, pageBriefModel.getCountThisTime()); + assertEquals(220, pageBriefModel.getMaxResponseTimeFromBegin()); + assertEquals(220, pageBriefModel.getMinResponseTimeFromBegin()); + assertTrue(pageBriefModel.getTimeFrame() >= 0); + assertEquals(220, pageBriefModel.getTotalResponseTimeThisTime()); + } + + @Test + public void testTwoPageWithStatisticsAtLast() { + this.getDataCollector().add( + PageResult.buildPageResult(2, + DataStatisticsTest.makeBehaviorList(1))); + this.getDataCollector().add( + PageResult.buildPageResult(2, + DataStatisticsTest.makeBehaviorList(2))); + PageBriefModel pageBriefModel = (PageBriefModel) this + .getDataCollector().getPageBriefStatistics(2); + assertEquals(2, pageBriefModel.getPageId()); + assertEquals(2, pageBriefModel.getCountFromBegin()); + assertEquals(2, pageBriefModel.getCountThisTime()); + assertEquals(220, pageBriefModel.getMaxResponseTimeFromBegin()); + assertEquals(200, pageBriefModel.getMinResponseTimeFromBegin()); + assertEquals(420, pageBriefModel.getTotalResponseTimeThisTime()); + assertTrue(pageBriefModel.getTimeFrame() >= 0); + } + + @Test + public void testTwoPageWithStatisticsIndividually() { + testOnePaegWithOneBehaviorResult(); + this.getDataCollector().add( + PageResult.buildPageResult(2, + DataStatisticsTest.makeBehaviorList(2))); + PageBriefModel model = (PageBriefModel) this.getDataCollector() + .getPageBriefStatistics(2); + assertEquals(2, model.getPageId()); + assertEquals(2, model.getCountFromBegin()); + assertEquals(1, model.getCountThisTime()); + assertEquals(220, model.getMaxResponseTimeFromBegin()); + assertEquals(200, model.getMinResponseTimeFromBegin()); + assertEquals(220, model.getTotalResponseTimeThisTime()); + assertTrue(model.getTimeFrame() >= -0); + } +} diff --git a/src/test/java/org/bench4q/agent/test/storage/TestDoubleBufferStorage.java b/src/test/java/org/bench4q/agent/test/storage/TestDoubleBufferStorage.java index f07fe2b2..f7f4cf86 100644 --- a/src/test/java/org/bench4q/agent/test/storage/TestDoubleBufferStorage.java +++ b/src/test/java/org/bench4q/agent/test/storage/TestDoubleBufferStorage.java @@ -19,7 +19,7 @@ import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(locations = { "classpath:test-storage-context.xml" }) +@ContextConfiguration(locations = { "classpath*:/org/bench4q/agent/config/application-context.xml" }) public class TestDoubleBufferStorage { private DoubleBufferStorage doubleBufferStorage; private static String SAVE_DIR = "StorageTest" diff --git a/src/test/resources/test-storage-context.xml b/src/test/resources/test-storage-context.xml index 7c690e9a..a9e939f0 100644 --- a/src/test/resources/test-storage-context.xml +++ b/src/test/resources/test-storage-context.xml @@ -5,6 +5,7 @@ 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"> - + From 498893c114bb36cc0cad8a160acf1ae54f0354f1 Mon Sep 17 00:00:00 2001 From: coderfengyun Date: Tue, 24 Dec 2013 15:51:16 +0800 Subject: [PATCH 133/196] add a field to pageBrief --- .../bench4q/agent/datacollector/impl/PageResultCollector.java | 4 ++++ .../agent/test/datastatistics/PageResultStatisticsTest.java | 4 ++++ 2 files changed, 8 insertions(+) diff --git a/src/main/java/org/bench4q/agent/datacollector/impl/PageResultCollector.java b/src/main/java/org/bench4q/agent/datacollector/impl/PageResultCollector.java index 8ac13f13..758dd60f 100644 --- a/src/main/java/org/bench4q/agent/datacollector/impl/PageResultCollector.java +++ b/src/main/java/org/bench4q/agent/datacollector/impl/PageResultCollector.java @@ -32,6 +32,7 @@ public class PageResultCollector extends AbstractDataCollector { pageBrief.countThisTime++; pageBrief.countFromBegin++; pageBrief.totalResponseTimeThisTime += pageResult.getExecuteRange(); + pageBrief.latesTimeResponseTime = pageResult.getExecuteRange(); if (pageResult.getExecuteRange() > pageBrief.maxResponseTimeFromBegin) { pageBrief.maxResponseTimeFromBegin = pageResult.getExecuteRange(); } @@ -58,6 +59,7 @@ public class PageResultCollector extends AbstractDataCollector { result.setPageId(pageId); long nowTime = new Date().getTime(); result.setTimeFrame(nowTime - pageBrief.lastSampleTime); + result.setLatestTimeResponseTime(pageBrief.latesTimeResponseTime); pageBrief.resetTemperatyField(); return result; } @@ -89,12 +91,14 @@ public class PageResultCollector extends AbstractDataCollector { public long maxResponseTimeFromBegin; public long minResponseTimeFromBegin; public long countFromBegin; + public long latesTimeResponseTime; public PageBrief() { resetTemperatyField(); this.maxResponseTimeFromBegin = Long.MIN_VALUE; this.minResponseTimeFromBegin = Long.MAX_VALUE; this.countFromBegin = 0; + this.latesTimeResponseTime = 0; } public void resetTemperatyField() { diff --git a/src/test/java/org/bench4q/agent/test/datastatistics/PageResultStatisticsTest.java b/src/test/java/org/bench4q/agent/test/datastatistics/PageResultStatisticsTest.java index 16d0fdad..7e4d40bb 100644 --- a/src/test/java/org/bench4q/agent/test/datastatistics/PageResultStatisticsTest.java +++ b/src/test/java/org/bench4q/agent/test/datastatistics/PageResultStatisticsTest.java @@ -72,6 +72,7 @@ public class PageResultStatisticsTest { assertEquals(200, pageBriefModel.getMinResponseTimeFromBegin()); assertTrue(pageBriefModel.getTimeFrame() >= 0); assertEquals(200, pageBriefModel.getTotalResponseTimeThisTime()); + assertEquals(200, pageBriefModel.getLatestTimeResponseTime()); } @Test @@ -89,6 +90,7 @@ public class PageResultStatisticsTest { assertEquals(220, pageBriefModel.getMinResponseTimeFromBegin()); assertTrue(pageBriefModel.getTimeFrame() >= 0); assertEquals(220, pageBriefModel.getTotalResponseTimeThisTime()); + assertEquals(220, pageBriefModel.getLatestTimeResponseTime()); } @Test @@ -108,6 +110,7 @@ public class PageResultStatisticsTest { assertEquals(200, pageBriefModel.getMinResponseTimeFromBegin()); assertEquals(420, pageBriefModel.getTotalResponseTimeThisTime()); assertTrue(pageBriefModel.getTimeFrame() >= 0); + assertEquals(220, pageBriefModel.getLatestTimeResponseTime()); } @Test @@ -125,5 +128,6 @@ public class PageResultStatisticsTest { assertEquals(200, model.getMinResponseTimeFromBegin()); assertEquals(220, model.getTotalResponseTimeThisTime()); assertTrue(model.getTimeFrame() >= -0); + assertEquals(220, model.getLatestTimeResponseTime()); } } From 0c17124ebfa697f01910667fb2018542c26a5402 Mon Sep 17 00:00:00 2001 From: coderfengyun Date: Tue, 24 Dec 2013 16:23:17 +0800 Subject: [PATCH 134/196] now the agent can support for pageBrief --- .../org/bench4q/agent/api/TestController.java | 14 ++++++++--- .../impl/ScenarioResultCollector.java | 3 +-- .../agent/test/TestWithScriptFile.java | 25 ++++++++++++++++--- .../datastatistics/DetailStatisticsTest.java | 8 +++--- .../PageResultStatisticsTest.java | 14 +++++------ ...sTest.java => ScenarioStatisticsTest.java} | 4 +-- 6 files changed, 47 insertions(+), 21 deletions(-) rename src/test/java/org/bench4q/agent/test/datastatistics/{DataStatisticsTest.java => ScenarioStatisticsTest.java} (95%) diff --git a/src/main/java/org/bench4q/agent/api/TestController.java b/src/main/java/org/bench4q/agent/api/TestController.java index 4bb97ba9..76f58dd4 100644 --- a/src/main/java/org/bench4q/agent/api/TestController.java +++ b/src/main/java/org/bench4q/agent/api/TestController.java @@ -227,9 +227,17 @@ public class TestController { return behaviorBriefModel; } - @RequestMapping(value = "/pageBrief/{pageId}") - public PageBriefModel pageBrief(@PathVariable int pageId) { - return null; + @RequestMapping(value = "/pageBrief/{runId}/{pageId}") + @ResponseBody + public PageBriefModel pageBrief(@PathVariable UUID runId, + @PathVariable int pageId) { + ScenarioContext context = this.getScenarioEngine().getRunningTests() + .get(runId); + if (context == null || context.isFinished()) { + return null; + } + return (PageBriefModel) context.getDataStatistics() + .getPageBriefStatistics(pageId); } @RequestMapping(value = "/behaviorsBrief/{runId}") diff --git a/src/main/java/org/bench4q/agent/datacollector/impl/ScenarioResultCollector.java b/src/main/java/org/bench4q/agent/datacollector/impl/ScenarioResultCollector.java index 856bec78..104934a5 100644 --- a/src/main/java/org/bench4q/agent/datacollector/impl/ScenarioResultCollector.java +++ b/src/main/java/org/bench4q/agent/datacollector/impl/ScenarioResultCollector.java @@ -267,8 +267,7 @@ public class ScenarioResultCollector extends AbstractDataCollector { } public Object getPageBriefStatistics(int pageId) { - // TODO Auto-generated method stub - return null; + return this.getPageResultCollector().getPageBriefStatistics(pageId); } } diff --git a/src/test/java/org/bench4q/agent/test/TestWithScriptFile.java b/src/test/java/org/bench4q/agent/test/TestWithScriptFile.java index e6d29e9b..99d57a4f 100644 --- a/src/test/java/org/bench4q/agent/test/TestWithScriptFile.java +++ b/src/test/java/org/bench4q/agent/test/TestWithScriptFile.java @@ -16,6 +16,7 @@ import org.apache.commons.io.FileUtils; import org.bench4q.share.helper.MarshalHelper; import org.bench4q.share.models.agent.AgentBriefStatusModel; import org.bench4q.share.models.agent.BehaviorBriefModel; +import org.bench4q.share.models.agent.PageBriefModel; import org.bench4q.share.models.agent.RunScenarioModel; import org.bench4q.share.models.agent.RunScenarioResultModel; import org.bench4q.share.models.agent.TestBehaviorsBriefModel; @@ -64,7 +65,7 @@ public class TestWithScriptFile { public void startTest() throws JAXBException { File file = new File(this.getFilePath()); if (!file.exists()) { - System.out.println("There's no this script!"); + System.out.println("this script not exists!"); return; } String scriptContent; @@ -121,7 +122,7 @@ public class TestWithScriptFile { this.url + "/stop/" + this.getTestId().toString(), null, null); } - private void brief() throws IOException, JAXBException { + private void scenarioBrief() throws IOException, JAXBException { System.out.println("Enter brief!"); HttpResponse httpResponse = this.getHttpRequester().sendGet( this.url + "/brief/" + this.getTestId().toString(), null, null); @@ -157,12 +158,30 @@ public class TestWithScriptFile { IOException { this.startTest(); Thread.sleep(5000); - this.brief(); + this.scenarioBrief(); Thread.sleep(5000); this.behaviorsBrief(); Thread.sleep(5000); this.behaviorBrief(); Thread.sleep(5000); + this.pageBrief(0); this.stopTest(); } + + private void pageBrief(int i) throws IOException, JAXBException { + try { + HttpResponse httpResponse = this.getHttpRequester().sendGet(url, + null, null); + if (httpResponse == null || httpResponse.getContent().isEmpty()) { + fail(); + } + System.out.println(httpResponse); + PageBriefModel pageBriefModel = (PageBriefModel) MarshalHelper + .unmarshal(PageBriefModel.class, httpResponse.getContent()); + assertTrue(pageBriefModel.getCountFromBegin() > 0); + } catch (Exception e) { + this.stopTest(); + } + + } } diff --git a/src/test/java/org/bench4q/agent/test/datastatistics/DetailStatisticsTest.java b/src/test/java/org/bench4q/agent/test/datastatistics/DetailStatisticsTest.java index c0e83e25..bfe51b2b 100644 --- a/src/test/java/org/bench4q/agent/test/datastatistics/DetailStatisticsTest.java +++ b/src/test/java/org/bench4q/agent/test/datastatistics/DetailStatisticsTest.java @@ -43,7 +43,7 @@ public class DetailStatisticsTest { @Test public void addZeroTest() { - for (BehaviorResult behaviorResult : DataStatisticsTest + for (BehaviorResult behaviorResult : ScenarioStatisticsTest .makeBehaviorList(0)) { this.getDetailStatistics().add(behaviorResult); } @@ -54,7 +54,7 @@ public class DetailStatisticsTest { @Test public void addOneDetailTest() { - for (BehaviorResult behaviorResult : DataStatisticsTest + for (BehaviorResult behaviorResult : ScenarioStatisticsTest .makeBehaviorList(1)) { this.getDetailStatistics().add(behaviorResult); } @@ -77,7 +77,7 @@ public class DetailStatisticsTest { @Test public void addTwoDetailTest() { - for (BehaviorResult behaviorResult : DataStatisticsTest + for (BehaviorResult behaviorResult : ScenarioStatisticsTest .makeBehaviorList(2)) { this.getDetailStatistics().add(behaviorResult); } @@ -121,7 +121,7 @@ public class DetailStatisticsTest { @Test public void addThreeTest() { - for (BehaviorResult behaviorResult : DataStatisticsTest + for (BehaviorResult behaviorResult : ScenarioStatisticsTest .makeBehaviorList(3)) { this.getDetailStatistics().add(behaviorResult); } diff --git a/src/test/java/org/bench4q/agent/test/datastatistics/PageResultStatisticsTest.java b/src/test/java/org/bench4q/agent/test/datastatistics/PageResultStatisticsTest.java index 7e4d40bb..daaa0df7 100644 --- a/src/test/java/org/bench4q/agent/test/datastatistics/PageResultStatisticsTest.java +++ b/src/test/java/org/bench4q/agent/test/datastatistics/PageResultStatisticsTest.java @@ -36,7 +36,7 @@ public class PageResultStatisticsTest { @Test public void pageResultTest() { PageResult pageResult = PageResult.buildPageResult(2, - DataStatisticsTest.makeBehaviorList(1)); + ScenarioStatisticsTest.makeBehaviorList(1)); assertEquals(2, pageResult.getPageId()); assertEquals(200, pageResult.getExecuteRange()); assertTrue(pageResult.getPageStartTime() > 0); @@ -45,7 +45,7 @@ public class PageResultStatisticsTest { @Test public void pageResultWithTwoBehaviorTest() { PageResult pageResult = PageResult.buildPageResult(2, - DataStatisticsTest.makeBehaviorList(2)); + ScenarioStatisticsTest.makeBehaviorList(2)); assertEquals(2, pageResult.getPageId()); assertEquals(220, pageResult.getExecuteRange()); assertEquals(200, pageResult.getPageStartTime()); @@ -62,7 +62,7 @@ public class PageResultStatisticsTest { public void testOnePaegWithOneBehaviorResult() { this.getDataCollector().add( PageResult.buildPageResult(2, - DataStatisticsTest.makeBehaviorList(1))); + ScenarioStatisticsTest.makeBehaviorList(1))); PageBriefModel pageBriefModel = (PageBriefModel) this .getDataCollector().getPageBriefStatistics(2); assertEquals(2, pageBriefModel.getPageId()); @@ -79,7 +79,7 @@ public class PageResultStatisticsTest { public void testOnePageWithTwoBehaviorResult() { this.getDataCollector().add( PageResult.buildPageResult(2, - DataStatisticsTest.makeBehaviorList(2))); + ScenarioStatisticsTest.makeBehaviorList(2))); PageBriefModel pageBriefModel = (PageBriefModel) this .getDataCollector().getPageBriefStatistics(2); System.out.println(pageBriefModel.getCountFromBegin()); @@ -97,10 +97,10 @@ public class PageResultStatisticsTest { public void testTwoPageWithStatisticsAtLast() { this.getDataCollector().add( PageResult.buildPageResult(2, - DataStatisticsTest.makeBehaviorList(1))); + ScenarioStatisticsTest.makeBehaviorList(1))); this.getDataCollector().add( PageResult.buildPageResult(2, - DataStatisticsTest.makeBehaviorList(2))); + ScenarioStatisticsTest.makeBehaviorList(2))); PageBriefModel pageBriefModel = (PageBriefModel) this .getDataCollector().getPageBriefStatistics(2); assertEquals(2, pageBriefModel.getPageId()); @@ -118,7 +118,7 @@ public class PageResultStatisticsTest { testOnePaegWithOneBehaviorResult(); this.getDataCollector().add( PageResult.buildPageResult(2, - DataStatisticsTest.makeBehaviorList(2))); + ScenarioStatisticsTest.makeBehaviorList(2))); PageBriefModel model = (PageBriefModel) this.getDataCollector() .getPageBriefStatistics(2); assertEquals(2, model.getPageId()); diff --git a/src/test/java/org/bench4q/agent/test/datastatistics/DataStatisticsTest.java b/src/test/java/org/bench4q/agent/test/datastatistics/ScenarioStatisticsTest.java similarity index 95% rename from src/test/java/org/bench4q/agent/test/datastatistics/DataStatisticsTest.java rename to src/test/java/org/bench4q/agent/test/datastatistics/ScenarioStatisticsTest.java index 151aa51f..088534d9 100644 --- a/src/test/java/org/bench4q/agent/test/datastatistics/DataStatisticsTest.java +++ b/src/test/java/org/bench4q/agent/test/datastatistics/ScenarioStatisticsTest.java @@ -17,7 +17,7 @@ import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; -public class DataStatisticsTest { +public class ScenarioStatisticsTest { private DataCollector dataStatistics; protected DataCollector getDataStatistics() { @@ -28,7 +28,7 @@ public class DataStatisticsTest { this.dataStatistics = dataStatistics; } - public DataStatisticsTest() { + public ScenarioStatisticsTest() { init(); } From c8acdf5e4e4c913ae109bec96404250f0e4077fc Mon Sep 17 00:00:00 2001 From: coderfengyun Date: Tue, 24 Dec 2013 16:45:57 +0800 Subject: [PATCH 135/196] refactor --- src/main/java/org/bench4q/agent/api/TestController.java | 8 ++++---- .../agent/datacollector/impl/ScenarioResultCollector.java | 2 +- .../java/org/bench4q/agent/test/TestWithScriptFile.java | 8 ++++---- .../agent/test/datastatistics/ScenarioStatisticsTest.java | 2 +- 4 files changed, 10 insertions(+), 10 deletions(-) diff --git a/src/main/java/org/bench4q/agent/api/TestController.java b/src/main/java/org/bench4q/agent/api/TestController.java index 76f58dd4..4b22211c 100644 --- a/src/main/java/org/bench4q/agent/api/TestController.java +++ b/src/main/java/org/bench4q/agent/api/TestController.java @@ -18,7 +18,6 @@ import org.bench4q.agent.scenario.Scenario; import org.bench4q.agent.scenario.ScenarioContext; import org.bench4q.agent.scenario.ScenarioEngine; import org.bench4q.agent.scenario.behavior.Behavior; -import org.bench4q.share.models.agent.AgentBriefStatusModel; import org.bench4q.share.models.agent.BehaviorBriefModel; import org.bench4q.share.models.agent.BehaviorStatusCodeResultModel; import org.bench4q.share.models.agent.CleanTestResultModel; @@ -26,7 +25,8 @@ import org.bench4q.share.models.agent.PageBriefModel; import org.bench4q.share.models.agent.RunScenarioModel; import org.bench4q.share.models.agent.RunScenarioResultModel; import org.bench4q.share.models.agent.StopTestModel; -import org.bench4q.share.models.agent.TestBehaviorsBriefModel; +import org.bench4q.share.models.agent.statistics.AgentBriefStatusModel; +import org.bench4q.share.models.agent.statistics.AgentBehaviorsBriefModel; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; @@ -242,8 +242,8 @@ public class TestController { @RequestMapping(value = "/behaviorsBrief/{runId}") @ResponseBody - public TestBehaviorsBriefModel behaviorsBrief(@PathVariable UUID runId) { - TestBehaviorsBriefModel ret = new TestBehaviorsBriefModel(); + public AgentBehaviorsBriefModel behaviorsBrief(@PathVariable UUID runId) { + AgentBehaviorsBriefModel ret = new AgentBehaviorsBriefModel(); List behaviorBriefModels = new ArrayList(); ScenarioContext scenarioContext = this.getScenarioEngine() .getRunningTests().get(runId); diff --git a/src/main/java/org/bench4q/agent/datacollector/impl/ScenarioResultCollector.java b/src/main/java/org/bench4q/agent/datacollector/impl/ScenarioResultCollector.java index 104934a5..b88b8e33 100644 --- a/src/main/java/org/bench4q/agent/datacollector/impl/ScenarioResultCollector.java +++ b/src/main/java/org/bench4q/agent/datacollector/impl/ScenarioResultCollector.java @@ -9,7 +9,7 @@ import java.util.UUID; import org.bench4q.agent.scenario.BehaviorResult; import org.bench4q.agent.scenario.PageResult; -import org.bench4q.share.models.agent.AgentBriefStatusModel; +import org.bench4q.share.models.agent.statistics.AgentBriefStatusModel; /** * This class collect the behavior result and statistic it. diff --git a/src/test/java/org/bench4q/agent/test/TestWithScriptFile.java b/src/test/java/org/bench4q/agent/test/TestWithScriptFile.java index 99d57a4f..a8054223 100644 --- a/src/test/java/org/bench4q/agent/test/TestWithScriptFile.java +++ b/src/test/java/org/bench4q/agent/test/TestWithScriptFile.java @@ -14,12 +14,12 @@ import javax.xml.bind.Unmarshaller; import org.apache.commons.io.FileUtils; import org.bench4q.share.helper.MarshalHelper; -import org.bench4q.share.models.agent.AgentBriefStatusModel; import org.bench4q.share.models.agent.BehaviorBriefModel; import org.bench4q.share.models.agent.PageBriefModel; import org.bench4q.share.models.agent.RunScenarioModel; import org.bench4q.share.models.agent.RunScenarioResultModel; -import org.bench4q.share.models.agent.TestBehaviorsBriefModel; +import org.bench4q.share.models.agent.statistics.AgentBriefStatusModel; +import org.bench4q.share.models.agent.statistics.AgentBehaviorsBriefModel; import org.junit.Test; import Communication.HttpRequester; @@ -137,8 +137,8 @@ public class TestWithScriptFile { HttpResponse httpResponse = this.getHttpRequester().sendGet( this.url + "/behaviorsBrief/" + this.getTestId().toString(), null, null); - TestBehaviorsBriefModel behaviorsBriefModel = (TestBehaviorsBriefModel) MarshalHelper - .unmarshal(TestBehaviorsBriefModel.class, + AgentBehaviorsBriefModel behaviorsBriefModel = (AgentBehaviorsBriefModel) MarshalHelper + .unmarshal(AgentBehaviorsBriefModel.class, httpResponse.getContent()); assertTrue(behaviorsBriefModel.getBehaviorBriefModels().size() > 0); } diff --git a/src/test/java/org/bench4q/agent/test/datastatistics/ScenarioStatisticsTest.java b/src/test/java/org/bench4q/agent/test/datastatistics/ScenarioStatisticsTest.java index 088534d9..6b0fbd75 100644 --- a/src/test/java/org/bench4q/agent/test/datastatistics/ScenarioStatisticsTest.java +++ b/src/test/java/org/bench4q/agent/test/datastatistics/ScenarioStatisticsTest.java @@ -12,7 +12,7 @@ import org.bench4q.agent.datacollector.interfaces.DataCollector; import org.bench4q.agent.scenario.BehaviorResult; import org.bench4q.agent.scenario.PageResult; import org.bench4q.agent.storage.StorageHelper; -import org.bench4q.share.models.agent.AgentBriefStatusModel; +import org.bench4q.share.models.agent.statistics.AgentBriefStatusModel; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; From 93b54cd7410972c94156f2e44a67e755b9d3602c Mon Sep 17 00:00:00 2001 From: coderfengyun Date: Wed, 25 Dec 2013 09:22:46 +0800 Subject: [PATCH 136/196] refa --- .../org/bench4q/agent/api/TestController.java | 6 +++--- .../impl/PageResultCollector.java | 6 +++--- .../bench4q/agent/test/TestWithScriptFile.java | 6 +++--- .../PageResultStatisticsTest.java | 18 +++++++++--------- 4 files changed, 18 insertions(+), 18 deletions(-) diff --git a/src/main/java/org/bench4q/agent/api/TestController.java b/src/main/java/org/bench4q/agent/api/TestController.java index 4b22211c..aa3b0659 100644 --- a/src/main/java/org/bench4q/agent/api/TestController.java +++ b/src/main/java/org/bench4q/agent/api/TestController.java @@ -21,12 +21,12 @@ import org.bench4q.agent.scenario.behavior.Behavior; import org.bench4q.share.models.agent.BehaviorBriefModel; import org.bench4q.share.models.agent.BehaviorStatusCodeResultModel; import org.bench4q.share.models.agent.CleanTestResultModel; -import org.bench4q.share.models.agent.PageBriefModel; import org.bench4q.share.models.agent.RunScenarioModel; import org.bench4q.share.models.agent.RunScenarioResultModel; import org.bench4q.share.models.agent.StopTestModel; import org.bench4q.share.models.agent.statistics.AgentBriefStatusModel; import org.bench4q.share.models.agent.statistics.AgentBehaviorsBriefModel; +import org.bench4q.share.models.agent.statistics.AgentPageBriefModel; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; @@ -229,14 +229,14 @@ public class TestController { @RequestMapping(value = "/pageBrief/{runId}/{pageId}") @ResponseBody - public PageBriefModel pageBrief(@PathVariable UUID runId, + public AgentPageBriefModel pageBrief(@PathVariable UUID runId, @PathVariable int pageId) { ScenarioContext context = this.getScenarioEngine().getRunningTests() .get(runId); if (context == null || context.isFinished()) { return null; } - return (PageBriefModel) context.getDataStatistics() + return (AgentPageBriefModel) context.getDataStatistics() .getPageBriefStatistics(pageId); } diff --git a/src/main/java/org/bench4q/agent/datacollector/impl/PageResultCollector.java b/src/main/java/org/bench4q/agent/datacollector/impl/PageResultCollector.java index 758dd60f..0a12d3b1 100644 --- a/src/main/java/org/bench4q/agent/datacollector/impl/PageResultCollector.java +++ b/src/main/java/org/bench4q/agent/datacollector/impl/PageResultCollector.java @@ -6,7 +6,7 @@ import java.util.Map; import org.bench4q.agent.scenario.BehaviorResult; import org.bench4q.agent.scenario.PageResult; -import org.bench4q.share.models.agent.PageBriefModel; +import org.bench4q.share.models.agent.statistics.AgentPageBriefModel; public class PageResultCollector extends AbstractDataCollector { Map pageBriefMap; @@ -50,7 +50,7 @@ public class PageResultCollector extends AbstractDataCollector { public Object getPageBriefStatistics(int pageId) { PageBrief pageBrief = guardTheValueOfThePageIdExists(pageId); - PageBriefModel result = new PageBriefModel(); + AgentPageBriefModel result = new AgentPageBriefModel(); result.setCountFromBegin(pageBrief.countFromBegin); result.setCountThisTime(pageBrief.countThisTime); result.setMaxResponseTimeFromBegin(pageBrief.maxResponseTimeFromBegin); @@ -59,7 +59,7 @@ public class PageResultCollector extends AbstractDataCollector { result.setPageId(pageId); long nowTime = new Date().getTime(); result.setTimeFrame(nowTime - pageBrief.lastSampleTime); - result.setLatestTimeResponseTime(pageBrief.latesTimeResponseTime); + result.setLatestResponseTime(pageBrief.latesTimeResponseTime); pageBrief.resetTemperatyField(); return result; } diff --git a/src/test/java/org/bench4q/agent/test/TestWithScriptFile.java b/src/test/java/org/bench4q/agent/test/TestWithScriptFile.java index a8054223..d27cf157 100644 --- a/src/test/java/org/bench4q/agent/test/TestWithScriptFile.java +++ b/src/test/java/org/bench4q/agent/test/TestWithScriptFile.java @@ -15,11 +15,11 @@ import javax.xml.bind.Unmarshaller; import org.apache.commons.io.FileUtils; import org.bench4q.share.helper.MarshalHelper; import org.bench4q.share.models.agent.BehaviorBriefModel; -import org.bench4q.share.models.agent.PageBriefModel; import org.bench4q.share.models.agent.RunScenarioModel; import org.bench4q.share.models.agent.RunScenarioResultModel; import org.bench4q.share.models.agent.statistics.AgentBriefStatusModel; import org.bench4q.share.models.agent.statistics.AgentBehaviorsBriefModel; +import org.bench4q.share.models.agent.statistics.AgentPageBriefModel; import org.junit.Test; import Communication.HttpRequester; @@ -176,8 +176,8 @@ public class TestWithScriptFile { fail(); } System.out.println(httpResponse); - PageBriefModel pageBriefModel = (PageBriefModel) MarshalHelper - .unmarshal(PageBriefModel.class, httpResponse.getContent()); + AgentPageBriefModel pageBriefModel = (AgentPageBriefModel) MarshalHelper + .unmarshal(AgentPageBriefModel.class, httpResponse.getContent()); assertTrue(pageBriefModel.getCountFromBegin() > 0); } catch (Exception e) { this.stopTest(); diff --git a/src/test/java/org/bench4q/agent/test/datastatistics/PageResultStatisticsTest.java b/src/test/java/org/bench4q/agent/test/datastatistics/PageResultStatisticsTest.java index daaa0df7..c8e0bb9c 100644 --- a/src/test/java/org/bench4q/agent/test/datastatistics/PageResultStatisticsTest.java +++ b/src/test/java/org/bench4q/agent/test/datastatistics/PageResultStatisticsTest.java @@ -3,7 +3,7 @@ package org.bench4q.agent.test.datastatistics; import org.bench4q.agent.datacollector.impl.PageResultCollector; import org.bench4q.agent.datacollector.interfaces.DataCollector; import org.bench4q.agent.scenario.PageResult; -import org.bench4q.share.models.agent.PageBriefModel; +import org.bench4q.share.models.agent.statistics.AgentPageBriefModel; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.context.support.ClassPathXmlApplicationContext; @@ -63,7 +63,7 @@ public class PageResultStatisticsTest { this.getDataCollector().add( PageResult.buildPageResult(2, ScenarioStatisticsTest.makeBehaviorList(1))); - PageBriefModel pageBriefModel = (PageBriefModel) this + AgentPageBriefModel pageBriefModel = (AgentPageBriefModel) this .getDataCollector().getPageBriefStatistics(2); assertEquals(2, pageBriefModel.getPageId()); assertEquals(1, pageBriefModel.getCountFromBegin()); @@ -72,7 +72,7 @@ public class PageResultStatisticsTest { assertEquals(200, pageBriefModel.getMinResponseTimeFromBegin()); assertTrue(pageBriefModel.getTimeFrame() >= 0); assertEquals(200, pageBriefModel.getTotalResponseTimeThisTime()); - assertEquals(200, pageBriefModel.getLatestTimeResponseTime()); + assertEquals(200, pageBriefModel.getLatestResponseTime()); } @Test @@ -80,7 +80,7 @@ public class PageResultStatisticsTest { this.getDataCollector().add( PageResult.buildPageResult(2, ScenarioStatisticsTest.makeBehaviorList(2))); - PageBriefModel pageBriefModel = (PageBriefModel) this + AgentPageBriefModel pageBriefModel = (AgentPageBriefModel) this .getDataCollector().getPageBriefStatistics(2); System.out.println(pageBriefModel.getCountFromBegin()); assertEquals(2, pageBriefModel.getPageId()); @@ -90,7 +90,7 @@ public class PageResultStatisticsTest { assertEquals(220, pageBriefModel.getMinResponseTimeFromBegin()); assertTrue(pageBriefModel.getTimeFrame() >= 0); assertEquals(220, pageBriefModel.getTotalResponseTimeThisTime()); - assertEquals(220, pageBriefModel.getLatestTimeResponseTime()); + assertEquals(220, pageBriefModel.getLatestResponseTime()); } @Test @@ -101,7 +101,7 @@ public class PageResultStatisticsTest { this.getDataCollector().add( PageResult.buildPageResult(2, ScenarioStatisticsTest.makeBehaviorList(2))); - PageBriefModel pageBriefModel = (PageBriefModel) this + AgentPageBriefModel pageBriefModel = (AgentPageBriefModel) this .getDataCollector().getPageBriefStatistics(2); assertEquals(2, pageBriefModel.getPageId()); assertEquals(2, pageBriefModel.getCountFromBegin()); @@ -110,7 +110,7 @@ public class PageResultStatisticsTest { assertEquals(200, pageBriefModel.getMinResponseTimeFromBegin()); assertEquals(420, pageBriefModel.getTotalResponseTimeThisTime()); assertTrue(pageBriefModel.getTimeFrame() >= 0); - assertEquals(220, pageBriefModel.getLatestTimeResponseTime()); + assertEquals(220, pageBriefModel.getLatestResponseTime()); } @Test @@ -119,7 +119,7 @@ public class PageResultStatisticsTest { this.getDataCollector().add( PageResult.buildPageResult(2, ScenarioStatisticsTest.makeBehaviorList(2))); - PageBriefModel model = (PageBriefModel) this.getDataCollector() + AgentPageBriefModel model = (AgentPageBriefModel) this.getDataCollector() .getPageBriefStatistics(2); assertEquals(2, model.getPageId()); assertEquals(2, model.getCountFromBegin()); @@ -128,6 +128,6 @@ public class PageResultStatisticsTest { assertEquals(200, model.getMinResponseTimeFromBegin()); assertEquals(220, model.getTotalResponseTimeThisTime()); assertTrue(model.getTimeFrame() >= -0); - assertEquals(220, model.getLatestTimeResponseTime()); + assertEquals(220, model.getLatestResponseTime()); } } From 9ca375dc6d0f6b8e475dcdd1da9504b9cfca032b Mon Sep 17 00:00:00 2001 From: coderfengyun Date: Wed, 25 Dec 2013 14:51:00 +0800 Subject: [PATCH 137/196] refactor the log --- src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java b/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java index c3979438..63ebff31 100644 --- a/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java +++ b/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java @@ -97,7 +97,7 @@ public class ScenarioEngine { executorService.execute(new Runnable() { public void run() { doRunScenario(scenarioContext); - System.out.println("end for once"); + logger.info("end for once!"); } }); } From f8a25f6471c7629919dbf50f483d85b7978c9678 Mon Sep 17 00:00:00 2001 From: coderfengyun Date: Mon, 30 Dec 2013 16:42:23 +0800 Subject: [PATCH 138/196] little refa --- .../org/bench4q/agent/api/TestController.java | 101 +----------------- 1 file changed, 1 insertion(+), 100 deletions(-) diff --git a/src/main/java/org/bench4q/agent/api/TestController.java b/src/main/java/org/bench4q/agent/api/TestController.java index aa3b0659..f309057e 100644 --- a/src/main/java/org/bench4q/agent/api/TestController.java +++ b/src/main/java/org/bench4q/agent/api/TestController.java @@ -85,105 +85,6 @@ public class TestController { } - // private Scenario extractScenario(RunScenarioModel runScenarioModel) { - // Scenario scenario = new Scenario(); - // scenario.setUsePlugins(new UsePlugin[runScenarioModel.getUsePlugins() - // .size()]); - // scenario.setPages(new Page[runScenarioModel.getPages().size()]); - // extractUsePlugins(runScenarioModel, scenario); - // extractPages(runScenarioModel, scenario); - // return scenario; - // } - // - // private void extractPages(RunScenarioModel runScenarioModel, - // Scenario scenario) { - // List pageModels = runScenarioModel.getPages(); - // for (int i = 0; i < pageModels.size(); i++) { - // PageModel pageModel = pageModels.get(i); - // scenario.getPages()[i] = extractPage(pageModel); - // } - // } - // - // private Page extractPage(PageModel pageModel) { - // Page page = new Page(); - // page.setBatches(new Batch[pageModel.getBatches().size()]); - // List batches = pageModel.getBatches(); - // for (int i = 0; i < pageModel.getBatches().size(); i++) { - // BatchModel batch = batches.get(i); - // page.getBatches()[i] = extractBatch(batch); - // } - // return page; - // } - // - // private Batch extractBatch(BatchModel batchModel) { - // Batch batch = new Batch(); - // batch.setBehaviors(new Behavior[batchModel.getBehaviors().size()]); - // batch.setId(batchModel.getId()); - // batch.setParentId(batchModel.getParentId()); - // batch.setChildId(batchModel.getChildId()); - // if (batchModel.getBehaviors() == null) { - // return batch; - // } - // batch.setBehaviors(new Behavior[batchModel.getBehaviors().size()]); - // for (int i = 0; i < batchModel.getBehaviors().size(); ++i) { - // batch.getBehaviors()[i] = extractBehavior(batchModel.getBehaviors() - // .get(i)); - // } - // return batch; - // } - // - // private void extractUsePlugins(RunScenarioModel runScenarioModel, - // Scenario scenario) { - // int i; - // List usePluginModels = runScenarioModel.getUsePlugins(); - // for (i = 0; i < runScenarioModel.getUsePlugins().size(); i++) { - // UsePluginModel usePluginModel = usePluginModels.get(i); - // UsePlugin usePlugin = extractUsePlugin(usePluginModel); - // scenario.getUsePlugins()[i] = usePlugin; - // } - // } - // - // private Behavior extractBehavior(BehaviorBaseModel behaviorModel) { - // Behavior behavior = BehaviorFactory.getBuisinessObject(behaviorModel); - // behavior.setName(behaviorModel.getName()); - // behavior.setUse(behaviorModel.getUse()); - // behavior.setId(behaviorModel.getId()); - // behavior.setParameters(new Parameter[behaviorModel.getParameters() - // .size()]); - // - // int k = 0; - // for (k = 0; k < behaviorModel.getParameters().size(); k++) { - // ParameterModel parameterModel = behaviorModel.getParameters() - // .get(k); - // Parameter parameter = extractParameter(parameterModel); - // behavior.getParameters()[k] = parameter; - // } - // return behavior; - // } - // - // private UsePlugin extractUsePlugin(UsePluginModel usePluginModel) { - // UsePlugin usePlugin = new UsePlugin(); - // usePlugin.setId(usePluginModel.getId()); - // usePlugin.setName(usePluginModel.getName()); - // usePlugin.setParameters(new Parameter[usePluginModel.getParameters() - // .size()]); - // int k = 0; - // for (k = 0; k < usePluginModel.getParameters().size(); k++) { - // ParameterModel parameterModel = usePluginModel.getParameters().get( - // k); - // Parameter parameter = extractParameter(parameterModel); - // usePlugin.getParameters()[k] = parameter; - // } - // return usePlugin; - // } - // - // private Parameter extractParameter(ParameterModel parameterModel) { - // Parameter parameter = new Parameter(); - // parameter.setKey(parameterModel.getKey()); - // parameter.setValue(parameterModel.getValue()); - // return parameter; - // } - @RequestMapping(value = "/brief/{runId}/{behaviorId}", method = RequestMethod.GET) @ResponseBody public BehaviorBriefModel behaviorBrief(@PathVariable UUID runId, @@ -294,7 +195,7 @@ public class TestController { scenarioContext.setFinished(true); StopTestModel stopTestModel = new StopTestModel(); stopTestModel.setSuccess(true); - // System.gc(); + System.gc(); return stopTestModel; } From 948bd29f25925eb24c7f700e88cbd311541b7b43 Mon Sep 17 00:00:00 2001 From: coderfengyun Date: Mon, 30 Dec 2013 16:49:55 +0800 Subject: [PATCH 139/196] little refa --- src/main/java/org/bench4q/agent/api/TestController.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/org/bench4q/agent/api/TestController.java b/src/main/java/org/bench4q/agent/api/TestController.java index f309057e..75f4acd9 100644 --- a/src/main/java/org/bench4q/agent/api/TestController.java +++ b/src/main/java/org/bench4q/agent/api/TestController.java @@ -195,7 +195,7 @@ public class TestController { scenarioContext.setFinished(true); StopTestModel stopTestModel = new StopTestModel(); stopTestModel.setSuccess(true); - System.gc(); + clean(runId); return stopTestModel; } From 408d511b1b64ee6ec0db3fcf7743cbf76158b25f Mon Sep 17 00:00:00 2001 From: coderfengyun Date: Thu, 2 Jan 2014 10:54:05 +0800 Subject: [PATCH 140/196] add a todo --- .../agent/datacollector/impl/ScenarioResultCollector.java | 1 + 1 file changed, 1 insertion(+) diff --git a/src/main/java/org/bench4q/agent/datacollector/impl/ScenarioResultCollector.java b/src/main/java/org/bench4q/agent/datacollector/impl/ScenarioResultCollector.java index b88b8e33..4f6a6e5a 100644 --- a/src/main/java/org/bench4q/agent/datacollector/impl/ScenarioResultCollector.java +++ b/src/main/java/org/bench4q/agent/datacollector/impl/ScenarioResultCollector.java @@ -200,6 +200,7 @@ public class ScenarioResultCollector extends AbstractDataCollector { Map detailStatusMap = this.detailMap .get(behaviorResult.getBehaviorId()); + // TODO: there's a problem about concurrency if (!detailStatusMap.containsKey(behaviorResult.getStatusCode())) { detailStatusMap.put( new Integer(behaviorResult.getStatusCode()), From cb693446889b77d3c18468a2959f20235fec8743 Mon Sep 17 00:00:00 2001 From: coderfengyun Date: Thu, 2 Jan 2014 16:35:21 +0800 Subject: [PATCH 141/196] add pages brief --- .../org/bench4q/agent/api/TestController.java | 20 +++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/src/main/java/org/bench4q/agent/api/TestController.java b/src/main/java/org/bench4q/agent/api/TestController.java index 75f4acd9..b79637a5 100644 --- a/src/main/java/org/bench4q/agent/api/TestController.java +++ b/src/main/java/org/bench4q/agent/api/TestController.java @@ -27,6 +27,7 @@ import org.bench4q.share.models.agent.StopTestModel; import org.bench4q.share.models.agent.statistics.AgentBriefStatusModel; import org.bench4q.share.models.agent.statistics.AgentBehaviorsBriefModel; import org.bench4q.share.models.agent.statistics.AgentPageBriefModel; +import org.bench4q.share.models.agent.statistics.AgentPagesBriefModel; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; @@ -128,6 +129,25 @@ public class TestController { return behaviorBriefModel; } + @RequestMapping(value = "/pagesBrief/{runId}") + @ResponseBody + public AgentPagesBriefModel pagesBrief(@PathVariable UUID runId) { + ScenarioContext context = this.getScenarioEngine().getRunningTests() + .get(runId); + AgentPagesBriefModel result = new AgentPagesBriefModel(); + List pageBrieves = new ArrayList(); + + if (context == null || context.isFinished()) { + return null; + } + for (int i = 0; i < context.getScenario().getPages().length; i++) { + pageBrieves.add((AgentPageBriefModel) context.getDataStatistics() + .getPageBriefStatistics(i)); + } + result.setPageBriefModels(pageBrieves); + return result; + } + @RequestMapping(value = "/pageBrief/{runId}/{pageId}") @ResponseBody public AgentPageBriefModel pageBrief(@PathVariable UUID runId, From 1cc120e690392e88f570c58ad1782cd974878ecd Mon Sep 17 00:00:00 2001 From: coderfengyun Date: Fri, 3 Jan 2014 16:28:39 +0800 Subject: [PATCH 142/196] refactor with synchronize --- .../bench4q/agent/datacollector/impl/PageResultCollector.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/main/java/org/bench4q/agent/datacollector/impl/PageResultCollector.java b/src/main/java/org/bench4q/agent/datacollector/impl/PageResultCollector.java index 0a12d3b1..7638549f 100644 --- a/src/main/java/org/bench4q/agent/datacollector/impl/PageResultCollector.java +++ b/src/main/java/org/bench4q/agent/datacollector/impl/PageResultCollector.java @@ -41,7 +41,7 @@ public class PageResultCollector extends AbstractDataCollector { } } - private PageBrief guardTheValueOfThePageIdExists(int pageId) { + private synchronized PageBrief guardTheValueOfThePageIdExists(int pageId) { if (!this.getPageBriefMap().containsKey(pageId)) { this.getPageBriefMap().put(pageId, new PageBrief()); } From bddf2b538e611e56d012f9a98066954d8b91a126 Mon Sep 17 00:00:00 2001 From: coderfengyun Date: Tue, 7 Jan 2014 10:24:54 +0800 Subject: [PATCH 143/196] add the behaviorUrl to behaviorBriefModel --- .../org/bench4q/agent/api/TestController.java | 8 ++++--- .../impl/ScenarioResultCollector.java | 22 +++++++++++-------- .../agent/scenario/BehaviorResult.java | 10 +++++++++ .../agent/scenario/ScenarioEngine.java | 5 +++++ .../agent/scenario/behavior/Behavior.java | 9 ++++++++ .../agent/test/TestWithScriptFile.java | 8 ++++--- 6 files changed, 47 insertions(+), 15 deletions(-) diff --git a/src/main/java/org/bench4q/agent/api/TestController.java b/src/main/java/org/bench4q/agent/api/TestController.java index b79637a5..14704150 100644 --- a/src/main/java/org/bench4q/agent/api/TestController.java +++ b/src/main/java/org/bench4q/agent/api/TestController.java @@ -97,11 +97,11 @@ public class TestController { } Map map = scenarioContext .getDataStatistics().getBehaviorBriefStatistics(behaviorId); - return buildBehaviorBrief(runId, behaviorId, map); + return buildBehaviorBrief(runId, behaviorId, "", map); } private BehaviorBriefModel buildBehaviorBrief(UUID runId, int behaviorId, - Map map) { + String behaviorUrl, Map map) { List detailStatusCodeResultModels = new ArrayList(); for (int statusCode : map.keySet()) { BehaviorStatusCodeResultModel behaviorStatusCodeResultModel = new BehaviorStatusCodeResultModel(); @@ -126,6 +126,7 @@ public class TestController { behaviorBriefModel.setBehaviorId(behaviorId); behaviorBriefModel .setDetailStatusCodeResultModels(detailStatusCodeResultModels); + behaviorBriefModel.setBehaviorUrl(behaviorUrl); return behaviorBriefModel; } @@ -179,7 +180,8 @@ public class TestController { if (map == null) { continue; } - behaviorBriefModels.add(buildBehaviorBrief(runId, behaviorId, map)); + behaviorBriefModels.add(buildBehaviorBrief(runId, behaviorId, + behavior.getUrl(), map)); } ret.setBehaviorBriefModels(behaviorBriefModels); return ret; diff --git a/src/main/java/org/bench4q/agent/datacollector/impl/ScenarioResultCollector.java b/src/main/java/org/bench4q/agent/datacollector/impl/ScenarioResultCollector.java index 4f6a6e5a..04958f4d 100644 --- a/src/main/java/org/bench4q/agent/datacollector/impl/ScenarioResultCollector.java +++ b/src/main/java/org/bench4q/agent/datacollector/impl/ScenarioResultCollector.java @@ -199,15 +199,8 @@ public class ScenarioResultCollector extends AbstractDataCollector { insertWhenNotExist(behaviorResult); Map detailStatusMap = this.detailMap .get(behaviorResult.getBehaviorId()); - // TODO: there's a problem about concurrency - if (!detailStatusMap.containsKey(behaviorResult.getStatusCode())) { - detailStatusMap.put( - new Integer(behaviorResult.getStatusCode()), - new BehaviorStatusCodeResult(behaviorResult - .getContentType())); - } - + guardStatusMapExists(behaviorResult, detailStatusMap); BehaviorStatusCodeResult statusCodeResult = detailStatusMap .get(behaviorResult.getStatusCode()); statusCodeResult.count++; @@ -229,7 +222,18 @@ public class ScenarioResultCollector extends AbstractDataCollector { } } - private void insertWhenNotExist(BehaviorResult behaviorResult) { + private synchronized void guardStatusMapExists( + BehaviorResult behaviorResult, + Map detailStatusMap) { + if (!detailStatusMap.containsKey(behaviorResult.getStatusCode())) { + detailStatusMap.put( + new Integer(behaviorResult.getStatusCode()), + new BehaviorStatusCodeResult(behaviorResult + .getContentType())); + } + } + + private synchronized void insertWhenNotExist(BehaviorResult behaviorResult) { if (!this.detailMap.containsKey(behaviorResult.getBehaviorId())) { this.detailMap.put(new Integer(behaviorResult.getBehaviorId()), new HashMap()); diff --git a/src/main/java/org/bench4q/agent/scenario/BehaviorResult.java b/src/main/java/org/bench4q/agent/scenario/BehaviorResult.java index 1a2ef304..501cddc1 100644 --- a/src/main/java/org/bench4q/agent/scenario/BehaviorResult.java +++ b/src/main/java/org/bench4q/agent/scenario/BehaviorResult.java @@ -10,7 +10,9 @@ public class BehaviorResult { private Date endDate; private long responseTime; private boolean success; + private int behaviorId; + private String behaviorUrl; private long contentLength; private int statusCode; private String contentType; @@ -80,6 +82,14 @@ public class BehaviorResult { this.behaviorId = behaviorId; } + public String getBehaviorUrl() { + return behaviorUrl; + } + + public void setBehaviorUrl(String behaviorUrl) { + this.behaviorUrl = behaviorUrl; + } + public long getContentLength() { return contentLength; } diff --git a/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java b/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java index 63ebff31..06e192bd 100644 --- a/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java +++ b/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java @@ -165,6 +165,11 @@ public class ScenarioEngine { if (pluginReturn instanceof HttpReturn) { HttpReturn httpReturn = (HttpReturn) pluginReturn; result.setBehaviorId(behavior.getId()); + for (Parameter parameter : behavior.getParameters()) { + if (parameter.getKey().equals("url")) { + result.setBehaviorUrl(parameter.getValue()); + } + } result.setContentLength(httpReturn.getContentLength()); result.setContentType(httpReturn.getContentType()); result.setStatusCode(httpReturn.getStatusCode()); diff --git a/src/main/java/org/bench4q/agent/scenario/behavior/Behavior.java b/src/main/java/org/bench4q/agent/scenario/behavior/Behavior.java index c94b6acc..2cb07860 100644 --- a/src/main/java/org/bench4q/agent/scenario/behavior/Behavior.java +++ b/src/main/java/org/bench4q/agent/scenario/behavior/Behavior.java @@ -48,4 +48,13 @@ public abstract class Behavior { public abstract Map getBehaviorBriefResult( DataCollector dataStatistics); + + public String getUrl() { + for (Parameter parameter : this.getParameters()) { + if (parameter.getKey().equals("url")) { + return parameter.getValue(); + } + } + return ""; + } } diff --git a/src/test/java/org/bench4q/agent/test/TestWithScriptFile.java b/src/test/java/org/bench4q/agent/test/TestWithScriptFile.java index d27cf157..aebed98a 100644 --- a/src/test/java/org/bench4q/agent/test/TestWithScriptFile.java +++ b/src/test/java/org/bench4q/agent/test/TestWithScriptFile.java @@ -170,14 +170,16 @@ public class TestWithScriptFile { private void pageBrief(int i) throws IOException, JAXBException { try { - HttpResponse httpResponse = this.getHttpRequester().sendGet(url, - null, null); + HttpResponse httpResponse = this.getHttpRequester().sendGet( + url + "/pageBrief/" + this.getTestId() + "/" + i, null, + null); if (httpResponse == null || httpResponse.getContent().isEmpty()) { fail(); } System.out.println(httpResponse); AgentPageBriefModel pageBriefModel = (AgentPageBriefModel) MarshalHelper - .unmarshal(AgentPageBriefModel.class, httpResponse.getContent()); + .unmarshal(AgentPageBriefModel.class, + httpResponse.getContent()); assertTrue(pageBriefModel.getCountFromBegin() > 0); } catch (Exception e) { this.stopTest(); From 540ffeac2563e5330c9b6727ae4eb6a4d8b30b4c Mon Sep 17 00:00:00 2001 From: coderfengyun Date: Wed, 8 Jan 2014 11:38:05 +0800 Subject: [PATCH 144/196] remove the bug while using threadPool --- .../org/bench4q/agent/api/TestController.java | 483 +++++++++--------- .../impl/AbstractDataCollector.java | 164 +++--- .../agent/scenario/ScenarioEngine.java | 407 +++++++-------- 3 files changed, 530 insertions(+), 524 deletions(-) diff --git a/src/main/java/org/bench4q/agent/api/TestController.java b/src/main/java/org/bench4q/agent/api/TestController.java index 14704150..4d9d9bc6 100644 --- a/src/main/java/org/bench4q/agent/api/TestController.java +++ b/src/main/java/org/bench4q/agent/api/TestController.java @@ -1,239 +1,244 @@ -package org.bench4q.agent.api; - -import java.io.ByteArrayOutputStream; -import java.net.UnknownHostException; -import java.util.ArrayList; -import java.util.Date; -import java.util.List; -import java.util.Map; -import java.util.UUID; - -import javax.xml.bind.JAXBContext; -import javax.xml.bind.JAXBException; -import javax.xml.bind.Marshaller; - -import org.apache.log4j.Logger; -import org.bench4q.agent.datacollector.impl.BehaviorStatusCodeResult; -import org.bench4q.agent.scenario.Scenario; -import org.bench4q.agent.scenario.ScenarioContext; -import org.bench4q.agent.scenario.ScenarioEngine; -import org.bench4q.agent.scenario.behavior.Behavior; -import org.bench4q.share.models.agent.BehaviorBriefModel; -import org.bench4q.share.models.agent.BehaviorStatusCodeResultModel; -import org.bench4q.share.models.agent.CleanTestResultModel; -import org.bench4q.share.models.agent.RunScenarioModel; -import org.bench4q.share.models.agent.RunScenarioResultModel; -import org.bench4q.share.models.agent.StopTestModel; -import org.bench4q.share.models.agent.statistics.AgentBriefStatusModel; -import org.bench4q.share.models.agent.statistics.AgentBehaviorsBriefModel; -import org.bench4q.share.models.agent.statistics.AgentPageBriefModel; -import org.bench4q.share.models.agent.statistics.AgentPagesBriefModel; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.ResponseBody; - -@Controller -@RequestMapping("/test") -public class TestController { - private ScenarioEngine scenarioEngine; - private Logger logger = Logger.getLogger(TestController.class); - - private Logger getLogger() { - return logger; - } - - private ScenarioEngine getScenarioEngine() { - return scenarioEngine; - } - - @Autowired - private void setScenarioEngine(ScenarioEngine scenarioEngine) { - this.scenarioEngine = scenarioEngine; - } - - @RequestMapping(value = "/run", method = RequestMethod.POST) - @ResponseBody - public RunScenarioResultModel run( - @RequestBody RunScenarioModel runScenarioModel) - throws UnknownHostException { - // Scenario scenario = extractScenario(runScenarioModel); - Scenario scenario = Scenario.scenarioBuilder(runScenarioModel); - UUID runId = UUID.randomUUID(); - System.out.println(runScenarioModel.getPoolSize()); - this.getLogger().info(marshalRunScenarioModel(runScenarioModel)); - this.getScenarioEngine().runScenario(runId, scenario, - runScenarioModel.getPoolSize()); - RunScenarioResultModel runScenarioResultModel = new RunScenarioResultModel(); - runScenarioResultModel.setRunId(runId); - return runScenarioResultModel; - } - - private String marshalRunScenarioModel(RunScenarioModel inModel) { - ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); - Marshaller marshaller; - try { - marshaller = JAXBContext.newInstance(RunScenarioModel.class) - .createMarshaller(); - marshaller.marshal(inModel, outputStream); - return outputStream.toString(); - } catch (JAXBException e) { - return "exception in marshal"; - } - - } - - @RequestMapping(value = "/brief/{runId}/{behaviorId}", method = RequestMethod.GET) - @ResponseBody - public BehaviorBriefModel behaviorBrief(@PathVariable UUID runId, - @PathVariable int behaviorId) { - ScenarioContext scenarioContext = this.getScenarioEngine() - .getRunningTests().get(runId); - if (scenarioContext == null) { - return null; - } - Map map = scenarioContext - .getDataStatistics().getBehaviorBriefStatistics(behaviorId); - return buildBehaviorBrief(runId, behaviorId, "", map); - } - - private BehaviorBriefModel buildBehaviorBrief(UUID runId, int behaviorId, - String behaviorUrl, Map map) { - List detailStatusCodeResultModels = new ArrayList(); - for (int statusCode : map.keySet()) { - BehaviorStatusCodeResultModel behaviorStatusCodeResultModel = new BehaviorStatusCodeResultModel(); - BehaviorStatusCodeResult detailStatusCodeResult = map - .get(statusCode); - behaviorStatusCodeResultModel.setStatusCode(statusCode); - behaviorStatusCodeResultModel - .setCount(detailStatusCodeResult.count); - behaviorStatusCodeResultModel - .setContentLength(detailStatusCodeResult.contentLength); - behaviorStatusCodeResultModel - .setMinResponseTime(detailStatusCodeResult.minResponseTime); - behaviorStatusCodeResultModel - .setMaxResponseTime(detailStatusCodeResult.maxResponseTime); - behaviorStatusCodeResultModel - .setContentType(detailStatusCodeResult.contentType); - behaviorStatusCodeResultModel - .setTotalResponseTimeThisTime(detailStatusCodeResult.totalResponseTimeThisTime); - detailStatusCodeResultModels.add(behaviorStatusCodeResultModel); - } - BehaviorBriefModel behaviorBriefModel = new BehaviorBriefModel(); - behaviorBriefModel.setBehaviorId(behaviorId); - behaviorBriefModel - .setDetailStatusCodeResultModels(detailStatusCodeResultModels); - behaviorBriefModel.setBehaviorUrl(behaviorUrl); - return behaviorBriefModel; - } - - @RequestMapping(value = "/pagesBrief/{runId}") - @ResponseBody - public AgentPagesBriefModel pagesBrief(@PathVariable UUID runId) { - ScenarioContext context = this.getScenarioEngine().getRunningTests() - .get(runId); - AgentPagesBriefModel result = new AgentPagesBriefModel(); - List pageBrieves = new ArrayList(); - - if (context == null || context.isFinished()) { - return null; - } - for (int i = 0; i < context.getScenario().getPages().length; i++) { - pageBrieves.add((AgentPageBriefModel) context.getDataStatistics() - .getPageBriefStatistics(i)); - } - result.setPageBriefModels(pageBrieves); - return result; - } - - @RequestMapping(value = "/pageBrief/{runId}/{pageId}") - @ResponseBody - public AgentPageBriefModel pageBrief(@PathVariable UUID runId, - @PathVariable int pageId) { - ScenarioContext context = this.getScenarioEngine().getRunningTests() - .get(runId); - if (context == null || context.isFinished()) { - return null; - } - return (AgentPageBriefModel) context.getDataStatistics() - .getPageBriefStatistics(pageId); - } - - @RequestMapping(value = "/behaviorsBrief/{runId}") - @ResponseBody - public AgentBehaviorsBriefModel behaviorsBrief(@PathVariable UUID runId) { - AgentBehaviorsBriefModel ret = new AgentBehaviorsBriefModel(); - List behaviorBriefModels = new ArrayList(); - ScenarioContext scenarioContext = this.getScenarioEngine() - .getRunningTests().get(runId); - if (scenarioContext == null || scenarioContext.isFinished()) { - return null; - } - for (Behavior behavior : scenarioContext.getScenario() - .getAllBehaviorsInScenario()) { - int behaviorId = behavior.getId(); - Map map = behavior - .getBehaviorBriefResult(scenarioContext.getDataStatistics()); - if (map == null) { - continue; - } - behaviorBriefModels.add(buildBehaviorBrief(runId, behaviorId, - behavior.getUrl(), map)); - } - ret.setBehaviorBriefModels(behaviorBriefModels); - return ret; - } - - @RequestMapping(value = "/brief/{runId}", method = RequestMethod.GET) - @ResponseBody - public AgentBriefStatusModel brief(@PathVariable UUID runId) { - ScenarioContext scenarioContext = this.getScenarioEngine() - .getRunningTests().get(runId); - if (scenarioContext == null) { - return null; - } - AgentBriefStatusModel agentStatusModel = (AgentBriefStatusModel) scenarioContext - .getDataStatistics().getScenarioBriefStatistics(); - agentStatusModel.setvUserCount(scenarioContext.getExecutor() - .getActiveCount()); - return agentStatusModel; - } - - @RequestMapping(value = "/stop/{runId}", method = { RequestMethod.GET, - RequestMethod.POST }) - @ResponseBody - public StopTestModel stop(@PathVariable UUID runId) { - System.out.println("stop method"); - ScenarioContext scenarioContext = this.getScenarioEngine() - .getRunningTests().get(runId); - if (scenarioContext == null) { - return null; - } - scenarioContext.setEndDate(new Date(System.currentTimeMillis())); - scenarioContext.getExecutor().shutdownNow(); - scenarioContext.setFinished(true); - StopTestModel stopTestModel = new StopTestModel(); - stopTestModel.setSuccess(true); - clean(runId); - return stopTestModel; - } - - @RequestMapping(value = "/clean/{runId}", method = RequestMethod.GET) - @ResponseBody - public CleanTestResultModel clean(@PathVariable UUID runId) { - ScenarioContext scenarioContext = this.getScenarioEngine() - .getRunningTests().get(runId); - if (scenarioContext == null) { - return null; - } - scenarioContext.getExecutor().shutdownNow(); - this.getScenarioEngine().getRunningTests().remove(runId); - System.gc(); - CleanTestResultModel cleanTestResultModel = new CleanTestResultModel(); - cleanTestResultModel.setSuccess(true); - return cleanTestResultModel; - } -} +package org.bench4q.agent.api; + +import java.io.ByteArrayOutputStream; +import java.net.UnknownHostException; +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +import javax.xml.bind.JAXBContext; +import javax.xml.bind.JAXBException; +import javax.xml.bind.Marshaller; + +import org.apache.log4j.Logger; +import org.bench4q.agent.datacollector.impl.BehaviorStatusCodeResult; +import org.bench4q.agent.scenario.Scenario; +import org.bench4q.agent.scenario.ScenarioContext; +import org.bench4q.agent.scenario.ScenarioEngine; +import org.bench4q.agent.scenario.behavior.Behavior; +import org.bench4q.share.models.agent.BehaviorBriefModel; +import org.bench4q.share.models.agent.BehaviorStatusCodeResultModel; +import org.bench4q.share.models.agent.CleanTestResultModel; +import org.bench4q.share.models.agent.RunScenarioModel; +import org.bench4q.share.models.agent.RunScenarioResultModel; +import org.bench4q.share.models.agent.StopTestModel; +import org.bench4q.share.models.agent.statistics.AgentBriefStatusModel; +import org.bench4q.share.models.agent.statistics.AgentBehaviorsBriefModel; +import org.bench4q.share.models.agent.statistics.AgentPageBriefModel; +import org.bench4q.share.models.agent.statistics.AgentPagesBriefModel; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.ResponseBody; + +@Controller +@RequestMapping("/test") +public class TestController { + private ScenarioEngine scenarioEngine; + private Logger logger = Logger.getLogger(TestController.class); + + private Logger getLogger() { + return logger; + } + + private ScenarioEngine getScenarioEngine() { + return scenarioEngine; + } + + @Autowired + private void setScenarioEngine(ScenarioEngine scenarioEngine) { + this.scenarioEngine = scenarioEngine; + } + + @RequestMapping(value = "/run", method = RequestMethod.POST) + @ResponseBody + public RunScenarioResultModel run( + @RequestBody RunScenarioModel runScenarioModel) + throws UnknownHostException { + // Scenario scenario = extractScenario(runScenarioModel); + Scenario scenario = Scenario.scenarioBuilder(runScenarioModel); + UUID runId = UUID.randomUUID(); + System.out.println(runScenarioModel.getPoolSize()); + this.getLogger().info(marshalRunScenarioModel(runScenarioModel)); + this.getScenarioEngine().runScenario(runId, scenario, + runScenarioModel.getPoolSize()); + RunScenarioResultModel runScenarioResultModel = new RunScenarioResultModel(); + runScenarioResultModel.setRunId(runId); + return runScenarioResultModel; + } + + private String marshalRunScenarioModel(RunScenarioModel inModel) { + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + Marshaller marshaller; + try { + marshaller = JAXBContext.newInstance(RunScenarioModel.class) + .createMarshaller(); + marshaller.marshal(inModel, outputStream); + return outputStream.toString(); + } catch (JAXBException e) { + return "exception in marshal"; + } + + } + + @RequestMapping(value = "/brief/{runId}/{behaviorId}", method = RequestMethod.GET) + @ResponseBody + public BehaviorBriefModel behaviorBrief(@PathVariable UUID runId, + @PathVariable int behaviorId) { + ScenarioContext scenarioContext = this.getScenarioEngine() + .getRunningTests().get(runId); + if (scenarioContext == null) { + return null; + } + Map map = scenarioContext + .getDataStatistics().getBehaviorBriefStatistics(behaviorId); + return buildBehaviorBrief(runId, behaviorId, "", map); + } + + private BehaviorBriefModel buildBehaviorBrief(UUID runId, int behaviorId, + String behaviorUrl, Map map) { + List detailStatusCodeResultModels = new ArrayList(); + for (int statusCode : map.keySet()) { + BehaviorStatusCodeResultModel behaviorStatusCodeResultModel = new BehaviorStatusCodeResultModel(); + BehaviorStatusCodeResult detailStatusCodeResult = map + .get(statusCode); + behaviorStatusCodeResultModel.setStatusCode(statusCode); + behaviorStatusCodeResultModel + .setCount(detailStatusCodeResult.count); + behaviorStatusCodeResultModel + .setContentLength(detailStatusCodeResult.contentLength); + behaviorStatusCodeResultModel + .setMinResponseTime(detailStatusCodeResult.minResponseTime); + behaviorStatusCodeResultModel + .setMaxResponseTime(detailStatusCodeResult.maxResponseTime); + behaviorStatusCodeResultModel + .setContentType(detailStatusCodeResult.contentType); + behaviorStatusCodeResultModel + .setTotalResponseTimeThisTime(detailStatusCodeResult.totalResponseTimeThisTime); + detailStatusCodeResultModels.add(behaviorStatusCodeResultModel); + } + BehaviorBriefModel behaviorBriefModel = new BehaviorBriefModel(); + behaviorBriefModel.setBehaviorId(behaviorId); + behaviorBriefModel + .setDetailStatusCodeResultModels(detailStatusCodeResultModels); + behaviorBriefModel.setBehaviorUrl(behaviorUrl); + return behaviorBriefModel; + } + + @RequestMapping(value = "/pagesBrief/{runId}") + @ResponseBody + public AgentPagesBriefModel pagesBrief(@PathVariable UUID runId) { + ScenarioContext context = this.getScenarioEngine().getRunningTests() + .get(runId); + AgentPagesBriefModel result = new AgentPagesBriefModel(); + List pageBrieves = new ArrayList(); + + if (context == null || context.isFinished()) { + return null; + } + for (int i = 0; i < context.getScenario().getPages().length; i++) { + pageBrieves.add((AgentPageBriefModel) context.getDataStatistics() + .getPageBriefStatistics(i)); + } + result.setPageBriefModels(pageBrieves); + return result; + } + + @RequestMapping(value = "/pageBrief/{runId}/{pageId}") + @ResponseBody + public AgentPageBriefModel pageBrief(@PathVariable UUID runId, + @PathVariable int pageId) { + ScenarioContext context = this.getScenarioEngine().getRunningTests() + .get(runId); + if (context == null || context.isFinished()) { + return null; + } + return (AgentPageBriefModel) context.getDataStatistics() + .getPageBriefStatistics(pageId); + } + + @RequestMapping(value = "/behaviorsBrief/{runId}") + @ResponseBody + public AgentBehaviorsBriefModel behaviorsBrief(@PathVariable UUID runId) { + AgentBehaviorsBriefModel ret = new AgentBehaviorsBriefModel(); + List behaviorBriefModels = new ArrayList(); + ScenarioContext scenarioContext = this.getScenarioEngine() + .getRunningTests().get(runId); + if (scenarioContext == null || scenarioContext.isFinished()) { + return null; + } + for (Behavior behavior : scenarioContext.getScenario() + .getAllBehaviorsInScenario()) { + int behaviorId = behavior.getId(); + Map map = behavior + .getBehaviorBriefResult(scenarioContext.getDataStatistics()); + if (map == null) { + continue; + } + behaviorBriefModels.add(buildBehaviorBrief(runId, behaviorId, + behavior.getUrl(), map)); + } + ret.setBehaviorBriefModels(behaviorBriefModels); + return ret; + } + + @RequestMapping(value = "/brief/{runId}", method = RequestMethod.GET) + @ResponseBody + public AgentBriefStatusModel brief(@PathVariable UUID runId) { + ScenarioContext scenarioContext = this.getScenarioEngine() + .getRunningTests().get(runId); + if (scenarioContext == null) { + return null; + } + AgentBriefStatusModel agentStatusModel = (AgentBriefStatusModel) scenarioContext + .getDataStatistics().getScenarioBriefStatistics(); + agentStatusModel.setvUserCount(scenarioContext.getExecutor() + .getActiveCount()); + return agentStatusModel; + } + + @RequestMapping(value = "/stop/{runId}", method = { RequestMethod.GET, + RequestMethod.POST }) + @ResponseBody + public StopTestModel stop(@PathVariable UUID runId) { + System.out.println("stop method"); + ScenarioContext scenarioContext = this.getScenarioEngine() + .getRunningTests().get(runId); + if (scenarioContext == null) { + return null; + } + scenarioContext.setEndDate(new Date(System.currentTimeMillis())); + System.out.println("when before stop, classId:" + + scenarioContext.getExecutor().toString()); + scenarioContext.getExecutor().shutdown(); + scenarioContext.getExecutor().shutdownNow(); + System.out.println("when after stop, classId:" + + scenarioContext.getExecutor().toString()); + scenarioContext.setFinished(true); + StopTestModel stopTestModel = new StopTestModel(); + stopTestModel.setSuccess(true); + clean(runId); + return stopTestModel; + } + + @RequestMapping(value = "/clean/{runId}", method = RequestMethod.GET) + @ResponseBody + public CleanTestResultModel clean(@PathVariable UUID runId) { + ScenarioContext scenarioContext = this.getScenarioEngine() + .getRunningTests().get(runId); + if (scenarioContext == null) { + return null; + } + scenarioContext.getExecutor().shutdownNow(); + this.getScenarioEngine().getRunningTests().remove(runId); + System.gc(); + CleanTestResultModel cleanTestResultModel = new CleanTestResultModel(); + cleanTestResultModel.setSuccess(true); + return cleanTestResultModel; + } +} diff --git a/src/main/java/org/bench4q/agent/datacollector/impl/AbstractDataCollector.java b/src/main/java/org/bench4q/agent/datacollector/impl/AbstractDataCollector.java index 2cad4b59..24228108 100644 --- a/src/main/java/org/bench4q/agent/datacollector/impl/AbstractDataCollector.java +++ b/src/main/java/org/bench4q/agent/datacollector/impl/AbstractDataCollector.java @@ -1,82 +1,82 @@ -package org.bench4q.agent.datacollector.impl; - -import java.util.Map; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; - -import org.bench4q.agent.Main; -import org.bench4q.agent.datacollector.interfaces.DataCollector; -import org.bench4q.agent.helper.ApplicationContextHelper; -import org.bench4q.agent.scenario.BehaviorResult; -import org.bench4q.agent.storage.StorageHelper; -import org.bench4q.share.models.agent.BehaviorResultModel; - -public abstract class AbstractDataCollector implements DataCollector { - protected StorageHelper storageHelper; - - protected StorageHelper getStorageHelper() { - return storageHelper; - } - - public void setStorageHelper(StorageHelper storageHelper) { - this.storageHelper = storageHelper; - } - - public AbstractDataCollector() { - mustDoWhenIniti(); - } - - // Each sub class should call this in their constructor - protected void mustDoWhenIniti() { - this.setStorageHelper(ApplicationContextHelper.getContext().getBean( - StorageHelper.class)); - } - - public void add(final BehaviorResult behaviorResult) { - if (!Main.IS_TO_SAVE_DETAIL) { - return; - } - if (behaviorResult == null) { - return; - } - Runnable runnable = new Runnable() { - public void run() { - storageHelper.getLocalStorage().writeFile( - buildBehaviorResultModel(behaviorResult) - .getModelString(), - calculateSavePath(behaviorResult)); - } - }; - ExecutorService executorService = Executors - .newSingleThreadScheduledExecutor(); - executorService.execute(runnable); - executorService.shutdown(); - } - - private BehaviorResultModel buildBehaviorResultModel( - BehaviorResult behaviorResult) { - BehaviorResultModel resultModel = new BehaviorResultModel(); - resultModel.setBehaviorId(behaviorResult.getBehaviorId()); - resultModel.setBehaviorName(behaviorResult.getBehaviorName()); - resultModel.setContentLength(behaviorResult.getContentLength()); - resultModel.setContentType(behaviorResult.getContentType()); - resultModel.setEndDate(behaviorResult.getEndDate()); - resultModel.setPluginId(behaviorResult.getPluginId()); - resultModel.setPluginName(behaviorResult.getPluginName()); - resultModel.setResponseTime(behaviorResult.getResponseTime()); - resultModel.setShouldBeCountResponseTime(behaviorResult - .isShouldBeCountResponseTime()); - resultModel.setStartDate(behaviorResult.getStartDate()); - resultModel.setStatusCode(behaviorResult.getStatusCode()); - resultModel.setSuccess(behaviorResult.isSuccess()); - return resultModel; - } - - protected abstract String calculateSavePath(BehaviorResult behaviorResult); - - public abstract Object getScenarioBriefStatistics(); - - public abstract Map getBehaviorBriefStatistics( - int id); - -} +package org.bench4q.agent.datacollector.impl; + +import java.util.Map; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +import org.bench4q.agent.Main; +import org.bench4q.agent.datacollector.interfaces.DataCollector; +import org.bench4q.agent.helper.ApplicationContextHelper; +import org.bench4q.agent.scenario.BehaviorResult; +import org.bench4q.agent.storage.StorageHelper; +import org.bench4q.share.models.agent.BehaviorResultModel; + +public abstract class AbstractDataCollector implements DataCollector { + protected StorageHelper storageHelper; + + protected StorageHelper getStorageHelper() { + return storageHelper; + } + + public void setStorageHelper(StorageHelper storageHelper) { + this.storageHelper = storageHelper; + } + + public AbstractDataCollector() { + mustDoWhenIniti(); + } + + // Each sub class should call this in their constructor + protected void mustDoWhenIniti() { + this.setStorageHelper(ApplicationContextHelper.getContext().getBean( + StorageHelper.class)); + } + + public void add(final BehaviorResult behaviorResult) { + if (!Main.IS_TO_SAVE_DETAIL) { + return; + } + if (behaviorResult == null) { + return; + } + Runnable runnable = new Runnable() { + public void run() { + storageHelper.getLocalStorage().writeFile( + buildBehaviorResultModel(behaviorResult) + .getModelString(), + calculateSavePath(behaviorResult)); + } + }; + ExecutorService executorService = Executors + .newSingleThreadScheduledExecutor(); + executorService.execute(runnable); + executorService.shutdown(); + } + + private BehaviorResultModel buildBehaviorResultModel( + BehaviorResult behaviorResult) { + BehaviorResultModel resultModel = new BehaviorResultModel(); + resultModel.setBehaviorId(behaviorResult.getBehaviorId()); + resultModel.setBehaviorName(behaviorResult.getBehaviorName()); + resultModel.setContentLength(behaviorResult.getContentLength()); + resultModel.setContentType(behaviorResult.getContentType()); + resultModel.setEndDate(behaviorResult.getEndDate()); + resultModel.setPluginId(behaviorResult.getPluginId()); + resultModel.setPluginName(behaviorResult.getPluginName()); + resultModel.setResponseTime(behaviorResult.getResponseTime()); + resultModel.setShouldBeCountResponseTime(behaviorResult + .isShouldBeCountResponseTime()); + resultModel.setStartDate(behaviorResult.getStartDate()); + resultModel.setStatusCode(behaviorResult.getStatusCode()); + resultModel.setSuccess(behaviorResult.isSuccess()); + return resultModel; + } + + protected abstract String calculateSavePath(BehaviorResult behaviorResult); + + public abstract Object getScenarioBriefStatistics(); + + public abstract Map getBehaviorBriefStatistics( + int id); + +} diff --git a/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java b/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java index 06e192bd..5c1a3492 100644 --- a/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java +++ b/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java @@ -1,203 +1,204 @@ -package org.bench4q.agent.scenario; - -import java.util.ArrayList; -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.UUID; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.SynchronousQueue; -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.interfaces.DataCollector; -import org.bench4q.agent.plugin.Plugin; -import org.bench4q.agent.plugin.PluginManager; -import org.bench4q.agent.plugin.result.HttpReturn; -import org.bench4q.agent.plugin.result.PluginReturn; -import org.bench4q.agent.scenario.behavior.Behavior; -import org.bench4q.agent.storage.StorageHelper; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; - -@Component -public class ScenarioEngine { - private static final long keepAliveTime = 10; - private PluginManager pluginManager; - private Map runningTests; - private StorageHelper storageHelper; - private Logger logger; - - @SuppressWarnings("unused") - private Logger getLogger() { - return logger; - } - - private void setLogger(Logger logger) { - this.logger = logger; - } - - public ScenarioEngine() { - this.setRunningTests(new HashMap()); - this.setLogger(Logger.getLogger(ScenarioEngine.class)); - } - - private PluginManager getPluginManager() { - return pluginManager; - } - - @Autowired - private void setPluginManager(PluginManager pluginManager) { - this.pluginManager = pluginManager; - } - - public StorageHelper getStorageHelper() { - return storageHelper; - } - - @Autowired - public void setStorageHelper(StorageHelper storageHelper) { - this.storageHelper = storageHelper; - } - - public Map getRunningTests() { - return runningTests; - } - - private void setRunningTests(Map runningTests) { - this.runningTests = runningTests; - } - - public void runScenario(UUID runId, final Scenario scenario, int poolSize) { - try { - final SynchronousQueue workQueue = new SynchronousQueue(); - ThreadPoolExecutor executor = new ThreadPoolExecutor(poolSize, - poolSize, keepAliveTime, TimeUnit.MINUTES, workQueue, - new DiscardPolicy()); - final ScenarioContext scenarioContext = ScenarioContext - .buildScenarioContext(runId, scenario, poolSize, executor); - this.getRunningTests().put(runId, scenarioContext); - System.out.println(poolSize); - executeTasks(executor, scenarioContext); - } catch (Exception e) { - e.printStackTrace(); - } - } - - private void executeTasks(final ExecutorService executorService, - final ScenarioContext scenarioContext) { - ExecutorService taskMaker = Executors.newSingleThreadExecutor(); - taskMaker.execute(new Runnable() { - public void run() { - while (true) { - executorService.execute(new Runnable() { - public void run() { - doRunScenario(scenarioContext); - logger.info("end for once!"); - } - }); - } - } - }); - } - - public void doRunScenario(ScenarioContext context) { - Map plugins = new HashMap(); - preparePlugins(context.getScenario(), plugins); - for (int i = 0; i < context.getScenario().getPages().length; i++) { - Page page = context.getScenario().getPages()[i]; - context.getDataStatistics().add( - PageResult.buildPageResult( - i, - doRunBatchesInPage(plugins, page, - context.getDataStatistics()))); - } - } - - private List doRunBatchesInPage( - Map plugins, Page page, DataCollector dataCollector) { - List results = new ArrayList(); - for (Batch batch : page.getBatches()) { - results.addAll(doRunBatch(plugins, batch, dataCollector)); - } - return results; - } - - private List doRunBatch(Map plugins, - Batch batch, DataCollector dataCollector) { - List results = new ArrayList(); - for (Behavior behavior : batch.getBehaviors()) { - Object plugin = plugins.get(behavior.getUse()); - Map behaviorParameters = prepareBehaviorParameters(behavior); - Date startDate = new Date(System.currentTimeMillis()); - PluginReturn pluginReturn = (PluginReturn) this.getPluginManager() - .doBehavior(plugin, behavior.getName(), behaviorParameters); - Date endDate = new Date(System.currentTimeMillis()); - if (!behavior.shouldBeCountResponseTime()) { - continue; - } - BehaviorResult behaviorResult = buildBehaviorResult(behavior, - plugin, startDate, pluginReturn, endDate); - dataCollector.add(behaviorResult); - results.add(behaviorResult); - } - return results; - } - - private BehaviorResult buildBehaviorResult(Behavior behavior, - Object plugin, Date startDate, PluginReturn pluginReturn, - Date endDate) { - BehaviorResult result = new BehaviorResult(); - result.setStartDate(startDate); - result.setEndDate(endDate); - result.setSuccess(pluginReturn.isSuccess()); - result.setResponseTime(endDate.getTime() - startDate.getTime()); - result.setBehaviorName(behavior.getName()); - result.setPluginId(behavior.getUse()); - result.setPluginName(plugin.getClass().getAnnotation(Plugin.class) - .value()); - result.setShouldBeCountResponseTime(behavior - .shouldBeCountResponseTime()); - if (pluginReturn instanceof HttpReturn) { - HttpReturn httpReturn = (HttpReturn) pluginReturn; - result.setBehaviorId(behavior.getId()); - for (Parameter parameter : behavior.getParameters()) { - if (parameter.getKey().equals("url")) { - result.setBehaviorUrl(parameter.getValue()); - } - } - result.setContentLength(httpReturn.getContentLength()); - result.setContentType(httpReturn.getContentType()); - result.setStatusCode(httpReturn.getStatusCode()); - } - return result; - } - - private Map prepareBehaviorParameters(Behavior behavior) { - Map behaviorParameters = new HashMap(); - for (Parameter parameter : behavior.getParameters()) { - behaviorParameters.put(parameter.getKey(), parameter.getValue()); - } - return behaviorParameters; - } - - private void preparePlugins(Scenario scenario, Map plugins) { - for (UsePlugin usePlugin : scenario.getUsePlugins()) { - String pluginId = usePlugin.getId(); - Class pluginClass = this.getPluginManager().getPlugins() - .get(usePlugin.getName()); - Map initParameters = new HashMap(); - for (Parameter parameter : usePlugin.getParameters()) { - initParameters.put(parameter.getKey(), parameter.getValue()); - } - Object plugin = this.getPluginManager().initializePlugin( - pluginClass, initParameters); - plugins.put(pluginId, plugin); - } - } - -} +package org.bench4q.agent.scenario; + +import java.util.ArrayList; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.SynchronousQueue; +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.interfaces.DataCollector; +import org.bench4q.agent.plugin.Plugin; +import org.bench4q.agent.plugin.PluginManager; +import org.bench4q.agent.plugin.result.HttpReturn; +import org.bench4q.agent.plugin.result.PluginReturn; +import org.bench4q.agent.scenario.behavior.Behavior; +import org.bench4q.agent.storage.StorageHelper; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +@Component +public class ScenarioEngine { + private static final long keepAliveTime = 10; + private PluginManager pluginManager; + private Map runningTests; + private StorageHelper storageHelper; + private Logger logger; + + @SuppressWarnings("unused") + private Logger getLogger() { + return logger; + } + + private void setLogger(Logger logger) { + this.logger = logger; + } + + public ScenarioEngine() { + this.setRunningTests(new HashMap()); + this.setLogger(Logger.getLogger(ScenarioEngine.class)); + } + + private PluginManager getPluginManager() { + return pluginManager; + } + + @Autowired + private void setPluginManager(PluginManager pluginManager) { + this.pluginManager = pluginManager; + } + + public StorageHelper getStorageHelper() { + return storageHelper; + } + + @Autowired + public void setStorageHelper(StorageHelper storageHelper) { + this.storageHelper = storageHelper; + } + + public Map getRunningTests() { + return runningTests; + } + + private void setRunningTests(Map runningTests) { + this.runningTests = runningTests; + } + + public void runScenario(UUID runId, final Scenario scenario, int poolSize) { + try { + final SynchronousQueue workQueue = new SynchronousQueue(); + ThreadPoolExecutor executor = new ThreadPoolExecutor(poolSize, + poolSize, keepAliveTime, TimeUnit.MINUTES, workQueue, + new DiscardPolicy()); + final ScenarioContext scenarioContext = ScenarioContext + .buildScenarioContext(runId, scenario, poolSize, executor); + System.out.println("when run, classId:" + executor.toString()); + this.getRunningTests().put(runId, scenarioContext); + System.out.println(poolSize); + executeTasks(executor, scenarioContext); + } catch (Exception e) { + e.printStackTrace(); + } + } + + private void executeTasks(final ExecutorService executor, + final ScenarioContext scenarioContext) { + ExecutorService taskMaker = Executors.newSingleThreadExecutor(); + taskMaker.execute(new Runnable() { + public void run() { + while (!scenarioContext.isFinished()) { + executor.execute(new Runnable() { + public void run() { + doRunScenario(scenarioContext); + logger.info("end for once!"); + } + }); + } + } + }); + } + + public void doRunScenario(ScenarioContext context) { + Map plugins = new HashMap(); + preparePlugins(context.getScenario(), plugins); + for (int i = 0; i < context.getScenario().getPages().length; i++) { + Page page = context.getScenario().getPages()[i]; + context.getDataStatistics().add( + PageResult.buildPageResult( + i, + doRunBatchesInPage(plugins, page, + context.getDataStatistics()))); + } + } + + private List doRunBatchesInPage( + Map plugins, Page page, DataCollector dataCollector) { + List results = new ArrayList(); + for (Batch batch : page.getBatches()) { + results.addAll(doRunBatch(plugins, batch, dataCollector)); + } + return results; + } + + private List doRunBatch(Map plugins, + Batch batch, DataCollector dataCollector) { + List results = new ArrayList(); + for (Behavior behavior : batch.getBehaviors()) { + Object plugin = plugins.get(behavior.getUse()); + Map behaviorParameters = prepareBehaviorParameters(behavior); + Date startDate = new Date(System.currentTimeMillis()); + PluginReturn pluginReturn = (PluginReturn) this.getPluginManager() + .doBehavior(plugin, behavior.getName(), behaviorParameters); + Date endDate = new Date(System.currentTimeMillis()); + if (!behavior.shouldBeCountResponseTime()) { + continue; + } + BehaviorResult behaviorResult = buildBehaviorResult(behavior, + plugin, startDate, pluginReturn, endDate); + dataCollector.add(behaviorResult); + results.add(behaviorResult); + } + return results; + } + + private BehaviorResult buildBehaviorResult(Behavior behavior, + Object plugin, Date startDate, PluginReturn pluginReturn, + Date endDate) { + BehaviorResult result = new BehaviorResult(); + result.setStartDate(startDate); + result.setEndDate(endDate); + result.setSuccess(pluginReturn.isSuccess()); + result.setResponseTime(endDate.getTime() - startDate.getTime()); + result.setBehaviorName(behavior.getName()); + result.setPluginId(behavior.getUse()); + result.setPluginName(plugin.getClass().getAnnotation(Plugin.class) + .value()); + result.setShouldBeCountResponseTime(behavior + .shouldBeCountResponseTime()); + if (pluginReturn instanceof HttpReturn) { + HttpReturn httpReturn = (HttpReturn) pluginReturn; + result.setBehaviorId(behavior.getId()); + for (Parameter parameter : behavior.getParameters()) { + if (parameter.getKey().equals("url")) { + result.setBehaviorUrl(parameter.getValue()); + } + } + result.setContentLength(httpReturn.getContentLength()); + result.setContentType(httpReturn.getContentType()); + result.setStatusCode(httpReturn.getStatusCode()); + } + return result; + } + + private Map prepareBehaviorParameters(Behavior behavior) { + Map behaviorParameters = new HashMap(); + for (Parameter parameter : behavior.getParameters()) { + behaviorParameters.put(parameter.getKey(), parameter.getValue()); + } + return behaviorParameters; + } + + private void preparePlugins(Scenario scenario, Map plugins) { + for (UsePlugin usePlugin : scenario.getUsePlugins()) { + String pluginId = usePlugin.getId(); + Class pluginClass = this.getPluginManager().getPlugins() + .get(usePlugin.getName()); + Map initParameters = new HashMap(); + for (Parameter parameter : usePlugin.getParameters()) { + initParameters.put(parameter.getKey(), parameter.getValue()); + } + Object plugin = this.getPluginManager().initializePlugin( + pluginClass, initParameters); + plugins.put(pluginId, plugin); + } + } + +} From b24a6585c3b39a2627217275aba4e75d95c2ad61 Mon Sep 17 00:00:00 2001 From: coderfengyun Date: Wed, 8 Jan 2014 11:39:57 +0800 Subject: [PATCH 145/196] little refa --- .../java/org/bench4q/agent/scenario/ScenarioEngine.java | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java b/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java index 5c1a3492..e97a5c5c 100644 --- a/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java +++ b/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java @@ -83,19 +83,18 @@ public class ScenarioEngine { System.out.println("when run, classId:" + executor.toString()); this.getRunningTests().put(runId, scenarioContext); System.out.println(poolSize); - executeTasks(executor, scenarioContext); + executeTasks(scenarioContext); } catch (Exception e) { e.printStackTrace(); } } - private void executeTasks(final ExecutorService executor, - final ScenarioContext scenarioContext) { + private void executeTasks(final ScenarioContext scenarioContext) { ExecutorService taskMaker = Executors.newSingleThreadExecutor(); taskMaker.execute(new Runnable() { public void run() { while (!scenarioContext.isFinished()) { - executor.execute(new Runnable() { + scenarioContext.getExecutor().execute(new Runnable() { public void run() { doRunScenario(scenarioContext); logger.info("end for once!"); From 8bb434c8a65e4fd2b8a6230f1b435e25a00c703f Mon Sep 17 00:00:00 2001 From: coderfengyun Date: Wed, 15 Jan 2014 15:16:17 +0800 Subject: [PATCH 146/196] refactor the way of send a http request --- .../345376a7-d01c-4faa-af89-4a3e1a182048.xml | 42 +- Scripts/goodForPage.xml | 235 ++++++++++- .../agent/plugin/basic/HttpPlugin.java | 368 +++++++++-------- .../agent/scenario/utils/ParameterParser.java | 219 ++++++++++ .../agent/test/TestWithScriptFile.java | 386 +++++++++--------- .../agent/test/plugin/TestHttpPlugin.java | 62 ++- 6 files changed, 927 insertions(+), 385 deletions(-) create mode 100644 src/main/java/org/bench4q/agent/scenario/utils/ParameterParser.java diff --git a/Scripts/345376a7-d01c-4faa-af89-4a3e1a182048.xml b/Scripts/345376a7-d01c-4faa-af89-4a3e1a182048.xml index d65eda6c..53e13dfa 100644 --- a/Scripts/345376a7-d01c-4faa-af89-4a3e1a182048.xml +++ b/Scripts/345376a7-d01c-4faa-af89-4a3e1a182048.xml @@ -1 +1,41 @@ -1Geturlhttp://localhost:8080/Bench4QTestCase/testcase.htmlparametershttp-10-10httpHttptimerConstantTimer \ No newline at end of file + + + + + + + 1 + Get + + + url + http://www.baidu.com + + + + parameters + + + + http + + + -1 + 0 + -1 + + + 0 + + + http + Http + + + + timer + ConstantTimer + + + + \ No newline at end of file diff --git a/Scripts/goodForPage.xml b/Scripts/goodForPage.xml index 635a1995..12cb22e0 100644 --- a/Scripts/goodForPage.xml +++ b/Scripts/goodForPage.xml @@ -1 +1,234 @@ -0Geturlhttp://133.133.12.3:8080/Bench4QTestCase/testcase.htmlparametersUSERBEHAVIORhttp20-10Sleeptime230TIMERBEHAVIORtimer-11-11Geturlhttp://133.133.12.3:8080/Bench4QTestCase/script/agentTable.jsparametersUSERBEHAVIORhttp2Geturlhttp://133.133.12.3:8080/Bench4QTestCase/images/3.jpgparametersUSERBEHAVIORhttp3Geturlhttp://133.133.12.3:8080/Bench4QTestCase/script/base.jsparametersUSERBEHAVIORhttp4Geturlhttp://133.133.12.3:8080/Bench4QTestCase/images/1.jpgparametersUSERBEHAVIORhttp5Geturlhttp://133.133.12.3:8080/Bench4QTestCase/images/2.jpgparametersUSERBEHAVIORhttp-1200Sleeptime96TIMERBEHAVIORtimer-13-10Sleeptime3TIMERBEHAVIORtimer-14-10Sleeptime10TIMERBEHAVIORtimer-15-10Sleeptime6TIMERBEHAVIORtimer-16-10httpHttptimerConstantTimer \ No newline at end of file + + + + + + + + + 0 + Get + + + url + + http://133.133.12.3:8080/Bench4QTestCase/testcase.html + + + + parameters + + + + USERBEHAVIOR + http + + + 2 + 0 + -1 + + + + + 0 + Sleep + + + time + 230 + + + TIMERBEHAVIOR + timer + + + -1 + 1 + -1 + + + + + 1 + Get + + + url + http://133.133.12.3:8080/Bench4QTestCase/script/agentTable.js + + + + parameters + + + + USERBEHAVIOR + http + + + 2 + Get + + + url + http://133.133.12.3:8080/Bench4QTestCase/images/3.jpg + + + + parameters + + + + USERBEHAVIOR + http + + + 3 + Get + + + url + http://133.133.12.3:8080/Bench4QTestCase/script/base.js + + + + parameters + + + + USERBEHAVIOR + http + + + 4 + Get + + + url + http://133.133.12.3:8080/Bench4QTestCase/images/1.jpg + + + + parameters + + + + USERBEHAVIOR + http + + + 5 + Get + + + url + http://133.133.12.3:8080/Bench4QTestCase/images/2.jpg + + + + parameters + + + + USERBEHAVIOR + http + + + -1 + 2 + 0 + + + + + 0 + Sleep + + + time + 96 + + + TIMERBEHAVIOR + timer + + + -1 + 3 + -1 + + + + + 0 + Sleep + + + time + 3 + + + TIMERBEHAVIOR + timer + + + -1 + 4 + -1 + + + + + 0 + Sleep + + + time + 10 + + + TIMERBEHAVIOR + timer + + + -1 + 5 + -1 + + + + + 0 + Sleep + + + time + 6 + + + TIMERBEHAVIOR + timer + + + -1 + 6 + -1 + + + + + 0 + + + http + Http + + + + timer + ConstantTimer + + + + \ No newline at end of file diff --git a/src/main/java/org/bench4q/agent/plugin/basic/HttpPlugin.java b/src/main/java/org/bench4q/agent/plugin/basic/HttpPlugin.java index 7612dfcb..4be168ca 100644 --- a/src/main/java/org/bench4q/agent/plugin/basic/HttpPlugin.java +++ b/src/main/java/org/bench4q/agent/plugin/basic/HttpPlugin.java @@ -1,162 +1,206 @@ -package org.bench4q.agent.plugin.basic; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; -import java.io.OutputStreamWriter; -import java.net.HttpURLConnection; -import java.net.MalformedURLException; -import java.net.URL; - -import org.apache.log4j.Logger; -import org.bench4q.agent.plugin.Behavior; -import org.bench4q.agent.plugin.Parameter; -import org.bench4q.agent.plugin.Plugin; -import org.bench4q.agent.plugin.result.HttpReturn; -import org.bench4q.agent.share.DealWithLog; - -@Plugin("Http") -public class HttpPlugin { - private Logger logger = Logger.getLogger(HttpPlugin.class); - - public HttpPlugin() { - - } - - @Behavior("Get") - public HttpReturn get(@Parameter("url") String url) { - HttpURLConnection httpURLConnection = null; - StringBuffer stringBuffer = null; - String requestMethod = "GET"; - try { - httpURLConnection = getRequestURLConnection(url, requestMethod); - stringBuffer = readConnectionInputStream(httpURLConnection); - return new HttpReturn(true, httpURLConnection.getResponseCode(), - stringBuffer.length() * 2, - httpURLConnection.getContentType()); - } catch (MalformedURLException e) { - logger.info(DealWithLog.getExceptionStackTrace(e)); - return new HttpReturn(false, 400, 0, ""); - } catch (IOException e) { - logger.info(DealWithLog.getExceptionStackTrace(e)); - return new HttpReturn(false, 404, 0, ""); - } - - } - - private HttpURLConnection getRequestURLConnection(String url, String method) - throws MalformedURLException, IOException { - HttpURLConnection httpURLConnection; - URL target = new URL(url); - httpURLConnection = (HttpURLConnection) target.openConnection(); - if (method.equals("GET")) { - httpURLConnection.setDoOutput(false); - } else { - httpURLConnection.setDoOutput(true); - } - httpURLConnection.setDoOutput(true); - httpURLConnection.setDoInput(true); - httpURLConnection.setUseCaches(false); - httpURLConnection.setRequestMethod(method); - return httpURLConnection; - } - - private StringBuffer readConnectionInputStream( - HttpURLConnection httpURLConnection) throws IOException { - StringBuffer stringBuffer = new StringBuffer(); - BufferedReader bufferedReader = new BufferedReader( - new InputStreamReader(httpURLConnection.getInputStream())); - int temp = -1; - while ((temp = bufferedReader.read()) != -1) { - stringBuffer.append((char) temp); - } - bufferedReader.close(); - return stringBuffer; - } - - private void writeContentToConnectOutputSteam(String content, - HttpURLConnection httpURLConnection) throws IOException { - OutputStreamWriter outputStreamWriter = new OutputStreamWriter( - httpURLConnection.getOutputStream()); - outputStreamWriter.write(content); - outputStreamWriter.flush(); - outputStreamWriter.close(); - } - - @Behavior("Post") - public HttpReturn post(@Parameter("url") String url, - @Parameter("content") String content, - @Parameter("contentType") String contentType, - @Parameter("accept") String accept) { - HttpURLConnection httpURLConnection = null; - String requestMethod = "POST"; - StringBuffer stringBuffer = null; - try { - httpURLConnection = getRequestURLConnection(url, requestMethod); - httpURLConnection.setRequestMethod("POST"); - if (contentType != null && contentType.length() > 0) { - httpURLConnection.setRequestProperty("Content-Type", - contentType); - } - if (accept != null && accept.length() > 0) { - httpURLConnection.setRequestProperty("Accept", accept); - } - writeContentToConnectOutputSteam(content, httpURLConnection); - stringBuffer = readConnectionInputStream(httpURLConnection); - return new HttpReturn(true, httpURLConnection.getResponseCode(), - stringBuffer.length() * 2, - httpURLConnection.getContentType()); - } catch (MalformedURLException e) { - logger.info(DealWithLog.getExceptionStackTrace(e)); - return new HttpReturn(false, 400, 0, ""); - } catch (IOException e) { - logger.info(DealWithLog.getExceptionStackTrace(e)); - return new HttpReturn(false, 404, 0, ""); - } - - } - - @Behavior("Put") - public HttpReturn put(@Parameter("url") String url, - @Parameter("content") String content) { - StringBuffer stringBuffer = null; - String requestMethod = "PUT"; - try { - HttpURLConnection httpURLConnection = this.getRequestURLConnection( - url, requestMethod); - writeContentToConnectOutputSteam(content, httpURLConnection); - stringBuffer = readConnectionInputStream(httpURLConnection); - return new HttpReturn(true, httpURLConnection.getResponseCode(), - stringBuffer.length() * 2, - httpURLConnection.getContentType()); - } catch (MalformedURLException e) { - logger.info(DealWithLog.getExceptionStackTrace(e)); - return new HttpReturn(false, 400, 0, ""); - } catch (IOException e) { - logger.info(DealWithLog.getExceptionStackTrace(e)); - return new HttpReturn(false, 404, 0, ""); - } - } - - @Behavior("Delete") - public HttpReturn delete(@Parameter("url") String url, - @Parameter("content") String content) { - StringBuffer stringBuffer = null; - String requestMethod = "DELETE"; - try { - HttpURLConnection httpURLConnection = getRequestURLConnection(url, - requestMethod); - writeContentToConnectOutputSteam(content, httpURLConnection); - stringBuffer = readConnectionInputStream(httpURLConnection); - return new HttpReturn(true, httpURLConnection.getResponseCode(), - stringBuffer.length() * 2, - httpURLConnection.getContentType()); - } catch (MalformedURLException e) { - logger.info(DealWithLog.getExceptionStackTrace(e)); - return new HttpReturn(false, 400, 0, ""); - } catch (IOException e) { - logger.info(DealWithLog.getExceptionStackTrace(e)); - return new HttpReturn(false, 404, 0, ""); - } - } -} +package org.bench4q.agent.plugin.basic; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.OutputStreamWriter; +import java.net.HttpURLConnection; +import java.net.MalformedURLException; +import java.net.URL; +import java.util.Iterator; +import java.util.List; + +import org.apache.commons.httpclient.HttpClient; +import org.apache.commons.httpclient.HttpException; +import org.apache.commons.httpclient.HttpMethod; +import org.apache.commons.httpclient.methods.GetMethod; +import org.apache.log4j.Logger; +import org.bench4q.agent.plugin.Behavior; +import org.bench4q.agent.plugin.Parameter; +import org.bench4q.agent.plugin.Plugin; +import org.bench4q.agent.plugin.result.HttpReturn; +import org.bench4q.agent.scenario.utils.ParameterParser; +import org.bench4q.agent.share.DealWithLog; + +@Plugin("Http") +public class HttpPlugin { + private Logger logger = Logger.getLogger(HttpPlugin.class); + private HttpClient httpClient; + + private HttpClient getHttpClient() { + return httpClient; + } + + private void setHttpClient(HttpClient httpClient) { + this.httpClient = httpClient; + } + + public HttpPlugin() { + this.setHttpClient(new HttpClient()); + } + + @Behavior("Get") + public HttpReturn get(@Parameter("url") String url, + @Parameter("queryParams") String queryParams, + @Parameter("headers") String headers) { + GetMethod method = new GetMethod(url); + if (queryParams != null && queryParams.length() > 0) { + method.setQueryString(queryParams); + } + method.getParams().makeLenient(); + setHeaders(method, headers); + + int responseCode = -1; + long contentLength = 0; + String contentType = ""; + try { + responseCode = this.getHttpClient().executeMethod(method); + method.getStatusLine().toString(); + method.getResponseHeaders(); + contentLength = method.getResponseContentLength(); + if (method.getResponseHeader("Content-Type") != null) { + contentType = method.getResponseHeader("Content-Type") + .getValue(); + } + System.out.println(method.getResponseBodyAsString()); + return new HttpReturn(responseCode > 0, responseCode, + contentLength, contentType); + } catch (HttpException e) { + e.printStackTrace(); + return new HttpReturn(false, 400, contentLength, contentType); + } catch (IOException e) { + e.printStackTrace(); + return new HttpReturn(false, 400, contentLength, contentType); + } finally { + method.releaseConnection(); + } + } + + static void setHeaders(HttpMethod method, String headers) { + if (headers != null) { + List> values = ParameterParser.getTable(headers); + Iterator> headerIter = values.iterator(); + while (headerIter.hasNext()) { + Iterator entryIter = headerIter.next().iterator(); + String name = entryIter.next(); + method.addRequestHeader(name, entryIter.next()); + } + } + } + + private HttpURLConnection getRequestURLConnection(String url, String method) + throws MalformedURLException, IOException { + HttpURLConnection httpURLConnection; + URL target = new URL(url); + httpURLConnection = (HttpURLConnection) target.openConnection(); + if (method.equals("GET")) { + httpURLConnection.setDoOutput(false); + } else { + httpURLConnection.setDoOutput(true); + } + httpURLConnection.setDoOutput(true); + httpURLConnection.setDoInput(true); + httpURLConnection.setUseCaches(false); + httpURLConnection.setRequestMethod(method); + return httpURLConnection; + } + + private StringBuffer readConnectionInputStream( + HttpURLConnection httpURLConnection) throws IOException { + StringBuffer stringBuffer = new StringBuffer(); + BufferedReader bufferedReader = new BufferedReader( + new InputStreamReader(httpURLConnection.getInputStream())); + int temp = -1; + while ((temp = bufferedReader.read()) != -1) { + stringBuffer.append((char) temp); + } + bufferedReader.close(); + return stringBuffer; + } + + private void writeContentToConnectOutputSteam(String content, + HttpURLConnection httpURLConnection) throws IOException { + OutputStreamWriter outputStreamWriter = new OutputStreamWriter( + httpURLConnection.getOutputStream()); + outputStreamWriter.write(content); + outputStreamWriter.flush(); + outputStreamWriter.close(); + } + + @Behavior("Post") + public HttpReturn post(@Parameter("url") String url, + @Parameter("content") String content, + @Parameter("contentType") String contentType, + @Parameter("accept") String accept) { + HttpURLConnection httpURLConnection = null; + String requestMethod = "POST"; + StringBuffer stringBuffer = null; + try { + httpURLConnection = getRequestURLConnection(url, requestMethod); + httpURLConnection.setRequestMethod("POST"); + if (contentType != null && contentType.length() > 0) { + httpURLConnection.setRequestProperty("Content-Type", + contentType); + } + if (accept != null && accept.length() > 0) { + httpURLConnection.setRequestProperty("Accept", accept); + } + writeContentToConnectOutputSteam(content, httpURLConnection); + stringBuffer = readConnectionInputStream(httpURLConnection); + return new HttpReturn(true, httpURLConnection.getResponseCode(), + stringBuffer.length() * 2, + httpURLConnection.getContentType()); + } catch (MalformedURLException e) { + logger.info(DealWithLog.getExceptionStackTrace(e)); + return new HttpReturn(false, 400, 0, ""); + } catch (IOException e) { + logger.info(DealWithLog.getExceptionStackTrace(e)); + return new HttpReturn(false, 404, 0, ""); + } + + } + + @Behavior("Put") + public HttpReturn put(@Parameter("url") String url, + @Parameter("content") String content) { + StringBuffer stringBuffer = null; + String requestMethod = "PUT"; + try { + HttpURLConnection httpURLConnection = this.getRequestURLConnection( + url, requestMethod); + writeContentToConnectOutputSteam(content, httpURLConnection); + stringBuffer = readConnectionInputStream(httpURLConnection); + return new HttpReturn(true, httpURLConnection.getResponseCode(), + stringBuffer.length() * 2, + httpURLConnection.getContentType()); + } catch (MalformedURLException e) { + logger.info(DealWithLog.getExceptionStackTrace(e)); + return new HttpReturn(false, 400, 0, ""); + } catch (IOException e) { + logger.info(DealWithLog.getExceptionStackTrace(e)); + return new HttpReturn(false, 404, 0, ""); + } + } + + @Behavior("Delete") + public HttpReturn delete(@Parameter("url") String url, + @Parameter("content") String content) { + StringBuffer stringBuffer = null; + String requestMethod = "DELETE"; + try { + HttpURLConnection httpURLConnection = getRequestURLConnection(url, + requestMethod); + writeContentToConnectOutputSteam(content, httpURLConnection); + stringBuffer = readConnectionInputStream(httpURLConnection); + return new HttpReturn(true, httpURLConnection.getResponseCode(), + stringBuffer.length() * 2, + httpURLConnection.getContentType()); + } catch (MalformedURLException e) { + logger.info(DealWithLog.getExceptionStackTrace(e)); + return new HttpReturn(false, 400, 0, ""); + } catch (IOException e) { + logger.info(DealWithLog.getExceptionStackTrace(e)); + return new HttpReturn(false, 404, 0, ""); + } + } +} diff --git a/src/main/java/org/bench4q/agent/scenario/utils/ParameterParser.java b/src/main/java/org/bench4q/agent/scenario/utils/ParameterParser.java new file mode 100644 index 00000000..d42f4c4b --- /dev/null +++ b/src/main/java/org/bench4q/agent/scenario/utils/ParameterParser.java @@ -0,0 +1,219 @@ +/* + * CLIF is a Load Injection Framework + * Copyright (C) 2008, 2009 France Telecom R&D + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + * Contact: clif@ow2.org + */ + +package org.bench4q.agent.scenario.utils; + +import java.util.ArrayList; +import java.util.List; +import java.util.StringTokenizer; + +/** + * + * @author coderfengyun + * + */ +public abstract class ParameterParser { + static public List getNField(String value) { + List realTokens = getRealTokens(";", value); + for (int i = 0; i < realTokens.size(); ++i) { + realTokens.set(i, unescape(realTokens.get(i))); + } + return realTokens; + } + + static public String getRadioGroup(String value) { + List realTokens = getRealTokens(";", value); + if (realTokens.size() == 0) { + return ""; + } else { + return unescape(realTokens.get(0)); + } + } + + static public List getCheckBox(String value) { + return getNField(value); + } + + static public String getCombo(String value) { + return getRadioGroup(value); + } + + /** + * This method analyzes the value to be set in the table, and remove all + * escape characters + * + * @param value + * The value containing the serialization of all values of the + * table + * @return The vector containing all the entries, each entries is in a + * vector, which contains the string values + */ + static public List> getTable(String value) { + List> result = new ArrayList>(); + List tempEntries = getRealTokens(";", value); + // now analyze all entries values, and get the '|' separator + List> allValues = new ArrayList>(); + for (int i = 0; i < tempEntries.size(); i++) { + String tempEntry = tempEntries.get(i); + List values = getRealTokens("|", tempEntry); + allValues.add(values); + } + // now analyze all values, and get the '=' separator + for (int i = 0; i < allValues.size(); i++) { + List resultValues = new ArrayList(); + List tempValues = allValues.get(i); + for (int j = 0; j < tempValues.size(); j++) { + String v = tempValues.get(j); + List temp = getRealTokens("=", v); + String res; + if (temp.size() > 1) { + res = temp.get(1); + } else { + res = ""; + } + res = unescape(res); + resultValues.add(res); + } + result.add(resultValues); + } + return result; + } + + /** + * Get the number of escape character in the end of the string + * + * @param value + * The string to be analyzed + * @return 0 if no escape character was found, else the number + */ + static private int getNumberOfEscapeCharacter(String value) { + int result = 0; + if (value.length() > 0) { + int last = value.lastIndexOf("\\"); + if (last == value.length() - 1) { + result = 1 + getNumberOfEscapeCharacter(value + .substring(0, last)); + } + } + return result; + } + + /** + * Add escape separator before each separator + * + * @param separator + * The separator character + * @param value + * The value of the string to add the escape characters + * @return The string modified + */ + static public String addEscapeCharacter(String separator, String value) { + String result = ""; + StringTokenizer st = new StringTokenizer(value, separator, true); + while (st.hasMoreTokens()) { + String token = st.nextToken(); + if (token.equals(separator)) { + result = result.concat("\\" + token); + } else { + result = result.concat(token); + } + } + return result; + } + + /** + * Split the string value with the separator, and check if there is no + * escape character before the separator + * + * @param separator + * The separator + * @param value + * The string value to be split + * @return The vector containing each token + */ + static public List getRealTokens(String separator, String value) { + List result = new ArrayList(); + if (value != null) { + StringTokenizer st = new StringTokenizer(value, separator, true); + String currentRealToken = ""; + while (st.hasMoreTokens()) { + String token = st.nextToken(); + // the token is the separator + if (token.equals(separator)) { + int nb = getNumberOfEscapeCharacter(currentRealToken); + // if nb is even, we don't have any escape character + if (nb % 2 == 0) { + result.add(currentRealToken); + currentRealToken = ""; + } + // nb is odd + else { + // remove the escape character + currentRealToken = currentRealToken.substring(0, + currentRealToken.length() - 1); + // add the separator character + currentRealToken = currentRealToken.concat(separator); + // if it's the last token add it to the result + if (!st.hasMoreTokens()) { + result.add(currentRealToken); + } + } + } + // the token is a string + else { + currentRealToken = currentRealToken.concat(token); + // if it's the last token add it to the result + if (!st.hasMoreTokens()) { + result.add(currentRealToken); + } + } + } + } + return result; + } + + /** + * Replaces every escape sequences by the corresponding original character + * + * @param value + * the string where some characters are escaped by '\' character + * @return the unescaped string + */ + static public String unescape(String value) { + StringBuilder result = new StringBuilder(); + char c; + boolean escape = false; // escape sequence + for (int i = 0; i < value.length(); ++i) { + c = value.charAt(i); + if (escape) { + result.append(c); + escape = false; + } else { + if (c == '\\') { + escape = true; + } else { + result.append(c); + } + } + } + return result.toString(); + } +} diff --git a/src/test/java/org/bench4q/agent/test/TestWithScriptFile.java b/src/test/java/org/bench4q/agent/test/TestWithScriptFile.java index aebed98a..42ad48a2 100644 --- a/src/test/java/org/bench4q/agent/test/TestWithScriptFile.java +++ b/src/test/java/org/bench4q/agent/test/TestWithScriptFile.java @@ -1,189 +1,197 @@ -package org.bench4q.agent.test; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.IOException; -import java.util.UUID; - -import static org.junit.Assert.*; - -import javax.xml.bind.JAXBContext; -import javax.xml.bind.JAXBException; -import javax.xml.bind.Unmarshaller; - -import org.apache.commons.io.FileUtils; -import org.bench4q.share.helper.MarshalHelper; -import org.bench4q.share.models.agent.BehaviorBriefModel; -import org.bench4q.share.models.agent.RunScenarioModel; -import org.bench4q.share.models.agent.RunScenarioResultModel; -import org.bench4q.share.models.agent.statistics.AgentBriefStatusModel; -import org.bench4q.share.models.agent.statistics.AgentBehaviorsBriefModel; -import org.bench4q.share.models.agent.statistics.AgentPageBriefModel; -import org.junit.Test; - -import Communication.HttpRequester; -import Communication.HttpRequester.HttpResponse; - -public class TestWithScriptFile { - private HttpRequester httpRequester; - private String url = "http://localhost:6565/test"; - private String filePath; - private UUID testId; - private static int load = 10; - - public String getFilePath() { - return filePath; - } - - public void setFilePath(String filePath) { - this.filePath = filePath; - } - - public HttpRequester getHttpRequester() { - return httpRequester; - } - - public void setHttpRequester(HttpRequester httpRequester) { - this.httpRequester = httpRequester; - } - - public UUID getTestId() { - return testId; - } - - public void setTestId(UUID testId) { - this.testId = testId; - } - - public TestWithScriptFile() { - this.setFilePath("Scripts" + System.getProperty("file.separator") - + "goodForPage.xml"); - this.setHttpRequester(new HttpRequester()); - } - - public void startTest() throws JAXBException { - File file = new File(this.getFilePath()); - if (!file.exists()) { - System.out.println("this script not exists!"); - return; - } - String scriptContent; - try { - scriptContent = FileUtils.readFileToString(file); - RunScenarioModel runScenarioModel = extractRunScenarioModel(scriptContent); - if (runScenarioModel == null) { - System.out.println("can't execute an unvalid script"); - return; - } - assertTrue(runScenarioModel.getPages().size() > 0); - assertTrue(runScenarioModel.getPages().get(0).getBatches().get(0) - .getBehaviors().size() > 0); - runScenarioModel.setPoolSize(load); - - HttpResponse httpResponse = this.getHttpRequester().sendPostXml( - this.url + "/run", - marshalRunScenarioModel(runScenarioModel), null); - RunScenarioResultModel resultModel = (RunScenarioResultModel) MarshalHelper - .unmarshal(RunScenarioResultModel.class, - httpResponse.getContent()); - this.setTestId(resultModel.getRunId()); - } catch (IOException e) { - System.out.println("IO exception!"); - } - } - - private RunScenarioModel extractRunScenarioModel(String scriptContent) { - try { - Unmarshaller unmarshaller = JAXBContext.newInstance( - RunScenarioModel.class).createUnmarshaller(); - return (RunScenarioModel) unmarshaller - .unmarshal(new ByteArrayInputStream(scriptContent - .getBytes())); - } catch (JAXBException e) { - System.out.println("model unmarshal has an exception!"); - e.printStackTrace(); - return null; - } - - } - - private String marshalRunScenarioModel(RunScenarioModel model) - throws JAXBException { - ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); - JAXBContext.newInstance(RunScenarioModel.class).createMarshaller() - .marshal(model, outputStream); - return outputStream.toString(); - } - - private void stopTest() throws IOException { - System.out.println("Enter stopTest!"); - this.getHttpRequester().sendGet( - this.url + "/stop/" + this.getTestId().toString(), null, null); - } - - private void scenarioBrief() throws IOException, JAXBException { - System.out.println("Enter brief!"); - HttpResponse httpResponse = this.getHttpRequester().sendGet( - this.url + "/brief/" + this.getTestId().toString(), null, null); - AgentBriefStatusModel briefModel = (AgentBriefStatusModel) MarshalHelper - .unmarshal(AgentBriefStatusModel.class, - httpResponse.getContent()); - assertTrue(briefModel.getTimeFrame() > 0); - } - - private void behaviorsBrief() throws IOException, JAXBException { - System.out.println("Enter behaviorsBrief!"); - HttpResponse httpResponse = this.getHttpRequester().sendGet( - this.url + "/behaviorsBrief/" + this.getTestId().toString(), - null, null); - AgentBehaviorsBriefModel behaviorsBriefModel = (AgentBehaviorsBriefModel) MarshalHelper - .unmarshal(AgentBehaviorsBriefModel.class, - httpResponse.getContent()); - assertTrue(behaviorsBriefModel.getBehaviorBriefModels().size() > 0); - } - - private void behaviorBrief() throws IOException, JAXBException { - System.out.println("Enter behaviorBrief!"); - HttpResponse httpResponse = this.getHttpRequester().sendGet( - this.url + "/brief/" + this.getTestId().toString() + "/0", - null, null); - BehaviorBriefModel behaviorBriefModel = (BehaviorBriefModel) MarshalHelper - .unmarshal(BehaviorBriefModel.class, httpResponse.getContent()); - assertTrue(behaviorBriefModel.getDetailStatusCodeResultModels().size() > 0); - } - - @Test - public void integrateTest() throws JAXBException, InterruptedException, - IOException { - this.startTest(); - Thread.sleep(5000); - this.scenarioBrief(); - Thread.sleep(5000); - this.behaviorsBrief(); - Thread.sleep(5000); - this.behaviorBrief(); - Thread.sleep(5000); - this.pageBrief(0); - this.stopTest(); - } - - private void pageBrief(int i) throws IOException, JAXBException { - try { - HttpResponse httpResponse = this.getHttpRequester().sendGet( - url + "/pageBrief/" + this.getTestId() + "/" + i, null, - null); - if (httpResponse == null || httpResponse.getContent().isEmpty()) { - fail(); - } - System.out.println(httpResponse); - AgentPageBriefModel pageBriefModel = (AgentPageBriefModel) MarshalHelper - .unmarshal(AgentPageBriefModel.class, - httpResponse.getContent()); - assertTrue(pageBriefModel.getCountFromBegin() > 0); - } catch (Exception e) { - this.stopTest(); - } - - } -} +package org.bench4q.agent.test; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.IOException; +import java.util.UUID; + +import static org.junit.Assert.*; + +import javax.xml.bind.JAXBContext; +import javax.xml.bind.JAXBException; +import javax.xml.bind.Unmarshaller; + +import org.apache.commons.io.FileUtils; +import org.bench4q.share.helper.MarshalHelper; +import org.bench4q.share.models.agent.BehaviorBriefModel; +import org.bench4q.share.models.agent.RunScenarioModel; +import org.bench4q.share.models.agent.RunScenarioResultModel; +import org.bench4q.share.models.agent.statistics.AgentBriefStatusModel; +import org.bench4q.share.models.agent.statistics.AgentBehaviorsBriefModel; +import org.bench4q.share.models.agent.statistics.AgentPageBriefModel; +import org.junit.Test; + +import Communication.HttpRequester; +import Communication.HttpRequester.HttpResponse; + +public class TestWithScriptFile { + private HttpRequester httpRequester; + private String url = "http://agent1.jd-app.com/test"; + private String filePath; + private UUID testId; + private static int load = 10; + + public String getFilePath() { + return filePath; + } + + public void setFilePath(String filePath) { + this.filePath = filePath; + } + + public HttpRequester getHttpRequester() { + return httpRequester; + } + + public void setHttpRequester(HttpRequester httpRequester) { + this.httpRequester = httpRequester; + } + + public UUID getTestId() { + return testId; + } + + public void setTestId(UUID testId) { + this.testId = testId; + } + + public TestWithScriptFile() { + this.setFilePath("Scripts" + System.getProperty("file.separator") + + "testJD.xml"); + this.setHttpRequester(new HttpRequester()); + } + + public void startTest() throws JAXBException { + File file = new File(this.getFilePath()); + if (!file.exists()) { + System.out.println("this script not exists!"); + return; + } + String scriptContent; + try { + scriptContent = FileUtils.readFileToString(file); + RunScenarioModel runScenarioModel = extractRunScenarioModel(scriptContent); + if (runScenarioModel == null) { + System.out.println("can't execute an unvalid script"); + return; + } + assertTrue(runScenarioModel.getPages().size() > 0); + assertTrue(runScenarioModel.getPages().get(0).getBatches().get(0) + .getBehaviors().size() > 0); + runScenarioModel.setPoolSize(load); + + HttpResponse httpResponse = this.getHttpRequester().sendPostXml( + this.url + "/run", + marshalRunScenarioModel(runScenarioModel), null); + RunScenarioResultModel resultModel = (RunScenarioResultModel) MarshalHelper + .unmarshal(RunScenarioResultModel.class, + httpResponse.getContent()); + this.setTestId(resultModel.getRunId()); + } catch (IOException e) { + System.out.println("IO exception!"); + } + } + + private RunScenarioModel extractRunScenarioModel(String scriptContent) { + try { + Unmarshaller unmarshaller = JAXBContext.newInstance( + RunScenarioModel.class).createUnmarshaller(); + return (RunScenarioModel) unmarshaller + .unmarshal(new ByteArrayInputStream(scriptContent + .getBytes())); + } catch (JAXBException e) { + System.out.println("model unmarshal has an exception!"); + e.printStackTrace(); + return null; + } + + } + + private String marshalRunScenarioModel(RunScenarioModel model) + throws JAXBException { + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + JAXBContext.newInstance(RunScenarioModel.class).createMarshaller() + .marshal(model, outputStream); + return outputStream.toString(); + } + + private void stopTest() throws IOException { + System.out.println("Enter stopTest!"); + this.getHttpRequester().sendGet( + this.url + "/stop/" + this.getTestId().toString(), null, null); + } + + private void scenarioBrief() throws IOException, JAXBException { + System.out.println("Enter brief!"); + HttpResponse httpResponse = this.getHttpRequester().sendGet( + this.url + "/brief/" + this.getTestId().toString(), null, null); + System.out.println(httpResponse.getContent()); + AgentBriefStatusModel briefModel = (AgentBriefStatusModel) MarshalHelper + .unmarshal(AgentBriefStatusModel.class, + httpResponse.getContent()); + assertTrue(briefModel.getTimeFrame() > 0); + } + + private void behaviorsBrief() throws IOException, JAXBException { + System.out.println("Enter behaviorsBrief!"); + HttpResponse httpResponse = this.getHttpRequester().sendGet( + this.url + "/behaviorsBrief/" + this.getTestId().toString(), + null, null); + System.out.println(httpResponse.getContent()); + AgentBehaviorsBriefModel behaviorsBriefModel = (AgentBehaviorsBriefModel) MarshalHelper + .unmarshal(AgentBehaviorsBriefModel.class, + httpResponse.getContent()); + assertTrue(behaviorsBriefModel.getBehaviorBriefModels().size() > 0); + } + + private void behaviorBrief() throws IOException, JAXBException { + System.out.println("Enter behaviorBrief!"); + HttpResponse httpResponse = this.getHttpRequester().sendGet( + this.url + "/brief/" + this.getTestId().toString() + "/0", + null, null); + BehaviorBriefModel behaviorBriefModel = (BehaviorBriefModel) MarshalHelper + .unmarshal(BehaviorBriefModel.class, httpResponse.getContent()); + assertTrue(behaviorBriefModel.getDetailStatusCodeResultModels().size() > 0); + } + + @Test + public void integrateTest() throws JAXBException, InterruptedException, + IOException { + try { + this.startTest(); + Thread.sleep(5000); + this.scenarioBrief(); + Thread.sleep(5000); + this.behaviorsBrief(); + Thread.sleep(5000); + this.behaviorBrief(); + Thread.sleep(5000); + this.pageBrief(0); + } catch (Exception e) { + e.printStackTrace(); + } finally { + this.stopTest(); + } + + } + + private void pageBrief(int i) throws IOException, JAXBException { + try { + HttpResponse httpResponse = this.getHttpRequester().sendGet( + url + "/pageBrief/" + this.getTestId() + "/" + i, null, + null); + if (httpResponse == null || httpResponse.getContent().isEmpty()) { + fail(); + } + System.out.println(httpResponse); + AgentPageBriefModel pageBriefModel = (AgentPageBriefModel) MarshalHelper + .unmarshal(AgentPageBriefModel.class, + httpResponse.getContent()); + assertTrue(pageBriefModel.getCountFromBegin() > 0); + } catch (Exception e) { + this.stopTest(); + } + + } +} diff --git a/src/test/java/org/bench4q/agent/test/plugin/TestHttpPlugin.java b/src/test/java/org/bench4q/agent/test/plugin/TestHttpPlugin.java index cd233400..4954e3ca 100644 --- a/src/test/java/org/bench4q/agent/test/plugin/TestHttpPlugin.java +++ b/src/test/java/org/bench4q/agent/test/plugin/TestHttpPlugin.java @@ -1,32 +1,30 @@ -package org.bench4q.agent.test.plugin; - -import org.bench4q.agent.plugin.basic.HttpPlugin; -import org.bench4q.agent.plugin.result.PluginReturn; -import org.junit.Test; - -import static org.junit.Assert.*; - -public class TestHttpPlugin { - private HttpPlugin httpPlugin; - - private HttpPlugin getHttpPlugin() { - return httpPlugin; - } - - private void setHttpPlugin(HttpPlugin httpPlugin) { - this.httpPlugin = httpPlugin; - } - - public TestHttpPlugin() { - this.setHttpPlugin(new HttpPlugin()); - } - - @Test - public void testGet() { - PluginReturn return1 = this - .getHttpPlugin() - .get("http://www.baidu.com/su?wd=&cb=window.bdsug.sugPreRequest&sid=4382_1435_4261_4588&t=1387332769213"); - assertTrue(return1.isSuccess()); - } - -} +package org.bench4q.agent.test.plugin; + +import org.bench4q.agent.plugin.basic.HttpPlugin; +import org.bench4q.agent.plugin.result.PluginReturn; +import org.junit.Test; + +import static org.junit.Assert.*; + +public class TestHttpPlugin { + private HttpPlugin httpPlugin; + + private HttpPlugin getHttpPlugin() { + return httpPlugin; + } + + private void setHttpPlugin(HttpPlugin httpPlugin) { + this.httpPlugin = httpPlugin; + } + + public TestHttpPlugin() { + this.setHttpPlugin(new HttpPlugin()); + } + + @Test + public void testGet() { + PluginReturn return1 = this.getHttpPlugin().get( + "http://www.baidu.com/s", "wd=ok", ""); + assertTrue(return1.isSuccess()); + } +} From 77a02bd135a4b2bf0c23192a915ec9adb625b961 Mon Sep 17 00:00:00 2001 From: coderfengyun Date: Wed, 15 Jan 2014 19:22:50 +0800 Subject: [PATCH 147/196] remove the bug, and add a task --- Scripts/forGoodRecord.xml | 1 + Scripts/testJD.xml | 66 +++++ .../agent/plugin/basic/HttpPlugin.java | 243 +++++++++--------- .../agent/scenario/utils/ParameterParser.java | 13 +- .../agent/test/TestWithScriptFile.java | 6 +- .../agent/test/plugin/TestHttpPlugin.java | 18 ++ .../scenario/utils/Test_ParameterParser.java | 39 +++ 7 files changed, 253 insertions(+), 133 deletions(-) create mode 100644 Scripts/forGoodRecord.xml create mode 100644 Scripts/testJD.xml create mode 100644 src/test/java/org/bench4q/agent/test/scenario/utils/Test_ParameterParser.java diff --git a/Scripts/forGoodRecord.xml b/Scripts/forGoodRecord.xml new file mode 100644 index 00000000..b85501ce --- /dev/null +++ b/Scripts/forGoodRecord.xml @@ -0,0 +1 @@ +0Geturlhttp://133.133.12.2:8080/bench4q-web/homepage.jspqueryParamsheadersheader=Accept|value= text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8|;USERBEHAVIORhttp-10-10Sleeptime15TIMERBEHAVIORtimer-11-11Geturlhttp://133.133.12.2:8080/bench4q-web/index.jspqueryParamsheadersheader=Accept|value= text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8|;USERBEHAVIORhttp42-10Sleeptime133TIMERBEHAVIORtimer-13-12Geturlhttp://133.133.12.2:8080/bench4q-web/css/bootstrap-cerulean.cssqueryParamsheadersheader=Accept|value= text/css,*/*;q=0.1|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/index.jsp|;USERBEHAVIORhttp3Geturlhttp://133.133.12.2:8080/bench4q-web/script/login.jsqueryParamsheadersheader=Accept|value= */*|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/index.jsp|;USERBEHAVIORhttp4Geturlhttp://133.133.12.2:8080/bench4q-web/js/jquery-1.7.2.min.jsqueryParamsheadersheader=Accept|value= */*|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/index.jsp|;USERBEHAVIORhttp5Geturlhttp://133.133.12.2:8080/bench4q-web/js/jquery.i18n.properties-1.0.9.jsqueryParamsheadersheader=Accept|value= */*|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/index.jsp|;USERBEHAVIORhttp6Geturlhttp://133.133.12.2:8080/bench4q-web/css/charisma-app.cssqueryParamsheadersheader=Accept|value= text/css,*/*;q=0.1|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/index.jsp|;USERBEHAVIORhttp-1420Sleeptime1TIMERBEHAVIORtimer-15-10Sleeptime72TIMERBEHAVIORtimer-16-10Sleeptime24TIMERBEHAVIORtimer-17-10Sleeptime1TIMERBEHAVIORtimer-18-10Sleeptime211TIMERBEHAVIORtimer-19-17Geturlhttp://fonts.googleapis.com/cssqueryParamsfamily=Karla|Ubuntuheadersheader=Accept|value= text/css,*/*;q=0.1|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/index.jsp|;USERBEHAVIORhttp-110-10Sleeptime3TIMERBEHAVIORtimer-111-18Geturlhttp://fonts.googleapis.com/cssqueryParamsfamily=Shojumaruheadersheader=Accept|value= text/css,*/*;q=0.1|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/index.jsp|;USERBEHAVIORhttp-112-10Sleeptime82TIMERBEHAVIORtimer-113-19Geturlhttp://133.133.12.2:8080/bench4q-web/img/glyphicons-halflings.pngqueryParamsheadersheader=Accept|value= image/webp,*/*;q=0.8|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/index.jsp|;USERBEHAVIORhttp-114-10Sleeptime2TIMERBEHAVIORtimer-115-110Geturlhttp://133.133.12.2:8080/bench4q-web/i18n/i18n.propertiesqueryParams_=1389777175541headersheader=Content-Type|value=text/plain;charset=UTF-8|;header=Accept|value= text/plain, */*; q=0.01|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/index.jsp|;USERBEHAVIORhttp-116-10Sleeptime10TIMERBEHAVIORtimer-117-111Geturlhttp://133.133.12.2:8080/bench4q-web/i18n/i18n_zh.propertiesqueryParams_=1389777175572headersheader=Content-Type|value=text/plain;charset=UTF-8|;header=Accept|value= text/plain, */*; q=0.01|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/index.jsp|;USERBEHAVIORhttp-118-10Sleeptime8TIMERBEHAVIORtimer-119-112Geturlhttp://133.133.12.2:8080/bench4q-web/i18n/i18n_zh-CN.propertiesqueryParams_=1389777175587headersheader=Content-Type|value=text/plain;charset=UTF-8|;header=Accept|value= text/plain, */*; q=0.01|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/index.jsp|;USERBEHAVIORhttp-120-10Sleeptime52TIMERBEHAVIORtimer-121-113Geturlhttp://themes.googleusercontent.com/static/fonts/karla/v3/azR40LUJrT4HaWK28zHmVA.woffqueryParamsheadersheader=Accept|value= */*|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/index.jsp|;USERBEHAVIORhttp-122-10Sleeptime16442TIMERBEHAVIORtimer-123-114Geturlhttp://themes.googleusercontent.com/static/fonts/ubuntu/v5/_xyN3apAT_yRRDeqB3sPRg.woffqueryParamsheadersheader=Accept|value= */*|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/index.jsp|;USERBEHAVIORhttp-124-10Sleeptime9TIMERBEHAVIORtimer325-115Geturlhttp://133.133.12.2:8080/bench4q-web/homepage.jspqueryParamsheadersheader=Accept|value= text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/index.jsp|;USERBEHAVIORhttp-126-10Sleeptime25TIMERBEHAVIORtimer-127-116Geturlhttp://133.133.12.2:8080/bench4q-web/css/bootstrap-responsive.cssqueryParamsheadersheader=Accept|value= text/css,*/*;q=0.1|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/homepage.jsp|;USERBEHAVIORhttp17Geturlhttp://133.133.12.2:8080/bench4q-web/css/noty_theme_default.cssqueryParamsheadersheader=Accept|value= text/css,*/*;q=0.1|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/homepage.jsp|;USERBEHAVIORhttp18Geturlhttp://133.133.12.2:8080/bench4q-web/js/jquery-1.8.2.min.jsqueryParamsheadersheader=Accept|value= */*|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/homepage.jsp|;USERBEHAVIORhttp19Geturlhttp://133.133.12.2:8080/bench4q-web/bench4q-css/bench4q.cssqueryParamsheadersheader=Accept|value= text/css,*/*;q=0.1|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/homepage.jsp|;USERBEHAVIORhttp20Geturlhttp://133.133.12.2:8080/bench4q-web/css/jquery-ui-1.8.21.custom.cssqueryParamsheadersheader=Accept|value= text/css,*/*;q=0.1|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/homepage.jsp|;USERBEHAVIORhttp21Geturlhttp://133.133.12.2:8080/bench4q-web/css/opa-icons.cssqueryParamsheadersheader=Accept|value= text/css,*/*;q=0.1|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/homepage.jsp|;USERBEHAVIORhttp22Geturlhttp://133.133.12.2:8080/bench4q-web/css/colorbox.cssqueryParamsheadersheader=Accept|value= text/css,*/*;q=0.1|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/homepage.jsp|;USERBEHAVIORhttp23Geturlhttp://133.133.12.2:8080/bench4q-web/js/jquery.cookie.jsqueryParamsheadersheader=Accept|value= */*|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/homepage.jsp|;USERBEHAVIORhttp24Geturlhttp://133.133.12.2:8080/bench4q-web/js/jquery.dataTables.min.jsqueryParamsheadersheader=Accept|value= */*|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/homepage.jsp|;USERBEHAVIORhttp25Geturlhttp://133.133.12.2:8080/bench4q-web/js/theme.jsqueryParamsheadersheader=Accept|value= */*|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/homepage.jsp|;USERBEHAVIORhttp26Geturlhttp://133.133.12.2:8080/bench4q-web/script/base.jsqueryParamsheadersheader=Accept|value= */*|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/homepage.jsp|;USERBEHAVIORhttp27Geturlhttp://133.133.12.2:8080/bench4q-web/script/bench4q.table.jsqueryParamsheadersheader=Accept|value= */*|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/homepage.jsp|;USERBEHAVIORhttp28Geturlhttp://133.133.12.2:8080/bench4q-web/script/loadTestPlans.jsqueryParamsheadersheader=Accept|value= */*|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/homepage.jsp|;USERBEHAVIORhttp29Geturlhttp://133.133.12.2:8080/bench4q-web/script/scriptTable.jsqueryParamsheadersheader=Accept|value= */*|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/homepage.jsp|;USERBEHAVIORhttp30Geturlhttp://133.133.12.2:8080/bench4q-web/js/jquery-ui-1.8.21.custom.min.jsqueryParamsheadersheader=Accept|value= */*|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/homepage.jsp|;USERBEHAVIORhttp31Geturlhttp://133.133.12.2:8080/bench4q-web/img/bench4q.pngqueryParamsheadersheader=Accept|value= image/webp,*/*;q=0.8|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/homepage.jsp|;USERBEHAVIORhttp32Geturlhttp://133.133.12.2:8080/bench4q-web/js/bootstrap-dropdown.jsqueryParamsheadersheader=Accept|value= */*|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/homepage.jsp|;USERBEHAVIORhttp36Geturlhttp://133.133.12.2:8080/bench4q-web/script/home.jsqueryParamsheadersheader=Accept|value= */*|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/homepage.jsp|;USERBEHAVIORhttp-12800Sleeptime10TIMERBEHAVIORtimer-129-10Sleeptime25TIMERBEHAVIORtimer-130-10Sleeptime1TIMERBEHAVIORtimer-131-10Sleeptime4TIMERBEHAVIORtimer-132-10Sleeptime4TIMERBEHAVIORtimer-133-10Sleeptime0TIMERBEHAVIORtimer-134-10Sleeptime1TIMERBEHAVIORtimer-135-10Sleeptime6TIMERBEHAVIORtimer-136-10Sleeptime27TIMERBEHAVIORtimer-137-10Sleeptime9TIMERBEHAVIORtimer-138-10Sleeptime1TIMERBEHAVIORtimer-139-10Sleeptime0TIMERBEHAVIORtimer-140-10Sleeptime1TIMERBEHAVIORtimer-141-10Sleeptime36TIMERBEHAVIORtimer-142-10Sleeptime5TIMERBEHAVIORtimer-143-10Sleeptime1TIMERBEHAVIORtimer-144-10Sleeptime75TIMERBEHAVIORtimer-145-133Geturlhttp://133.133.12.2:8080/bench4q-web/img/opa-icons-blue32.pngqueryParamsheadersheader=Accept|value= image/webp,*/*;q=0.8|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/homepage.jsp|;USERBEHAVIORhttp-146-10Sleeptime30TIMERBEHAVIORtimer-147-134Geturlhttp://133.133.12.2:8080/bench4q-web/img/opa-icons-color32.pngqueryParamsheadersheader=Accept|value= image/webp,*/*;q=0.8|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/homepage.jsp|;USERBEHAVIORhttp-148-10Sleeptime27TIMERBEHAVIORtimer-149-135Geturlhttp://133.133.12.2:8080/bench4q-web/img/opa-icons-red32.pngqueryParamsheadersheader=Accept|value= image/webp,*/*;q=0.8|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/homepage.jsp|;USERBEHAVIORhttp-150-10Sleeptime1TIMERBEHAVIORtimer-151-10Sleeptime24TIMERBEHAVIORtimer-152-137Geturlhttp://themes.googleusercontent.com/static/fonts/shojumaru/v2/pYVcIM206l3F7GUKEvtB3T8E0i7KZn-EPnyo3HZu7kw.woffqueryParamsheadersheader=Accept|value= */*|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/index.jsp|;USERBEHAVIORhttp-153-10Sleeptime145TIMERBEHAVIORtimer-154-138Geturlhttp://133.133.12.2:8080/bench4q-web/img/opa-icons-green32.pngqueryParamsheadersheader=Accept|value= image/webp,*/*;q=0.8|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/homepage.jsp|;USERBEHAVIORhttp-155-10Sleeptime1TIMERBEHAVIORtimer-156-139Geturlhttp://133.133.12.2:8080/bench4q-web/i18n/i18n.propertiesqueryParams_=1389777196041headersheader=Content-Type|value=text/plain;charset=UTF-8|;header=Accept|value= text/plain, */*; q=0.01|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/homepage.jsp|;USERBEHAVIORhttp-157-10Sleeptime8TIMERBEHAVIORtimer-158-140Geturlhttp://133.133.12.2:8080/bench4q-web/i18n/i18n_zh.propertiesqueryParams_=1389777196134headersheader=Content-Type|value=text/plain;charset=UTF-8|;header=Accept|value= text/plain, */*; q=0.01|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/homepage.jsp|;USERBEHAVIORhttp-159-10Sleeptime7TIMERBEHAVIORtimer-160-141Geturlhttp://133.133.12.2:8080/bench4q-web/i18n/i18n_zh-CN.propertiesqueryParams_=1389777196150headersheader=Content-Type|value=text/plain;charset=UTF-8|;header=Accept|value= text/plain, */*; q=0.01|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/homepage.jsp|;USERBEHAVIORhttp-161-10Sleeptime163TIMERBEHAVIORtimer-162-142Posturlhttp://133.133.12.2:8080/bench4q-web/loadTestPlansqueryParamsheadersheader=Accept|value= application/json, text/javascript, */*; q=0.01|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/homepage.jsp|;bodyparametersUSERBEHAVIORhttp-163-10Sleeptime1TIMERBEHAVIORtimer-164-143Posturlhttp://133.133.12.2:8080/bench4q-web/loadScriptqueryParamsheadersheader=Accept|value= application/json, text/javascript, */*; q=0.01|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/homepage.jsp|;bodyparametersUSERBEHAVIORhttp-165-10Sleeptime27TIMERBEHAVIORtimer-166-144Geturlhttp://133.133.12.2:8080/bench4q-web/img/glyphicons-halflings-white.pngqueryParamsheadersheader=Accept|value= image/webp,*/*;q=0.8|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/homepage.jsp|;USERBEHAVIORhttp-167-10httpHttptimerConstantTimer \ No newline at end of file diff --git a/Scripts/testJD.xml b/Scripts/testJD.xml new file mode 100644 index 00000000..f8c2d673 --- /dev/null +++ b/Scripts/testJD.xml @@ -0,0 +1,66 @@ + + + + + + + + + 0 + Get + + + url + + http://www.baidu.com + + + + parameters + + + + USERBEHAVIOR + http + + + 2 + 0 + -1 + + + + + 0 + Sleep + + + time + 230 + + + TIMERBEHAVIOR + timer + + + -1 + 1 + -1 + + + + + 0 + + + http + Http + + + + timer + ConstantTimer + + + + \ No newline at end of file diff --git a/src/main/java/org/bench4q/agent/plugin/basic/HttpPlugin.java b/src/main/java/org/bench4q/agent/plugin/basic/HttpPlugin.java index 4be168ca..1c15398d 100644 --- a/src/main/java/org/bench4q/agent/plugin/basic/HttpPlugin.java +++ b/src/main/java/org/bench4q/agent/plugin/basic/HttpPlugin.java @@ -1,30 +1,30 @@ package org.bench4q.agent.plugin.basic; -import java.io.BufferedReader; import java.io.IOException; -import java.io.InputStreamReader; -import java.io.OutputStreamWriter; -import java.net.HttpURLConnection; -import java.net.MalformedURLException; -import java.net.URL; +import java.io.UnsupportedEncodingException; +import java.util.HashSet; import java.util.Iterator; import java.util.List; +import java.util.Set; +import org.apache.commons.httpclient.Header; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpException; import org.apache.commons.httpclient.HttpMethod; +import org.apache.commons.httpclient.NameValuePair; +import org.apache.commons.httpclient.methods.DeleteMethod; import org.apache.commons.httpclient.methods.GetMethod; -import org.apache.log4j.Logger; +import org.apache.commons.httpclient.methods.PostMethod; +import org.apache.commons.httpclient.methods.PutMethod; +import org.apache.commons.httpclient.methods.StringRequestEntity; import org.bench4q.agent.plugin.Behavior; import org.bench4q.agent.plugin.Parameter; import org.bench4q.agent.plugin.Plugin; import org.bench4q.agent.plugin.result.HttpReturn; import org.bench4q.agent.scenario.utils.ParameterParser; -import org.bench4q.agent.share.DealWithLog; @Plugin("Http") public class HttpPlugin { - private Logger logger = Logger.getLogger(HttpPlugin.class); private HttpClient httpClient; private HttpClient getHttpClient() { @@ -39,17 +39,53 @@ public class HttpPlugin { this.setHttpClient(new HttpClient()); } + static void setHeaders(HttpMethod method, String headers) { + if (headers != null) { + List> values = ParameterParser.getTable(headers); + Iterator> headerIter = values.iterator(); + while (headerIter.hasNext()) { + Iterator entryIter = headerIter.next().iterator(); + String name = entryIter.next(); + method.addRequestHeader(name, entryIter.next()); + } + } + } + + private static NameValuePair[] setInputParameters( + List inputParameters) { + Set res = new HashSet(); + Iterator paramIter = inputParameters.iterator(); + + while (paramIter.hasNext()) { + String token = paramIter.next(); + int index = token.indexOf('='); + res.add(new NameValuePair(token.substring(0, index), token + .substring(index + 1))); + } + return res.toArray(new NameValuePair[res.size()]); + } + + private static String completeUri(String uri) { + String scheme = uri.substring(0, 5); + if (!scheme.equals("http:") && !scheme.equals("https")) + uri = "http://" + uri; + return uri; + } + @Behavior("Get") public HttpReturn get(@Parameter("url") String url, @Parameter("queryParams") String queryParams, @Parameter("headers") String headers) { - GetMethod method = new GetMethod(url); - if (queryParams != null && queryParams.length() > 0) { + GetMethod method = new GetMethod(completeUri(url)); + if (isValidString(queryParams)) { method.setQueryString(queryParams); } - method.getParams().makeLenient(); setHeaders(method, headers); + method.getParams().makeLenient(); + return excuteMethod(method); + } + private HttpReturn excuteMethod(HttpMethod method) { int responseCode = -1; long contentLength = 0; String contentType = ""; @@ -57,7 +93,10 @@ public class HttpPlugin { responseCode = this.getHttpClient().executeMethod(method); method.getStatusLine().toString(); method.getResponseHeaders(); - contentLength = method.getResponseContentLength(); + if (method.getResponseHeader("Content-Length") != null) { + contentLength = Long.parseLong(method.getResponseHeader( + "Content-Length").getValue()); + } if (method.getResponseHeader("Content-Type") != null) { contentType = method.getResponseHeader("Content-Type") .getValue(); @@ -76,131 +115,85 @@ public class HttpPlugin { } } - static void setHeaders(HttpMethod method, String headers) { - if (headers != null) { - List> values = ParameterParser.getTable(headers); - Iterator> headerIter = values.iterator(); - while (headerIter.hasNext()) { - Iterator entryIter = headerIter.next().iterator(); - String name = entryIter.next(); - method.addRequestHeader(name, entryIter.next()); - } - } - } - - private HttpURLConnection getRequestURLConnection(String url, String method) - throws MalformedURLException, IOException { - HttpURLConnection httpURLConnection; - URL target = new URL(url); - httpURLConnection = (HttpURLConnection) target.openConnection(); - if (method.equals("GET")) { - httpURLConnection.setDoOutput(false); - } else { - httpURLConnection.setDoOutput(true); - } - httpURLConnection.setDoOutput(true); - httpURLConnection.setDoInput(true); - httpURLConnection.setUseCaches(false); - httpURLConnection.setRequestMethod(method); - return httpURLConnection; - } - - private StringBuffer readConnectionInputStream( - HttpURLConnection httpURLConnection) throws IOException { - StringBuffer stringBuffer = new StringBuffer(); - BufferedReader bufferedReader = new BufferedReader( - new InputStreamReader(httpURLConnection.getInputStream())); - int temp = -1; - while ((temp = bufferedReader.read()) != -1) { - stringBuffer.append((char) temp); - } - bufferedReader.close(); - return stringBuffer; - } - - private void writeContentToConnectOutputSteam(String content, - HttpURLConnection httpURLConnection) throws IOException { - OutputStreamWriter outputStreamWriter = new OutputStreamWriter( - httpURLConnection.getOutputStream()); - outputStreamWriter.write(content); - outputStreamWriter.flush(); - outputStreamWriter.close(); - } - @Behavior("Post") public HttpReturn post(@Parameter("url") String url, - @Parameter("content") String content, - @Parameter("contentType") String contentType, - @Parameter("accept") String accept) { - HttpURLConnection httpURLConnection = null; - String requestMethod = "POST"; - StringBuffer stringBuffer = null; - try { - httpURLConnection = getRequestURLConnection(url, requestMethod); - httpURLConnection.setRequestMethod("POST"); - if (contentType != null && contentType.length() > 0) { - httpURLConnection.setRequestProperty("Content-Type", - contentType); - } - if (accept != null && accept.length() > 0) { - httpURLConnection.setRequestProperty("Accept", accept); - } - writeContentToConnectOutputSteam(content, httpURLConnection); - stringBuffer = readConnectionInputStream(httpURLConnection); - return new HttpReturn(true, httpURLConnection.getResponseCode(), - stringBuffer.length() * 2, - httpURLConnection.getContentType()); - } catch (MalformedURLException e) { - logger.info(DealWithLog.getExceptionStackTrace(e)); - return new HttpReturn(false, 400, 0, ""); - } catch (IOException e) { - logger.info(DealWithLog.getExceptionStackTrace(e)); - return new HttpReturn(false, 404, 0, ""); + @Parameter("queryParams") String queryParams, + @Parameter("headers") String headers, + @Parameter("bodyContent") String bodyContent, + @Parameter("bodyparameters") String bodyParams) { + PostMethod method = new PostMethod(completeUri(url)); + setHeaders(method, headers); + if (isValidString(queryParams)) { + method.setQueryString(setInputParameters(ParameterParser + .getNField(queryParams))); } + if (isValidString(bodyParams)) { + method.setRequestBody(setInputParameters(ParameterParser + .getNField(bodyParams))); + } + String contentType = getMethodContentType(method); + if (isValidString(bodyContent) && isValidString(contentType)) { + try { + method.setRequestEntity(new StringRequestEntity(bodyContent, + contentType, null)); + } catch (Exception ex) { + ex.printStackTrace(); + } + } + method.getParams().makeLenient(); + return excuteMethod(method); + } + private String getMethodContentType(HttpMethod method) { + Header contentTypeHeader = method.getRequestHeader("Content-Type"); + String contentType = null; + if (contentTypeHeader != null + && !contentTypeHeader.toExternalForm().isEmpty()) { + contentType = contentTypeHeader.toExternalForm(); + } + return contentType; + } + + private boolean isValidString(String content) { + return content != null && content.length() != 0; } @Behavior("Put") public HttpReturn put(@Parameter("url") String url, - @Parameter("content") String content) { - StringBuffer stringBuffer = null; - String requestMethod = "PUT"; - try { - HttpURLConnection httpURLConnection = this.getRequestURLConnection( - url, requestMethod); - writeContentToConnectOutputSteam(content, httpURLConnection); - stringBuffer = readConnectionInputStream(httpURLConnection); - return new HttpReturn(true, httpURLConnection.getResponseCode(), - stringBuffer.length() * 2, - httpURLConnection.getContentType()); - } catch (MalformedURLException e) { - logger.info(DealWithLog.getExceptionStackTrace(e)); - return new HttpReturn(false, 400, 0, ""); - } catch (IOException e) { - logger.info(DealWithLog.getExceptionStackTrace(e)); - return new HttpReturn(false, 404, 0, ""); + @Parameter("queryParams") String queryParams, + @Parameter("headers") String headers, + @Parameter("bodyContent") String bodyContent, + @Parameter("bodyparameters") String bodyParams) { + PutMethod method = new PutMethod(completeUri(url)); + setHeaders(method, headers); + if (isValidString(queryParams)) { + method.setQueryString(setInputParameters(ParameterParser + .getNField(queryParams))); } + String contentType = getMethodContentType(method); + if (isValidString(bodyContent) && isValidString(contentType)) { + try { + method.setRequestEntity(new StringRequestEntity(bodyContent, + contentType, null)); + } catch (UnsupportedEncodingException e) { + e.printStackTrace(); + } + } + method.getParams().makeLenient(); + return excuteMethod(method); } @Behavior("Delete") public HttpReturn delete(@Parameter("url") String url, - @Parameter("content") String content) { - StringBuffer stringBuffer = null; - String requestMethod = "DELETE"; - try { - HttpURLConnection httpURLConnection = getRequestURLConnection(url, - requestMethod); - writeContentToConnectOutputSteam(content, httpURLConnection); - stringBuffer = readConnectionInputStream(httpURLConnection); - return new HttpReturn(true, httpURLConnection.getResponseCode(), - stringBuffer.length() * 2, - httpURLConnection.getContentType()); - } catch (MalformedURLException e) { - logger.info(DealWithLog.getExceptionStackTrace(e)); - return new HttpReturn(false, 400, 0, ""); - } catch (IOException e) { - logger.info(DealWithLog.getExceptionStackTrace(e)); - return new HttpReturn(false, 404, 0, ""); + @Parameter("queryParams") String queryParams, + @Parameter("headers") String headers) { + DeleteMethod method = new DeleteMethod(completeUri(url)); + setHeaders(method, headers); + if (isValidString(queryParams)) { + method.setQueryString(setInputParameters(ParameterParser + .getNField(queryParams))); } + method.getParams().makeLenient(); + return excuteMethod(method); } } diff --git a/src/main/java/org/bench4q/agent/scenario/utils/ParameterParser.java b/src/main/java/org/bench4q/agent/scenario/utils/ParameterParser.java index d42f4c4b..d492cdba 100644 --- a/src/main/java/org/bench4q/agent/scenario/utils/ParameterParser.java +++ b/src/main/java/org/bench4q/agent/scenario/utils/ParameterParser.java @@ -32,11 +32,13 @@ import java.util.StringTokenizer; */ public abstract class ParameterParser { static public List getNField(String value) { - List realTokens = getRealTokens(";", value); - for (int i = 0; i < realTokens.size(); ++i) { - realTokens.set(i, unescape(realTokens.get(i))); + StringTokenizer st = new StringTokenizer(value, ";", false); + List result = new ArrayList(); + while (st.hasMoreTokens()) { + String token = st.nextToken(); + result.add(token.trim()); } - return realTokens; + return result; } static public String getRadioGroup(String value) { @@ -68,7 +70,8 @@ public abstract class ParameterParser { */ static public List> getTable(String value) { List> result = new ArrayList>(); - List tempEntries = getRealTokens(";", value); + // TODO: read this carefully + List tempEntries = getRealTokens("|;", value); // now analyze all entries values, and get the '|' separator List> allValues = new ArrayList>(); for (int i = 0; i < tempEntries.size(); i++) { diff --git a/src/test/java/org/bench4q/agent/test/TestWithScriptFile.java b/src/test/java/org/bench4q/agent/test/TestWithScriptFile.java index 42ad48a2..9b97ea80 100644 --- a/src/test/java/org/bench4q/agent/test/TestWithScriptFile.java +++ b/src/test/java/org/bench4q/agent/test/TestWithScriptFile.java @@ -27,7 +27,7 @@ import Communication.HttpRequester.HttpResponse; public class TestWithScriptFile { private HttpRequester httpRequester; - private String url = "http://agent1.jd-app.com/test"; + private String url = "http://localhost:6565/test"; private String filePath; private UUID testId; private static int load = 10; @@ -58,7 +58,7 @@ public class TestWithScriptFile { public TestWithScriptFile() { this.setFilePath("Scripts" + System.getProperty("file.separator") - + "testJD.xml"); + + "forGoodRecord.xml"); this.setHttpRequester(new HttpRequester()); } @@ -171,7 +171,7 @@ public class TestWithScriptFile { } catch (Exception e) { e.printStackTrace(); } finally { - this.stopTest(); + // this.stopTest(); } } diff --git a/src/test/java/org/bench4q/agent/test/plugin/TestHttpPlugin.java b/src/test/java/org/bench4q/agent/test/plugin/TestHttpPlugin.java index 4954e3ca..5850cd9b 100644 --- a/src/test/java/org/bench4q/agent/test/plugin/TestHttpPlugin.java +++ b/src/test/java/org/bench4q/agent/test/plugin/TestHttpPlugin.java @@ -27,4 +27,22 @@ public class TestHttpPlugin { "http://www.baidu.com/s", "wd=ok", ""); assertTrue(return1.isSuccess()); } + + @Test + public void testPost() { + PluginReturn result = this.getHttpPlugin().post( + "http://133.133.12.2:8080/bench4q-web/login", + "userName=admin;password=admin", null, null, null); + assertTrue(result.isSuccess()); + } + + @Test + public void testGetWithActualBehavior() { + PluginReturn result = this + .getHttpPlugin() + .get("http://133.133.12.2:8080/bench4q-web/index.jsp", + "", + "header=Accept|value=text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8|"); + assertTrue(result.isSuccess()); + } } diff --git a/src/test/java/org/bench4q/agent/test/scenario/utils/Test_ParameterParser.java b/src/test/java/org/bench4q/agent/test/scenario/utils/Test_ParameterParser.java new file mode 100644 index 00000000..fe8a69d0 --- /dev/null +++ b/src/test/java/org/bench4q/agent/test/scenario/utils/Test_ParameterParser.java @@ -0,0 +1,39 @@ +package org.bench4q.agent.test.scenario.utils; + +import static org.junit.Assert.*; + +import java.util.ArrayList; +import java.util.List; + +import org.bench4q.agent.scenario.utils.ParameterParser; +import org.junit.Test; + +public class Test_ParameterParser { + private String testcase = " _nacc=yeah ;_nvid=525d29a534e918cbf04ea7159706a93d;_nvtm=0;_nvsf=0;_nvfi=1;_nlag=zh-cn;_nlmf=1389570024;_nres=1440x900;_nscd=32-bit;_nstm=0;"; + + private List expectedNFField = new ArrayList() { + private static final long serialVersionUID = 1L; + { + add("_nacc=yeah"); + add("_nvid=525d29a534e918cbf04ea7159706a93d"); + add("_nvtm=0"); + add("_nvsf=0"); + add("_nvfi=1"); + add("_nlag=zh-cn"); + add("_nlmf=1389570024"); + add("_nres=1440x900"); + add("_nscd=32-bit"); + add("_nstm=0"); + } + }; + + @Test + public void testParseParam() { + List result = ParameterParser.getNField(testcase); + assertEquals(10, result.size()); + for (int i = 0; i < result.size(); i++) { + assertEquals(result.get(i), expectedNFField.get(i)); + System.out.println(result.get(i)); + } + } +} From 4e2a83755259f0d1759e24146231627cec7639ed Mon Sep 17 00:00:00 2001 From: coderfengyun Date: Tue, 18 Feb 2014 15:09:28 +0800 Subject: [PATCH 148/196] remove that sysout --- src/main/java/org/bench4q/agent/plugin/basic/HttpPlugin.java | 1 - 1 file changed, 1 deletion(-) diff --git a/src/main/java/org/bench4q/agent/plugin/basic/HttpPlugin.java b/src/main/java/org/bench4q/agent/plugin/basic/HttpPlugin.java index 1c15398d..29e9b554 100644 --- a/src/main/java/org/bench4q/agent/plugin/basic/HttpPlugin.java +++ b/src/main/java/org/bench4q/agent/plugin/basic/HttpPlugin.java @@ -101,7 +101,6 @@ public class HttpPlugin { contentType = method.getResponseHeader("Content-Type") .getValue(); } - System.out.println(method.getResponseBodyAsString()); return new HttpReturn(responseCode > 0, responseCode, contentLength, contentType); } catch (HttpException e) { From cd810c1ea201939ed1dfda5fd98df23a204c9a0e Mon Sep 17 00:00:00 2001 From: coderfengyun Date: Tue, 4 Mar 2014 13:47:31 +0800 Subject: [PATCH 149/196] add new test about httpPlugin --- Scripts/forGoodRecord.xml | 2077 ++++++++++++++++- pom.xml | 212 +- .../agent/plugin/basic/HttpPlugin.java | 4 +- .../agent/plugin/result/HttpReturn.java | 107 +- .../agent/test/plugin/TestHttpPlugin.java | 28 + 5 files changed, 2274 insertions(+), 154 deletions(-) diff --git a/Scripts/forGoodRecord.xml b/Scripts/forGoodRecord.xml index b85501ce..aeb6083b 100644 --- a/Scripts/forGoodRecord.xml +++ b/Scripts/forGoodRecord.xml @@ -1 +1,2076 @@ -0Geturlhttp://133.133.12.2:8080/bench4q-web/homepage.jspqueryParamsheadersheader=Accept|value= text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8|;USERBEHAVIORhttp-10-10Sleeptime15TIMERBEHAVIORtimer-11-11Geturlhttp://133.133.12.2:8080/bench4q-web/index.jspqueryParamsheadersheader=Accept|value= text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8|;USERBEHAVIORhttp42-10Sleeptime133TIMERBEHAVIORtimer-13-12Geturlhttp://133.133.12.2:8080/bench4q-web/css/bootstrap-cerulean.cssqueryParamsheadersheader=Accept|value= text/css,*/*;q=0.1|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/index.jsp|;USERBEHAVIORhttp3Geturlhttp://133.133.12.2:8080/bench4q-web/script/login.jsqueryParamsheadersheader=Accept|value= */*|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/index.jsp|;USERBEHAVIORhttp4Geturlhttp://133.133.12.2:8080/bench4q-web/js/jquery-1.7.2.min.jsqueryParamsheadersheader=Accept|value= */*|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/index.jsp|;USERBEHAVIORhttp5Geturlhttp://133.133.12.2:8080/bench4q-web/js/jquery.i18n.properties-1.0.9.jsqueryParamsheadersheader=Accept|value= */*|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/index.jsp|;USERBEHAVIORhttp6Geturlhttp://133.133.12.2:8080/bench4q-web/css/charisma-app.cssqueryParamsheadersheader=Accept|value= text/css,*/*;q=0.1|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/index.jsp|;USERBEHAVIORhttp-1420Sleeptime1TIMERBEHAVIORtimer-15-10Sleeptime72TIMERBEHAVIORtimer-16-10Sleeptime24TIMERBEHAVIORtimer-17-10Sleeptime1TIMERBEHAVIORtimer-18-10Sleeptime211TIMERBEHAVIORtimer-19-17Geturlhttp://fonts.googleapis.com/cssqueryParamsfamily=Karla|Ubuntuheadersheader=Accept|value= text/css,*/*;q=0.1|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/index.jsp|;USERBEHAVIORhttp-110-10Sleeptime3TIMERBEHAVIORtimer-111-18Geturlhttp://fonts.googleapis.com/cssqueryParamsfamily=Shojumaruheadersheader=Accept|value= text/css,*/*;q=0.1|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/index.jsp|;USERBEHAVIORhttp-112-10Sleeptime82TIMERBEHAVIORtimer-113-19Geturlhttp://133.133.12.2:8080/bench4q-web/img/glyphicons-halflings.pngqueryParamsheadersheader=Accept|value= image/webp,*/*;q=0.8|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/index.jsp|;USERBEHAVIORhttp-114-10Sleeptime2TIMERBEHAVIORtimer-115-110Geturlhttp://133.133.12.2:8080/bench4q-web/i18n/i18n.propertiesqueryParams_=1389777175541headersheader=Content-Type|value=text/plain;charset=UTF-8|;header=Accept|value= text/plain, */*; q=0.01|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/index.jsp|;USERBEHAVIORhttp-116-10Sleeptime10TIMERBEHAVIORtimer-117-111Geturlhttp://133.133.12.2:8080/bench4q-web/i18n/i18n_zh.propertiesqueryParams_=1389777175572headersheader=Content-Type|value=text/plain;charset=UTF-8|;header=Accept|value= text/plain, */*; q=0.01|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/index.jsp|;USERBEHAVIORhttp-118-10Sleeptime8TIMERBEHAVIORtimer-119-112Geturlhttp://133.133.12.2:8080/bench4q-web/i18n/i18n_zh-CN.propertiesqueryParams_=1389777175587headersheader=Content-Type|value=text/plain;charset=UTF-8|;header=Accept|value= text/plain, */*; q=0.01|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/index.jsp|;USERBEHAVIORhttp-120-10Sleeptime52TIMERBEHAVIORtimer-121-113Geturlhttp://themes.googleusercontent.com/static/fonts/karla/v3/azR40LUJrT4HaWK28zHmVA.woffqueryParamsheadersheader=Accept|value= */*|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/index.jsp|;USERBEHAVIORhttp-122-10Sleeptime16442TIMERBEHAVIORtimer-123-114Geturlhttp://themes.googleusercontent.com/static/fonts/ubuntu/v5/_xyN3apAT_yRRDeqB3sPRg.woffqueryParamsheadersheader=Accept|value= */*|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/index.jsp|;USERBEHAVIORhttp-124-10Sleeptime9TIMERBEHAVIORtimer325-115Geturlhttp://133.133.12.2:8080/bench4q-web/homepage.jspqueryParamsheadersheader=Accept|value= text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/index.jsp|;USERBEHAVIORhttp-126-10Sleeptime25TIMERBEHAVIORtimer-127-116Geturlhttp://133.133.12.2:8080/bench4q-web/css/bootstrap-responsive.cssqueryParamsheadersheader=Accept|value= text/css,*/*;q=0.1|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/homepage.jsp|;USERBEHAVIORhttp17Geturlhttp://133.133.12.2:8080/bench4q-web/css/noty_theme_default.cssqueryParamsheadersheader=Accept|value= text/css,*/*;q=0.1|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/homepage.jsp|;USERBEHAVIORhttp18Geturlhttp://133.133.12.2:8080/bench4q-web/js/jquery-1.8.2.min.jsqueryParamsheadersheader=Accept|value= */*|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/homepage.jsp|;USERBEHAVIORhttp19Geturlhttp://133.133.12.2:8080/bench4q-web/bench4q-css/bench4q.cssqueryParamsheadersheader=Accept|value= text/css,*/*;q=0.1|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/homepage.jsp|;USERBEHAVIORhttp20Geturlhttp://133.133.12.2:8080/bench4q-web/css/jquery-ui-1.8.21.custom.cssqueryParamsheadersheader=Accept|value= text/css,*/*;q=0.1|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/homepage.jsp|;USERBEHAVIORhttp21Geturlhttp://133.133.12.2:8080/bench4q-web/css/opa-icons.cssqueryParamsheadersheader=Accept|value= text/css,*/*;q=0.1|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/homepage.jsp|;USERBEHAVIORhttp22Geturlhttp://133.133.12.2:8080/bench4q-web/css/colorbox.cssqueryParamsheadersheader=Accept|value= text/css,*/*;q=0.1|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/homepage.jsp|;USERBEHAVIORhttp23Geturlhttp://133.133.12.2:8080/bench4q-web/js/jquery.cookie.jsqueryParamsheadersheader=Accept|value= */*|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/homepage.jsp|;USERBEHAVIORhttp24Geturlhttp://133.133.12.2:8080/bench4q-web/js/jquery.dataTables.min.jsqueryParamsheadersheader=Accept|value= */*|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/homepage.jsp|;USERBEHAVIORhttp25Geturlhttp://133.133.12.2:8080/bench4q-web/js/theme.jsqueryParamsheadersheader=Accept|value= */*|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/homepage.jsp|;USERBEHAVIORhttp26Geturlhttp://133.133.12.2:8080/bench4q-web/script/base.jsqueryParamsheadersheader=Accept|value= */*|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/homepage.jsp|;USERBEHAVIORhttp27Geturlhttp://133.133.12.2:8080/bench4q-web/script/bench4q.table.jsqueryParamsheadersheader=Accept|value= */*|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/homepage.jsp|;USERBEHAVIORhttp28Geturlhttp://133.133.12.2:8080/bench4q-web/script/loadTestPlans.jsqueryParamsheadersheader=Accept|value= */*|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/homepage.jsp|;USERBEHAVIORhttp29Geturlhttp://133.133.12.2:8080/bench4q-web/script/scriptTable.jsqueryParamsheadersheader=Accept|value= */*|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/homepage.jsp|;USERBEHAVIORhttp30Geturlhttp://133.133.12.2:8080/bench4q-web/js/jquery-ui-1.8.21.custom.min.jsqueryParamsheadersheader=Accept|value= */*|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/homepage.jsp|;USERBEHAVIORhttp31Geturlhttp://133.133.12.2:8080/bench4q-web/img/bench4q.pngqueryParamsheadersheader=Accept|value= image/webp,*/*;q=0.8|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/homepage.jsp|;USERBEHAVIORhttp32Geturlhttp://133.133.12.2:8080/bench4q-web/js/bootstrap-dropdown.jsqueryParamsheadersheader=Accept|value= */*|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/homepage.jsp|;USERBEHAVIORhttp36Geturlhttp://133.133.12.2:8080/bench4q-web/script/home.jsqueryParamsheadersheader=Accept|value= */*|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/homepage.jsp|;USERBEHAVIORhttp-12800Sleeptime10TIMERBEHAVIORtimer-129-10Sleeptime25TIMERBEHAVIORtimer-130-10Sleeptime1TIMERBEHAVIORtimer-131-10Sleeptime4TIMERBEHAVIORtimer-132-10Sleeptime4TIMERBEHAVIORtimer-133-10Sleeptime0TIMERBEHAVIORtimer-134-10Sleeptime1TIMERBEHAVIORtimer-135-10Sleeptime6TIMERBEHAVIORtimer-136-10Sleeptime27TIMERBEHAVIORtimer-137-10Sleeptime9TIMERBEHAVIORtimer-138-10Sleeptime1TIMERBEHAVIORtimer-139-10Sleeptime0TIMERBEHAVIORtimer-140-10Sleeptime1TIMERBEHAVIORtimer-141-10Sleeptime36TIMERBEHAVIORtimer-142-10Sleeptime5TIMERBEHAVIORtimer-143-10Sleeptime1TIMERBEHAVIORtimer-144-10Sleeptime75TIMERBEHAVIORtimer-145-133Geturlhttp://133.133.12.2:8080/bench4q-web/img/opa-icons-blue32.pngqueryParamsheadersheader=Accept|value= image/webp,*/*;q=0.8|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/homepage.jsp|;USERBEHAVIORhttp-146-10Sleeptime30TIMERBEHAVIORtimer-147-134Geturlhttp://133.133.12.2:8080/bench4q-web/img/opa-icons-color32.pngqueryParamsheadersheader=Accept|value= image/webp,*/*;q=0.8|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/homepage.jsp|;USERBEHAVIORhttp-148-10Sleeptime27TIMERBEHAVIORtimer-149-135Geturlhttp://133.133.12.2:8080/bench4q-web/img/opa-icons-red32.pngqueryParamsheadersheader=Accept|value= image/webp,*/*;q=0.8|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/homepage.jsp|;USERBEHAVIORhttp-150-10Sleeptime1TIMERBEHAVIORtimer-151-10Sleeptime24TIMERBEHAVIORtimer-152-137Geturlhttp://themes.googleusercontent.com/static/fonts/shojumaru/v2/pYVcIM206l3F7GUKEvtB3T8E0i7KZn-EPnyo3HZu7kw.woffqueryParamsheadersheader=Accept|value= */*|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/index.jsp|;USERBEHAVIORhttp-153-10Sleeptime145TIMERBEHAVIORtimer-154-138Geturlhttp://133.133.12.2:8080/bench4q-web/img/opa-icons-green32.pngqueryParamsheadersheader=Accept|value= image/webp,*/*;q=0.8|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/homepage.jsp|;USERBEHAVIORhttp-155-10Sleeptime1TIMERBEHAVIORtimer-156-139Geturlhttp://133.133.12.2:8080/bench4q-web/i18n/i18n.propertiesqueryParams_=1389777196041headersheader=Content-Type|value=text/plain;charset=UTF-8|;header=Accept|value= text/plain, */*; q=0.01|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/homepage.jsp|;USERBEHAVIORhttp-157-10Sleeptime8TIMERBEHAVIORtimer-158-140Geturlhttp://133.133.12.2:8080/bench4q-web/i18n/i18n_zh.propertiesqueryParams_=1389777196134headersheader=Content-Type|value=text/plain;charset=UTF-8|;header=Accept|value= text/plain, */*; q=0.01|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/homepage.jsp|;USERBEHAVIORhttp-159-10Sleeptime7TIMERBEHAVIORtimer-160-141Geturlhttp://133.133.12.2:8080/bench4q-web/i18n/i18n_zh-CN.propertiesqueryParams_=1389777196150headersheader=Content-Type|value=text/plain;charset=UTF-8|;header=Accept|value= text/plain, */*; q=0.01|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/homepage.jsp|;USERBEHAVIORhttp-161-10Sleeptime163TIMERBEHAVIORtimer-162-142Posturlhttp://133.133.12.2:8080/bench4q-web/loadTestPlansqueryParamsheadersheader=Accept|value= application/json, text/javascript, */*; q=0.01|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/homepage.jsp|;bodyparametersUSERBEHAVIORhttp-163-10Sleeptime1TIMERBEHAVIORtimer-164-143Posturlhttp://133.133.12.2:8080/bench4q-web/loadScriptqueryParamsheadersheader=Accept|value= application/json, text/javascript, */*; q=0.01|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/homepage.jsp|;bodyparametersUSERBEHAVIORhttp-165-10Sleeptime27TIMERBEHAVIORtimer-166-144Geturlhttp://133.133.12.2:8080/bench4q-web/img/glyphicons-halflings-white.pngqueryParamsheadersheader=Accept|value= image/webp,*/*;q=0.8|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/homepage.jsp|;USERBEHAVIORhttp-167-10httpHttptimerConstantTimer \ No newline at end of file + + + + + + + + + 0 + Get + + + url + http://133.133.12.2:8080/bench4q-web/homepage.jsp + + + + queryParams + + + + headers + header=Accept|value= + text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8|; + + + + USERBEHAVIOR + http + + + -1 + 0 + -1 + + + + + 0 + Sleep + + + time + 15 + + + TIMERBEHAVIOR + timer + + + -1 + 1 + -1 + + + + + 1 + Get + + + url + http://133.133.12.2:8080/bench4q-web/index.jsp + + + queryParams + + + + headers + header=Accept|value= + text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8|; + + + + USERBEHAVIOR + http + + + 4 + 2 + -1 + + + + + 0 + Sleep + + + time + 133 + + + TIMERBEHAVIOR + timer + + + -1 + 3 + -1 + + + + + 2 + Get + + + url + http://133.133.12.2:8080/bench4q-web/css/bootstrap-cerulean.css + + + + queryParams + + + + headers + header=Accept|value= + text/css,*/*;q=0.1|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/index.jsp|; + + + + USERBEHAVIOR + http + + + 3 + Get + + + url + http://133.133.12.2:8080/bench4q-web/script/login.js + + + + queryParams + + + + headers + header=Accept|value= + */*|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/index.jsp|; + + + + USERBEHAVIOR + http + + + 4 + Get + + + url + http://133.133.12.2:8080/bench4q-web/js/jquery-1.7.2.min.js + + + + queryParams + + + + headers + header=Accept|value= + */*|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/index.jsp|; + + + + USERBEHAVIOR + http + + + 5 + Get + + + url + http://133.133.12.2:8080/bench4q-web/js/jquery.i18n.properties-1.0.9.js + + + + queryParams + + + + headers + header=Accept|value= + */*|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/index.jsp|; + + + + USERBEHAVIOR + http + + + 6 + Get + + + url + http://133.133.12.2:8080/bench4q-web/css/charisma-app.css + + + + queryParams + + + + headers + header=Accept|value= + text/css,*/*;q=0.1|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/index.jsp|; + + + + USERBEHAVIOR + http + + + -1 + 4 + 2 + + + + + 0 + Sleep + + + time + 1 + + + TIMERBEHAVIOR + timer + + + -1 + 5 + -1 + + + + + 0 + Sleep + + + time + 72 + + + TIMERBEHAVIOR + timer + + + -1 + 6 + -1 + + + + + 0 + Sleep + + + time + 24 + + + TIMERBEHAVIOR + timer + + + -1 + 7 + -1 + + + + + 0 + Sleep + + + time + 1 + + + TIMERBEHAVIOR + timer + + + -1 + 8 + -1 + + + + + 0 + Sleep + + + time + 211 + + + TIMERBEHAVIOR + timer + + + -1 + 9 + -1 + + + + + 7 + Get + + + url + http://fonts.googleapis.com/css + + + queryParams + family=Karla|Ubuntu + + + headers + header=Accept|value= + text/css,*/*;q=0.1|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/index.jsp|; + + + + USERBEHAVIOR + http + + + -1 + 10 + -1 + + + + + 0 + Sleep + + + time + 3 + + + TIMERBEHAVIOR + timer + + + -1 + 11 + -1 + + + + + 8 + Get + + + url + http://fonts.googleapis.com/css + + + queryParams + family=Shojumaru + + + headers + header=Accept|value= + text/css,*/*;q=0.1|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/index.jsp|; + + + + USERBEHAVIOR + http + + + -1 + 12 + -1 + + + + + 0 + Sleep + + + time + 82 + + + TIMERBEHAVIOR + timer + + + -1 + 13 + -1 + + + + + 9 + Get + + + url + http://133.133.12.2:8080/bench4q-web/img/glyphicons-halflings.png + + + + queryParams + + + + headers + header=Accept|value= + image/webp,*/*;q=0.8|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/index.jsp|; + + + + USERBEHAVIOR + http + + + -1 + 14 + -1 + + + + + 0 + Sleep + + + time + 2 + + + TIMERBEHAVIOR + timer + + + -1 + 15 + -1 + + + + + 10 + Get + + + url + http://133.133.12.2:8080/bench4q-web/i18n/i18n.properties + + + + queryParams + _=1389777175541 + + + headers + header=Content-Type|value=text/plain;charset=UTF-8|;header=Accept|value= + text/plain, */*; + q=0.01|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/index.jsp|; + + + + USERBEHAVIOR + http + + + -1 + 16 + -1 + + + + + 0 + Sleep + + + time + 10 + + + TIMERBEHAVIOR + timer + + + -1 + 17 + -1 + + + + + 11 + Get + + + url + http://133.133.12.2:8080/bench4q-web/i18n/i18n_zh.properties + + + + queryParams + _=1389777175572 + + + headers + header=Content-Type|value=text/plain;charset=UTF-8|;header=Accept|value= + text/plain, */*; + q=0.01|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/index.jsp|; + + + + USERBEHAVIOR + http + + + -1 + 18 + -1 + + + + + 0 + Sleep + + + time + 8 + + + TIMERBEHAVIOR + timer + + + -1 + 19 + -1 + + + + + 12 + Get + + + url + http://133.133.12.2:8080/bench4q-web/i18n/i18n_zh-CN.properties + + + + queryParams + _=1389777175587 + + + headers + header=Content-Type|value=text/plain;charset=UTF-8|;header=Accept|value= + text/plain, */*; + q=0.01|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/index.jsp|; + + + + USERBEHAVIOR + http + + + -1 + 20 + -1 + + + + + 0 + Sleep + + + time + 52 + + + TIMERBEHAVIOR + timer + + + -1 + 21 + -1 + + + + + 13 + Get + + + url + http://themes.googleusercontent.com/static/fonts/karla/v3/azR40LUJrT4HaWK28zHmVA.woff + + + + queryParams + + + + headers + header=Accept|value= + */*|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/index.jsp|; + + + + USERBEHAVIOR + http + + + -1 + 22 + -1 + + + + + 0 + Sleep + + + time + 16442 + + + TIMERBEHAVIOR + timer + + + -1 + 23 + -1 + + + + + 14 + Get + + + url + http://themes.googleusercontent.com/static/fonts/ubuntu/v5/_xyN3apAT_yRRDeqB3sPRg.woff + + + + queryParams + + + + headers + header=Accept|value= + */*|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/index.jsp|; + + + + USERBEHAVIOR + http + + + -1 + 24 + -1 + + + + + + + + + 0 + Sleep + + + time + 9 + + + TIMERBEHAVIOR + timer + + + 3 + 25 + -1 + + + + + 15 + Get + + + url + http://133.133.12.2:8080/bench4q-web/homepage.jsp + + + + queryParams + + + + headers + header=Accept|value= + text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/index.jsp|; + + + + USERBEHAVIOR + http + + + -1 + 26 + -1 + + + + + 0 + Sleep + + + time + 25 + + + TIMERBEHAVIOR + timer + + + -1 + 27 + -1 + + + + + 16 + Get + + + url + http://133.133.12.2:8080/bench4q-web/css/bootstrap-responsive.css + + + + queryParams + + + + headers + header=Accept|value= + text/css,*/*;q=0.1|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/homepage.jsp|; + + + + USERBEHAVIOR + http + + + 17 + Get + + + url + http://133.133.12.2:8080/bench4q-web/css/noty_theme_default.css + + + + queryParams + + + + headers + header=Accept|value= + text/css,*/*;q=0.1|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/homepage.jsp|; + + + + USERBEHAVIOR + http + + + 18 + Get + + + url + http://133.133.12.2:8080/bench4q-web/js/jquery-1.8.2.min.js + + + + queryParams + + + + headers + header=Accept|value= + */*|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/homepage.jsp|; + + + + USERBEHAVIOR + http + + + 19 + Get + + + url + http://133.133.12.2:8080/bench4q-web/bench4q-css/bench4q.css + + + + queryParams + + + + headers + header=Accept|value= + text/css,*/*;q=0.1|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/homepage.jsp|; + + + + USERBEHAVIOR + http + + + 20 + Get + + + url + http://133.133.12.2:8080/bench4q-web/css/jquery-ui-1.8.21.custom.css + + + + queryParams + + + + headers + header=Accept|value= + text/css,*/*;q=0.1|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/homepage.jsp|; + + + + USERBEHAVIOR + http + + + 21 + Get + + + url + http://133.133.12.2:8080/bench4q-web/css/opa-icons.css + + + + queryParams + + + + headers + header=Accept|value= + text/css,*/*;q=0.1|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/homepage.jsp|; + + + + USERBEHAVIOR + http + + + 22 + Get + + + url + http://133.133.12.2:8080/bench4q-web/css/colorbox.css + + + + queryParams + + + + headers + header=Accept|value= + text/css,*/*;q=0.1|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/homepage.jsp|; + + + + USERBEHAVIOR + http + + + 23 + Get + + + url + http://133.133.12.2:8080/bench4q-web/js/jquery.cookie.js + + + + queryParams + + + + headers + header=Accept|value= + */*|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/homepage.jsp|; + + + + USERBEHAVIOR + http + + + 24 + Get + + + url + http://133.133.12.2:8080/bench4q-web/js/jquery.dataTables.min.js + + + + queryParams + + + + headers + header=Accept|value= + */*|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/homepage.jsp|; + + + + USERBEHAVIOR + http + + + 25 + Get + + + url + http://133.133.12.2:8080/bench4q-web/js/theme.js + + + queryParams + + + + headers + header=Accept|value= + */*|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/homepage.jsp|; + + + + USERBEHAVIOR + http + + + 26 + Get + + + url + http://133.133.12.2:8080/bench4q-web/script/base.js + + + + queryParams + + + + headers + header=Accept|value= + */*|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/homepage.jsp|; + + + + USERBEHAVIOR + http + + + 27 + Get + + + url + http://133.133.12.2:8080/bench4q-web/script/bench4q.table.js + + + + queryParams + + + + headers + header=Accept|value= + */*|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/homepage.jsp|; + + + + USERBEHAVIOR + http + + + 28 + Get + + + url + http://133.133.12.2:8080/bench4q-web/script/loadTestPlans.js + + + + queryParams + + + + headers + header=Accept|value= + */*|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/homepage.jsp|; + + + + USERBEHAVIOR + http + + + 29 + Get + + + url + http://133.133.12.2:8080/bench4q-web/script/scriptTable.js + + + + queryParams + + + + headers + header=Accept|value= + */*|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/homepage.jsp|; + + + + USERBEHAVIOR + http + + + 30 + Get + + + url + http://133.133.12.2:8080/bench4q-web/js/jquery-ui-1.8.21.custom.min.js + + + + queryParams + + + + headers + header=Accept|value= + */*|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/homepage.jsp|; + + + + USERBEHAVIOR + http + + + 31 + Get + + + url + http://133.133.12.2:8080/bench4q-web/img/bench4q.png + + + + queryParams + + + + headers + header=Accept|value= + image/webp,*/*;q=0.8|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/homepage.jsp|; + + + + USERBEHAVIOR + http + + + 32 + Get + + + url + http://133.133.12.2:8080/bench4q-web/js/bootstrap-dropdown.js + + + + queryParams + + + + headers + header=Accept|value= + */*|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/homepage.jsp|; + + + + USERBEHAVIOR + http + + + 36 + Get + + + url + http://133.133.12.2:8080/bench4q-web/script/home.js + + + + queryParams + + + + headers + header=Accept|value= + */*|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/homepage.jsp|; + + + + USERBEHAVIOR + http + + + -1 + 28 + 0 + + + + + 0 + Sleep + + + time + 10 + + + TIMERBEHAVIOR + timer + + + -1 + 29 + -1 + + + + + 0 + Sleep + + + time + 25 + + + TIMERBEHAVIOR + timer + + + -1 + 30 + -1 + + + + + 0 + Sleep + + + time + 1 + + + TIMERBEHAVIOR + timer + + + -1 + 31 + -1 + + + + + 0 + Sleep + + + time + 4 + + + TIMERBEHAVIOR + timer + + + -1 + 32 + -1 + + + + + 0 + Sleep + + + time + 4 + + + TIMERBEHAVIOR + timer + + + -1 + 33 + -1 + + + + + 0 + Sleep + + + time + 0 + + + TIMERBEHAVIOR + timer + + + -1 + 34 + -1 + + + + + 0 + Sleep + + + time + 1 + + + TIMERBEHAVIOR + timer + + + -1 + 35 + -1 + + + + + 0 + Sleep + + + time + 6 + + + TIMERBEHAVIOR + timer + + + -1 + 36 + -1 + + + + + 0 + Sleep + + + time + 27 + + + TIMERBEHAVIOR + timer + + + -1 + 37 + -1 + + + + + 0 + Sleep + + + time + 9 + + + TIMERBEHAVIOR + timer + + + -1 + 38 + -1 + + + + + 0 + Sleep + + + time + 1 + + + TIMERBEHAVIOR + timer + + + -1 + 39 + -1 + + + + + 0 + Sleep + + + time + 0 + + + TIMERBEHAVIOR + timer + + + -1 + 40 + -1 + + + + + 0 + Sleep + + + time + 1 + + + TIMERBEHAVIOR + timer + + + -1 + 41 + -1 + + + + + 0 + Sleep + + + time + 36 + + + TIMERBEHAVIOR + timer + + + -1 + 42 + -1 + + + + + 0 + Sleep + + + time + 5 + + + TIMERBEHAVIOR + timer + + + -1 + 43 + -1 + + + + + 0 + Sleep + + + time + 1 + + + TIMERBEHAVIOR + timer + + + -1 + 44 + -1 + + + + + 0 + Sleep + + + time + 75 + + + TIMERBEHAVIOR + timer + + + -1 + 45 + -1 + + + + + 33 + Get + + + url + http://133.133.12.2:8080/bench4q-web/img/opa-icons-blue32.png + + + + queryParams + + + + headers + header=Accept|value= + image/webp,*/*;q=0.8|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/homepage.jsp|; + + + + USERBEHAVIOR + http + + + -1 + 46 + -1 + + + + + 0 + Sleep + + + time + 30 + + + TIMERBEHAVIOR + timer + + + -1 + 47 + -1 + + + + + 34 + Get + + + url + http://133.133.12.2:8080/bench4q-web/img/opa-icons-color32.png + + + + queryParams + + + + headers + header=Accept|value= + image/webp,*/*;q=0.8|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/homepage.jsp|; + + + + USERBEHAVIOR + http + + + -1 + 48 + -1 + + + + + 0 + Sleep + + + time + 27 + + + TIMERBEHAVIOR + timer + + + -1 + 49 + -1 + + + + + 35 + Get + + + url + http://133.133.12.2:8080/bench4q-web/img/opa-icons-red32.png + + + + queryParams + + + + headers + header=Accept|value= + image/webp,*/*;q=0.8|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/homepage.jsp|; + + + + USERBEHAVIOR + http + + + -1 + 50 + -1 + + + + + 0 + Sleep + + + time + 1 + + + TIMERBEHAVIOR + timer + + + -1 + 51 + -1 + + + + + 0 + Sleep + + + time + 24 + + + TIMERBEHAVIOR + timer + + + -1 + 52 + -1 + + + + + 37 + Get + + + url + http://themes.googleusercontent.com/static/fonts/shojumaru/v2/pYVcIM206l3F7GUKEvtB3T8E0i7KZn-EPnyo3HZu7kw.woff + + + + queryParams + + + + headers + header=Accept|value= + */*|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/index.jsp|; + + + + USERBEHAVIOR + http + + + -1 + 53 + -1 + + + + + 0 + Sleep + + + time + 145 + + + TIMERBEHAVIOR + timer + + + -1 + 54 + -1 + + + + + 38 + Get + + + url + http://133.133.12.2:8080/bench4q-web/img/opa-icons-green32.png + + + + queryParams + + + + headers + header=Accept|value= + image/webp,*/*;q=0.8|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/homepage.jsp|; + + + + USERBEHAVIOR + http + + + -1 + 55 + -1 + + + + + 0 + Sleep + + + time + 1 + + + TIMERBEHAVIOR + timer + + + -1 + 56 + -1 + + + + + 39 + Get + + + url + http://133.133.12.2:8080/bench4q-web/i18n/i18n.properties + + + + queryParams + _=1389777196041 + + + headers + header=Content-Type|value=text/plain;charset=UTF-8|;header=Accept|value= + text/plain, */*; + q=0.01|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/homepage.jsp|; + + + + USERBEHAVIOR + http + + + -1 + 57 + -1 + + + + + 0 + Sleep + + + time + 8 + + + TIMERBEHAVIOR + timer + + + -1 + 58 + -1 + + + + + 40 + Get + + + url + http://133.133.12.2:8080/bench4q-web/i18n/i18n_zh.properties + + + + queryParams + _=1389777196134 + + + headers + header=Content-Type|value=text/plain;charset=UTF-8|;header=Accept|value= + text/plain, */*; + q=0.01|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/homepage.jsp|; + + + + USERBEHAVIOR + http + + + -1 + 59 + -1 + + + + + 0 + Sleep + + + time + 7 + + + TIMERBEHAVIOR + timer + + + -1 + 60 + -1 + + + + + 41 + Get + + + url + http://133.133.12.2:8080/bench4q-web/i18n/i18n_zh-CN.properties + + + + queryParams + _=1389777196150 + + + headers + header=Content-Type|value=text/plain;charset=UTF-8|;header=Accept|value= + text/plain, */*; + q=0.01|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/homepage.jsp|; + + + + USERBEHAVIOR + http + + + -1 + 61 + -1 + + + + + 0 + Sleep + + + time + 163 + + + TIMERBEHAVIOR + timer + + + -1 + 62 + -1 + + + + + 42 + Post + + + url + http://133.133.12.2:8080/bench4q-web/loadTestPlans + + + + queryParams + + + + headers + header=Accept|value= application/json, text/javascript, + */*; + q=0.01|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/homepage.jsp|; + + + + bodyparameters + + + + USERBEHAVIOR + http + + + -1 + 63 + -1 + + + + + 0 + Sleep + + + time + 1 + + + TIMERBEHAVIOR + timer + + + -1 + 64 + -1 + + + + + 43 + Post + + + url + http://133.133.12.2:8080/bench4q-web/loadScript + + + queryParams + + + + headers + header=Accept|value= application/json, text/javascript, + */*; + q=0.01|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/homepage.jsp|; + + + + bodyparameters + + + + USERBEHAVIOR + http + + + -1 + 65 + -1 + + + + + 0 + Sleep + + + time + 27 + + + TIMERBEHAVIOR + timer + + + -1 + 66 + -1 + + + + + 44 + Get + + + url + http://133.133.12.2:8080/bench4q-web/img/glyphicons-halflings-white.png + + + + queryParams + + + + headers + header=Accept|value= + image/webp,*/*;q=0.8|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/homepage.jsp|; + + + + USERBEHAVIOR + http + + + -1 + 67 + -1 + + + + + 0 + + + http + Http + + + + timer + ConstantTimer + + + + \ No newline at end of file diff --git a/pom.xml b/pom.xml index 703d59a6..c2a500b5 100644 --- a/pom.xml +++ b/pom.xml @@ -1,107 +1,107 @@ - - 4.0.0 - org.bench4q - bench4q-agent - jar - 0.0.1-SNAPSHOT - Bench4Q Agent - Bench4Q Agent - - TCSE, ISCAS - - - - junit - junit - 4.11 - test - - - org.eclipse.jetty - jetty-server - 9.1.0.RC2 - - - org.eclipse.jetty - jetty-servlet - 9.1.0.RC2 - - - org.springframework - spring-webmvc - 3.2.4.RELEASE - - - org.codehaus.jackson - jackson-mapper-asl - 1.9.12 - - - org.apache.hadoop - hadoop-core - 1.1.2 - - - log4j - log4j - 1.2.17 - - - org.bench4q - bench4q-share - 0.0.1-SNAPSHOT - - - org.springframework - spring-core - 3.2.5.RELEASE - - - org.springframework - spring-test - 3.2.5.RELEASE - - - - - - maven-jar-plugin - - - - org.bench4q.agent.Main - true - lib/ - - - - - - maven-assembly-plugin - - - make-zip - package - - single - - - - descriptor.xml - - - - - - - org.apache.maven.plugins - maven-surefire-plugin - - true - - - - bench4q-agent - + + 4.0.0 + org.bench4q + bench4q-agent + jar + 0.0.1-SNAPSHOT + Bench4Q Agent + Bench4Q Agent + + TCSE, ISCAS + + + + junit + junit + 4.11 + test + + + org.eclipse.jetty + jetty-server + 9.1.0.RC2 + + + org.eclipse.jetty + jetty-servlet + 9.1.0.RC2 + + + org.springframework + spring-webmvc + 3.2.4.RELEASE + + + org.codehaus.jackson + jackson-mapper-asl + 1.9.12 + + + org.apache.hadoop + hadoop-core + 1.1.2 + + + log4j + log4j + 1.2.17 + + + org.bench4q + bench4q-share + 0.0.1-SNAPSHOT + + + org.springframework + spring-core + 3.2.5.RELEASE + + + org.springframework + spring-test + 3.2.5.RELEASE + + + + + + maven-jar-plugin + + + + org.bench4q.agent.Main + true + lib/ + + + + + + maven-assembly-plugin + + + make-zip + package + + single + + + + descriptor.xml + + + + + + + org.apache.maven.plugins + maven-surefire-plugin + + true + + + + bench4q-agent + \ No newline at end of file diff --git a/src/main/java/org/bench4q/agent/plugin/basic/HttpPlugin.java b/src/main/java/org/bench4q/agent/plugin/basic/HttpPlugin.java index 29e9b554..b4186912 100644 --- a/src/main/java/org/bench4q/agent/plugin/basic/HttpPlugin.java +++ b/src/main/java/org/bench4q/agent/plugin/basic/HttpPlugin.java @@ -92,7 +92,7 @@ public class HttpPlugin { try { responseCode = this.getHttpClient().executeMethod(method); method.getStatusLine().toString(); - method.getResponseHeaders(); + Header[] responseHeaders = method.getResponseHeaders(); if (method.getResponseHeader("Content-Length") != null) { contentLength = Long.parseLong(method.getResponseHeader( "Content-Length").getValue()); @@ -102,7 +102,7 @@ public class HttpPlugin { .getValue(); } return new HttpReturn(responseCode > 0, responseCode, - contentLength, contentType); + contentLength, contentType, responseHeaders); } catch (HttpException e) { e.printStackTrace(); return new HttpReturn(false, 400, contentLength, contentType); diff --git a/src/main/java/org/bench4q/agent/plugin/result/HttpReturn.java b/src/main/java/org/bench4q/agent/plugin/result/HttpReturn.java index 0821fd86..a82a5be9 100644 --- a/src/main/java/org/bench4q/agent/plugin/result/HttpReturn.java +++ b/src/main/java/org/bench4q/agent/plugin/result/HttpReturn.java @@ -1,45 +1,62 @@ -package org.bench4q.agent.plugin.result; - -/*** - * the contentLength's unit is Byte - * - * @author coderfengyun - * - */ -public class HttpReturn extends PluginReturn { - private int statusCode; - private long contentLength; - private String contentType; - - public int getStatusCode() { - return statusCode; - } - - private void setStatusCode(int statusCode) { - this.statusCode = statusCode; - } - - public long getContentLength() { - return contentLength; - } - - private void setContentLength(long contentLength) { - this.contentLength = contentLength; - } - - public String getContentType() { - return contentType; - } - - private void setContentType(String contentType) { - this.contentType = contentType; - } - - public HttpReturn(boolean success, int statusCode, long contentLength, - String contentType) { - this.setSuccess(success); - this.setStatusCode(statusCode); - this.setContentLength(contentLength); - this.setContentType(contentType); - } -} +package org.bench4q.agent.plugin.result; + +import org.apache.commons.httpclient.Header; + +/*** + * the contentLength's unit is Byte + * + * @author coderfengyun + * + */ +public class HttpReturn extends PluginReturn { + private int statusCode; + private long contentLength; + private String contentType; + private Header[] headers; + + public int getStatusCode() { + return statusCode; + } + + private void setStatusCode(int statusCode) { + this.statusCode = statusCode; + } + + public long getContentLength() { + return contentLength; + } + + private void setContentLength(long contentLength) { + this.contentLength = contentLength; + } + + public String getContentType() { + return contentType; + } + + private void setContentType(String contentType) { + this.contentType = contentType; + } + + public Header[] getHeaders() { + return headers; + } + + private void setHeaders(Header[] headers) { + this.headers = headers; + } + + public HttpReturn(boolean success, int statusCode, long contentLength, + String contentType) { + this.setSuccess(success); + this.setStatusCode(statusCode); + this.setContentLength(contentLength); + this.setContentType(contentType); + } + + public HttpReturn(boolean success, int responseCode, long contentLength2, + String contentType2, Header[] responseHeaders) { + this(success, responseCode, contentLength2, contentType2); + this.setHeaders(responseHeaders); + } +} diff --git a/src/test/java/org/bench4q/agent/test/plugin/TestHttpPlugin.java b/src/test/java/org/bench4q/agent/test/plugin/TestHttpPlugin.java index 5850cd9b..a92bb4e4 100644 --- a/src/test/java/org/bench4q/agent/test/plugin/TestHttpPlugin.java +++ b/src/test/java/org/bench4q/agent/test/plugin/TestHttpPlugin.java @@ -1,6 +1,8 @@ package org.bench4q.agent.test.plugin; +import org.apache.commons.httpclient.Header; import org.bench4q.agent.plugin.basic.HttpPlugin; +import org.bench4q.agent.plugin.result.HttpReturn; import org.bench4q.agent.plugin.result.PluginReturn; import org.junit.Test; @@ -45,4 +47,30 @@ public class TestHttpPlugin { "header=Accept|value=text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8|"); assertTrue(result.isSuccess()); } + + @Test + public void testSessionAndCookie() { + String homeUrl = "http://pan.baidu.com/"; + HttpReturn httpReturn = this + .getHttpPlugin() + .get(homeUrl, + "", + "header=Accept|value=text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8|"); + assertEquals(200, httpReturn.getStatusCode()); + assertNotNull(httpReturn.getHeaders()); + for (Header header : httpReturn.getHeaders()) { + if (header.getName().equals("Set-Cookie")) { + System.out.println("find the cookie : " + header.getValue()); + // Set the cookie to client + setCookieToClient(header); + } + } + + // Then, login with this + + } + + private void setCookieToClient(Header header) { + + } } From 187cf67d8e3ab1269182d945f036d3a065abcf59 Mon Sep 17 00:00:00 2001 From: coderfengyun Date: Wed, 5 Mar 2014 16:16:55 +0800 Subject: [PATCH 150/196] refactor and add new tests --- .../plugin/basic/{ => http}/HttpPlugin.java | 34 ++++-- .../plugin/basic/http/ParameterConstant.java | 6 + .../basic/http}/ParameterParser.java | 62 ++++++---- .../agent/test/plugin/TestHttpPlugin.java | 76 ------------- .../agent/test/plugin/Test_HttpPlugin.java | 107 ++++++++++++++++++ .../scenario/utils/Test_ParameterParser.java | 35 +++++- 6 files changed, 210 insertions(+), 110 deletions(-) rename src/main/java/org/bench4q/agent/plugin/basic/{ => http}/HttpPlugin.java (85%) create mode 100644 src/main/java/org/bench4q/agent/plugin/basic/http/ParameterConstant.java rename src/main/java/org/bench4q/agent/{scenario/utils => plugin/basic/http}/ParameterParser.java (83%) delete mode 100644 src/test/java/org/bench4q/agent/test/plugin/TestHttpPlugin.java create mode 100644 src/test/java/org/bench4q/agent/test/plugin/Test_HttpPlugin.java diff --git a/src/main/java/org/bench4q/agent/plugin/basic/HttpPlugin.java b/src/main/java/org/bench4q/agent/plugin/basic/http/HttpPlugin.java similarity index 85% rename from src/main/java/org/bench4q/agent/plugin/basic/HttpPlugin.java rename to src/main/java/org/bench4q/agent/plugin/basic/http/HttpPlugin.java index b4186912..f0306969 100644 --- a/src/main/java/org/bench4q/agent/plugin/basic/HttpPlugin.java +++ b/src/main/java/org/bench4q/agent/plugin/basic/http/HttpPlugin.java @@ -1,4 +1,4 @@ -package org.bench4q.agent.plugin.basic; +package org.bench4q.agent.plugin.basic.http; import java.io.IOException; import java.io.UnsupportedEncodingException; @@ -21,13 +21,12 @@ import org.bench4q.agent.plugin.Behavior; import org.bench4q.agent.plugin.Parameter; import org.bench4q.agent.plugin.Plugin; import org.bench4q.agent.plugin.result.HttpReturn; -import org.bench4q.agent.scenario.utils.ParameterParser; @Plugin("Http") public class HttpPlugin { private HttpClient httpClient; - private HttpClient getHttpClient() { + public HttpClient getHttpClient() { return httpClient; } @@ -41,12 +40,16 @@ public class HttpPlugin { static void setHeaders(HttpMethod method, String headers) { if (headers != null) { - List> values = ParameterParser.getTable(headers); - Iterator> headerIter = values.iterator(); - while (headerIter.hasNext()) { - Iterator entryIter = headerIter.next().iterator(); - String name = entryIter.next(); - method.addRequestHeader(name, entryIter.next()); + // List> values = ParameterParser.getTable(headers); + // Iterator> headerIter = values.iterator(); + // while (headerIter.hasNext()) { + // Iterator entryIter = headerIter.next().iterator(); + // String name = entryIter.next(); + // method.addRequestHeader(name, entryIter.next()); + // } + List nvPairs = ParameterParser.parseHeaders(headers); + for (NameValuePair nv : nvPairs) { + method.addRequestHeader(nv.getName(), nv.getValue()); } } } @@ -82,6 +85,7 @@ public class HttpPlugin { } setHeaders(method, headers); method.getParams().makeLenient(); + method.setFollowRedirects(false); return excuteMethod(method); } @@ -101,6 +105,10 @@ public class HttpPlugin { contentType = method.getResponseHeader("Content-Type") .getValue(); } + if (method.getRequestHeader("Set-Cookie") != null) { + setCookies(method.getRequestHeader("Set-Cookie"), method + .getURI().getHost() + ":" + method.getURI().getPort()); + } return new HttpReturn(responseCode > 0, responseCode, contentLength, contentType, responseHeaders); } catch (HttpException e) { @@ -114,6 +122,14 @@ public class HttpPlugin { } } + private void setCookies(Header requestHeader, String domain) { + // this.getHttpClient() + // .getState() + // .addCookie( + // new Cookie(domain, requestHeader.getName(), + // requestHeader.getValue())); + } + @Behavior("Post") public HttpReturn post(@Parameter("url") String url, @Parameter("queryParams") String queryParams, diff --git a/src/main/java/org/bench4q/agent/plugin/basic/http/ParameterConstant.java b/src/main/java/org/bench4q/agent/plugin/basic/http/ParameterConstant.java new file mode 100644 index 00000000..fbbe8a60 --- /dev/null +++ b/src/main/java/org/bench4q/agent/plugin/basic/http/ParameterConstant.java @@ -0,0 +1,6 @@ +package org.bench4q.agent.plugin.basic.http; + +public class ParameterConstant { + public static final String HEADER_VALUE_SIGN = "value="; + public static final String HEADER_NAME_SIGN = "header="; +} diff --git a/src/main/java/org/bench4q/agent/scenario/utils/ParameterParser.java b/src/main/java/org/bench4q/agent/plugin/basic/http/ParameterParser.java similarity index 83% rename from src/main/java/org/bench4q/agent/scenario/utils/ParameterParser.java rename to src/main/java/org/bench4q/agent/plugin/basic/http/ParameterParser.java index d492cdba..c803ee7d 100644 --- a/src/main/java/org/bench4q/agent/scenario/utils/ParameterParser.java +++ b/src/main/java/org/bench4q/agent/plugin/basic/http/ParameterParser.java @@ -1,36 +1,19 @@ -/* - * CLIF is a Load Injection Framework - * Copyright (C) 2008, 2009 France Telecom R&D - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - * - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA - * - * Contact: clif@ow2.org - */ - -package org.bench4q.agent.scenario.utils; +package org.bench4q.agent.plugin.basic.http; import java.util.ArrayList; +import java.util.LinkedList; import java.util.List; import java.util.StringTokenizer; +import org.apache.commons.httpclient.NameValuePair; + /** * * @author coderfengyun * */ public abstract class ParameterParser { + static public List getNField(String value) { StringTokenizer st = new StringTokenizer(value, ";", false); List result = new ArrayList(); @@ -58,6 +41,40 @@ public abstract class ParameterParser { return getRadioGroup(value); } + static public List parseHeaders(String value) { + List nvPairs = new LinkedList(); + String[] entrys = value.split("\\|;"); + + for (String entry : entrys) { + String[] nv = entry.split("\\|"); + if (nv.length != 2) { + continue; + } + ; + nvPairs.add(distillHeader(nv[0].trim(), nv[1].trim())); + } + return nvPairs; + } + + private static NameValuePair distillHeader(String name, String value) { + return new NameValuePair(extractHeaderName(name), + extractHeaderValue(value)); + } + + private static String extractHeaderValue(String value) { + if (!value.startsWith(ParameterConstant.HEADER_VALUE_SIGN)) { + return value; + } + return value.substring(ParameterConstant.HEADER_VALUE_SIGN.length()); + } + + private static String extractHeaderName(String name) { + if (!name.startsWith(ParameterConstant.HEADER_NAME_SIGN)) { + return name; + } + return name.substring(ParameterConstant.HEADER_NAME_SIGN.length()); + } + /** * This method analyzes the value to be set in the table, and remove all * escape characters @@ -70,7 +87,6 @@ public abstract class ParameterParser { */ static public List> getTable(String value) { List> result = new ArrayList>(); - // TODO: read this carefully List tempEntries = getRealTokens("|;", value); // now analyze all entries values, and get the '|' separator List> allValues = new ArrayList>(); diff --git a/src/test/java/org/bench4q/agent/test/plugin/TestHttpPlugin.java b/src/test/java/org/bench4q/agent/test/plugin/TestHttpPlugin.java deleted file mode 100644 index a92bb4e4..00000000 --- a/src/test/java/org/bench4q/agent/test/plugin/TestHttpPlugin.java +++ /dev/null @@ -1,76 +0,0 @@ -package org.bench4q.agent.test.plugin; - -import org.apache.commons.httpclient.Header; -import org.bench4q.agent.plugin.basic.HttpPlugin; -import org.bench4q.agent.plugin.result.HttpReturn; -import org.bench4q.agent.plugin.result.PluginReturn; -import org.junit.Test; - -import static org.junit.Assert.*; - -public class TestHttpPlugin { - private HttpPlugin httpPlugin; - - private HttpPlugin getHttpPlugin() { - return httpPlugin; - } - - private void setHttpPlugin(HttpPlugin httpPlugin) { - this.httpPlugin = httpPlugin; - } - - public TestHttpPlugin() { - this.setHttpPlugin(new HttpPlugin()); - } - - @Test - public void testGet() { - PluginReturn return1 = this.getHttpPlugin().get( - "http://www.baidu.com/s", "wd=ok", ""); - assertTrue(return1.isSuccess()); - } - - @Test - public void testPost() { - PluginReturn result = this.getHttpPlugin().post( - "http://133.133.12.2:8080/bench4q-web/login", - "userName=admin;password=admin", null, null, null); - assertTrue(result.isSuccess()); - } - - @Test - public void testGetWithActualBehavior() { - PluginReturn result = this - .getHttpPlugin() - .get("http://133.133.12.2:8080/bench4q-web/index.jsp", - "", - "header=Accept|value=text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8|"); - assertTrue(result.isSuccess()); - } - - @Test - public void testSessionAndCookie() { - String homeUrl = "http://pan.baidu.com/"; - HttpReturn httpReturn = this - .getHttpPlugin() - .get(homeUrl, - "", - "header=Accept|value=text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8|"); - assertEquals(200, httpReturn.getStatusCode()); - assertNotNull(httpReturn.getHeaders()); - for (Header header : httpReturn.getHeaders()) { - if (header.getName().equals("Set-Cookie")) { - System.out.println("find the cookie : " + header.getValue()); - // Set the cookie to client - setCookieToClient(header); - } - } - - // Then, login with this - - } - - private void setCookieToClient(Header header) { - - } -} diff --git a/src/test/java/org/bench4q/agent/test/plugin/Test_HttpPlugin.java b/src/test/java/org/bench4q/agent/test/plugin/Test_HttpPlugin.java new file mode 100644 index 00000000..0f39e3c6 --- /dev/null +++ b/src/test/java/org/bench4q/agent/test/plugin/Test_HttpPlugin.java @@ -0,0 +1,107 @@ +package org.bench4q.agent.test.plugin; + +import java.util.HashMap; +import java.util.Map; + +import org.apache.commons.httpclient.Cookie; +import org.apache.commons.httpclient.Header; +import org.apache.commons.httpclient.cookie.MalformedCookieException; +import org.apache.commons.httpclient.cookie.RFC2109Spec; +import org.bench4q.agent.plugin.basic.http.HttpPlugin; +import org.bench4q.agent.plugin.result.HttpReturn; +import org.bench4q.agent.plugin.result.PluginReturn; +import org.junit.Test; + +import static org.junit.Assert.*; + +public class Test_HttpPlugin { + private static final boolean HTTP_ONLY = false; + private HttpPlugin httpPlugin; + + private HttpPlugin getHttpPlugin() { + return httpPlugin; + } + + private void setHttpPlugin(HttpPlugin httpPlugin) { + this.httpPlugin = httpPlugin; + } + + public Test_HttpPlugin() { + this.setHttpPlugin(new HttpPlugin()); + } + + @Test + public void testGet() { + PluginReturn return1 = this.getHttpPlugin().get( + "http://www.baidu.com/s", "wd=ok", ""); + assertTrue(return1.isSuccess()); + } + + @Test + public void testPost() { + PluginReturn result = this.getHttpPlugin().post( + "http://133.133.12.2:8080/bench4q-web/login", + "userName=admin;password=admin", null, null, null); + assertTrue(result.isSuccess()); + } + + @Test + public void testGetWithActualBehavior() { + PluginReturn result = this + .getHttpPlugin() + .get("http://133.133.12.2:8080/bench4q-web/index.jsp", + "", + "header=Accept|value=text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8|"); + assertTrue(result.isSuccess()); + } + + @Test + public void testSessionAndCookie() throws MalformedCookieException, + IllegalArgumentException { + String loginPageUrl = "http://124.16.137.203:7080/cloudshare_web/login"; + HttpReturn httpReturn2 = this + .getHttpPlugin() + .get(loginPageUrl, + "", + "header=Accept|value=text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8|"); + assertEquals(401, httpReturn2.getStatusCode()); + assertNotNull(httpReturn2.getHeaders()); + setCookieToClient(httpReturn2.getHeaders(), "124.16.137.205", 7080); + + HttpReturn httpReturn = this + .getHttpPlugin() + .post(loginPageUrl, + "", + "header=Content-Type|value=application/x-www-form-urlencoded|;header=Content-Length|value=63|;header=Accept|value=text/html,application/xhtml+xml,application/xml|;", + null, + "username=chentienan12@otcaix.iscas.ac.cn&password=jingcai2008"); + assertEquals(200, httpReturn.getStatusCode()); + assertNotNull(httpReturn2.getHeaders()); + } + + private void setCookieToClient(Header[] headers, String hostName, int port) + throws MalformedCookieException, IllegalArgumentException { + for (Header header : headers) { + if (header.getName().equals("Set-Cookie")) { + addCookieToClient(header, hostName, port); + } + } + } + + private void addCookieToClient(Header header, String hostName, int port) + throws MalformedCookieException, IllegalArgumentException { + String contentFromResponse = header.getValue(); + System.out.println(contentFromResponse); + String[] cookieContent = contentFromResponse.split(";"); + Map nValueMap = new HashMap(); + for (int i = 0; i < cookieContent.length; i++) { + int equalSignIndex = cookieContent[i].indexOf('='); + nValueMap.put(cookieContent[i].substring(0, equalSignIndex).trim(), + cookieContent[i].substring(equalSignIndex + 1).trim()); + } + Cookie[] cookies = new RFC2109Spec().parse(hostName, port, + nValueMap.get("Path"), HTTP_ONLY, header); + this.getHttpPlugin().getHttpClient().getState().addCookies(cookies); + } + +} diff --git a/src/test/java/org/bench4q/agent/test/scenario/utils/Test_ParameterParser.java b/src/test/java/org/bench4q/agent/test/scenario/utils/Test_ParameterParser.java index fe8a69d0..8c6efeef 100644 --- a/src/test/java/org/bench4q/agent/test/scenario/utils/Test_ParameterParser.java +++ b/src/test/java/org/bench4q/agent/test/scenario/utils/Test_ParameterParser.java @@ -5,12 +5,14 @@ import static org.junit.Assert.*; import java.util.ArrayList; import java.util.List; -import org.bench4q.agent.scenario.utils.ParameterParser; +import org.apache.commons.httpclient.NameValuePair; +import org.bench4q.agent.plugin.basic.http.ParameterParser; import org.junit.Test; public class Test_ParameterParser { private String testcase = " _nacc=yeah ;_nvid=525d29a534e918cbf04ea7159706a93d;_nvtm=0;_nvsf=0;_nvfi=1;_nlag=zh-cn;_nlmf=1389570024;_nres=1440x900;_nscd=32-bit;_nstm=0;"; - + private String testHeaders = "header=Content-Type|value=application/x-www-form-urlencoded|;header=Content-Length|value=63|;header=Accept|value=text/html,application/xhtml+xml,application/xml|;"; + private String testheaderWithUpperCase = "HEADER=Content-Type|Value=application/x-www-form-urlencoded|;header=Content-Length|value=63|;header=Accept|value=text/html,application/xhtml+xml,application/xml|;"; private List expectedNFField = new ArrayList() { private static final long serialVersionUID = 1L; { @@ -36,4 +38,33 @@ public class Test_ParameterParser { System.out.println(result.get(i)); } } + + @Test + public void testGetHeadersWithRightCase() { + List nvPairs = ParameterParser.parseHeaders(testHeaders); + assertEquals(3, nvPairs.size()); + assertEquals("Content-Type", nvPairs.get(0).getName()); + assertEquals("application/x-www-form-urlencoded", nvPairs.get(0) + .getValue()); + assertEquals("Content-Length", nvPairs.get(1).getName()); + assertEquals("63", nvPairs.get(1).getValue()); + assertEquals("Accept", nvPairs.get(2).getName()); + assertEquals("text/html,application/xhtml+xml,application/xml", nvPairs + .get(2).getValue()); + } + + @Test + public void testGetHeadersWithUpperCase() { + List nvPairs = ParameterParser + .parseHeaders(testheaderWithUpperCase); + assertEquals(3, nvPairs.size()); + assertEquals("Content-Type", nvPairs.get(0).getName()); + assertEquals("application/x-www-form-urlencoded", nvPairs.get(0) + .getValue()); + assertEquals("Content-Length", nvPairs.get(1).getName()); + assertEquals("63", nvPairs.get(1).getValue()); + assertEquals("Accept", nvPairs.get(2).getName()); + assertEquals("text/html,application/xhtml+xml,application/xml", nvPairs + .get(2).getValue()); + } } From e6d7b5ed31fd937d5de9a44191ca9ee302262dea Mon Sep 17 00:00:00 2001 From: coderfengyun Date: Wed, 5 Mar 2014 16:20:01 +0800 Subject: [PATCH 151/196] pass the test --- .../org/bench4q/agent/plugin/basic/http/ParameterParser.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/bench4q/agent/plugin/basic/http/ParameterParser.java b/src/main/java/org/bench4q/agent/plugin/basic/http/ParameterParser.java index c803ee7d..3818297c 100644 --- a/src/main/java/org/bench4q/agent/plugin/basic/http/ParameterParser.java +++ b/src/main/java/org/bench4q/agent/plugin/basic/http/ParameterParser.java @@ -62,14 +62,15 @@ public abstract class ParameterParser { } private static String extractHeaderValue(String value) { - if (!value.startsWith(ParameterConstant.HEADER_VALUE_SIGN)) { + if (!value.toLowerCase() + .startsWith(ParameterConstant.HEADER_VALUE_SIGN)) { return value; } return value.substring(ParameterConstant.HEADER_VALUE_SIGN.length()); } private static String extractHeaderName(String name) { - if (!name.startsWith(ParameterConstant.HEADER_NAME_SIGN)) { + if (!name.toLowerCase().startsWith(ParameterConstant.HEADER_NAME_SIGN)) { return name; } return name.substring(ParameterConstant.HEADER_NAME_SIGN.length()); From 1ca7c0eb36b030915aa4551fec9eaf2409cf4b71 Mon Sep 17 00:00:00 2001 From: coderfengyun Date: Wed, 5 Mar 2014 20:37:06 +0800 Subject: [PATCH 152/196] the httpclient can keep session all itself --- .../agent/plugin/basic/http/HttpPlugin.java | 27 ++++---- .../agent/test/plugin/Test_HttpPlugin.java | 62 ++++++++----------- 2 files changed, 40 insertions(+), 49 deletions(-) diff --git a/src/main/java/org/bench4q/agent/plugin/basic/http/HttpPlugin.java b/src/main/java/org/bench4q/agent/plugin/basic/http/HttpPlugin.java index f0306969..b0da1abd 100644 --- a/src/main/java/org/bench4q/agent/plugin/basic/http/HttpPlugin.java +++ b/src/main/java/org/bench4q/agent/plugin/basic/http/HttpPlugin.java @@ -7,6 +7,7 @@ import java.util.Iterator; import java.util.List; import java.util.Set; +import org.apache.commons.httpclient.Cookie; import org.apache.commons.httpclient.Header; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpException; @@ -38,19 +39,23 @@ public class HttpPlugin { this.setHttpClient(new HttpClient()); } - static void setHeaders(HttpMethod method, String headers) { + void setHeaders(HttpMethod method, String headers) { if (headers != null) { - // List> values = ParameterParser.getTable(headers); - // Iterator> headerIter = values.iterator(); - // while (headerIter.hasNext()) { - // Iterator entryIter = headerIter.next().iterator(); - // String name = entryIter.next(); - // method.addRequestHeader(name, entryIter.next()); - // } List nvPairs = ParameterParser.parseHeaders(headers); for (NameValuePair nv : nvPairs) { method.addRequestHeader(nv.getName(), nv.getValue()); } + // New add + String cookieValue = ""; + for (Cookie cookie : this.getHttpClient().getState().getCookies()) { + if (!cookieValue.isEmpty()) { + cookieValue += ";"; + } + cookieValue += cookie.getName() + "=" + cookie.getValue(); + } + if (!cookieValue.isEmpty()) { + method.addRequestHeader("Cookie", cookieValue); + } } } @@ -79,6 +84,7 @@ public class HttpPlugin { public HttpReturn get(@Parameter("url") String url, @Parameter("queryParams") String queryParams, @Parameter("headers") String headers) { + // QueryParams should be split by ; GetMethod method = new GetMethod(completeUri(url)); if (isValidString(queryParams)) { method.setQueryString(queryParams); @@ -123,11 +129,6 @@ public class HttpPlugin { } private void setCookies(Header requestHeader, String domain) { - // this.getHttpClient() - // .getState() - // .addCookie( - // new Cookie(domain, requestHeader.getName(), - // requestHeader.getValue())); } @Behavior("Post") diff --git a/src/test/java/org/bench4q/agent/test/plugin/Test_HttpPlugin.java b/src/test/java/org/bench4q/agent/test/plugin/Test_HttpPlugin.java index 0f39e3c6..5b73ae13 100644 --- a/src/test/java/org/bench4q/agent/test/plugin/Test_HttpPlugin.java +++ b/src/test/java/org/bench4q/agent/test/plugin/Test_HttpPlugin.java @@ -1,12 +1,7 @@ package org.bench4q.agent.test.plugin; -import java.util.HashMap; -import java.util.Map; - import org.apache.commons.httpclient.Cookie; -import org.apache.commons.httpclient.Header; import org.apache.commons.httpclient.cookie.MalformedCookieException; -import org.apache.commons.httpclient.cookie.RFC2109Spec; import org.bench4q.agent.plugin.basic.http.HttpPlugin; import org.bench4q.agent.plugin.result.HttpReturn; import org.bench4q.agent.plugin.result.PluginReturn; @@ -15,7 +10,7 @@ import org.junit.Test; import static org.junit.Assert.*; public class Test_HttpPlugin { - private static final boolean HTTP_ONLY = false; + private static final int UnAuthorized = 401; private HttpPlugin httpPlugin; private HttpPlugin getHttpPlugin() { @@ -64,44 +59,39 @@ public class Test_HttpPlugin { .get(loginPageUrl, "", "header=Accept|value=text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8|"); - assertEquals(401, httpReturn2.getStatusCode()); + assertEquals(UnAuthorized, httpReturn2.getStatusCode()); assertNotNull(httpReturn2.getHeaders()); - setCookieToClient(httpReturn2.getHeaders(), "124.16.137.205", 7080); - - HttpReturn httpReturn = this + // setCookieToClient(httpReturn2.getHeaders(), "124.16.137.205", 7080); + logTheCookie("first"); + HttpReturn httpReturnLogin = this .getHttpPlugin() .post(loginPageUrl, - "", + "username=chentienan12%40otcaix.iscas.ac.cn;password=jingcai2008", "header=Content-Type|value=application/x-www-form-urlencoded|;header=Content-Length|value=63|;header=Accept|value=text/html,application/xhtml+xml,application/xml|;", + null, null); + assertEquals(200, httpReturnLogin.getStatusCode()); + assertNotNull(httpReturnLogin.getHeaders()); + logTheCookie("second"); + this.getHttpPlugin() + .get(loginPageUrl, + "", + "header=Accept|value=text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8|"); + logTheCookie("third"); + HttpReturn homeReturn = this + .getHttpPlugin() + .get("http://124.16.137.203:7080/cloudshare_web/home", null, - "username=chentienan12@otcaix.iscas.ac.cn&password=jingcai2008"); - assertEquals(200, httpReturn.getStatusCode()); - assertNotNull(httpReturn2.getHeaders()); + "header=Accept|value=text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8|;header=Accept-Language|value=zh-CN,zh;q=0.8|;"); + assertEquals(302, homeReturn.getStatusCode()); + logTheCookie("fourth"); } - private void setCookieToClient(Header[] headers, String hostName, int port) - throws MalformedCookieException, IllegalArgumentException { - for (Header header : headers) { - if (header.getName().equals("Set-Cookie")) { - addCookieToClient(header, hostName, port); - } + private void logTheCookie(String times) { + for (Cookie cookie : this.getHttpPlugin().getHttpClient().getState() + .getCookies()) { + System.out.println("Cookie from httpState for " + times + " : " + + cookie.getName() + " : " + cookie.getValue()); } } - private void addCookieToClient(Header header, String hostName, int port) - throws MalformedCookieException, IllegalArgumentException { - String contentFromResponse = header.getValue(); - System.out.println(contentFromResponse); - String[] cookieContent = contentFromResponse.split(";"); - Map nValueMap = new HashMap(); - for (int i = 0; i < cookieContent.length; i++) { - int equalSignIndex = cookieContent[i].indexOf('='); - nValueMap.put(cookieContent[i].substring(0, equalSignIndex).trim(), - cookieContent[i].substring(equalSignIndex + 1).trim()); - } - Cookie[] cookies = new RFC2109Spec().parse(hostName, port, - nValueMap.get("Path"), HTTP_ONLY, header); - this.getHttpPlugin().getHttpClient().getState().addCookies(cookies); - } - } From c7ed65cc9cb4c8a8f72b5e8198491d733b2c0cf1 Mon Sep 17 00:00:00 2001 From: coderfengyun Date: Wed, 5 Mar 2014 21:21:45 +0800 Subject: [PATCH 153/196] now, this testcase has passed the session one --- .../agent/plugin/basic/http/HttpPlugin.java | 1 + .../agent/test/plugin/Test_HttpPlugin.java | 31 +++++++++---------- 2 files changed, 15 insertions(+), 17 deletions(-) diff --git a/src/main/java/org/bench4q/agent/plugin/basic/http/HttpPlugin.java b/src/main/java/org/bench4q/agent/plugin/basic/http/HttpPlugin.java index b0da1abd..2beb74c9 100644 --- a/src/main/java/org/bench4q/agent/plugin/basic/http/HttpPlugin.java +++ b/src/main/java/org/bench4q/agent/plugin/basic/http/HttpPlugin.java @@ -157,6 +157,7 @@ public class HttpPlugin { } } method.getParams().makeLenient(); + method.setFollowRedirects(false); return excuteMethod(method); } diff --git a/src/test/java/org/bench4q/agent/test/plugin/Test_HttpPlugin.java b/src/test/java/org/bench4q/agent/test/plugin/Test_HttpPlugin.java index 5b73ae13..0c8c6659 100644 --- a/src/test/java/org/bench4q/agent/test/plugin/Test_HttpPlugin.java +++ b/src/test/java/org/bench4q/agent/test/plugin/Test_HttpPlugin.java @@ -54,35 +54,32 @@ public class Test_HttpPlugin { public void testSessionAndCookie() throws MalformedCookieException, IllegalArgumentException { String loginPageUrl = "http://124.16.137.203:7080/cloudshare_web/login"; - HttpReturn httpReturn2 = this + HttpReturn indexReturn = this .getHttpPlugin() .get(loginPageUrl, "", - "header=Accept|value=text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8|"); - assertEquals(UnAuthorized, httpReturn2.getStatusCode()); - assertNotNull(httpReturn2.getHeaders()); - // setCookieToClient(httpReturn2.getHeaders(), "124.16.137.205", 7080); + "header=Accept|value=text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8|;"); + assertEquals(UnAuthorized, indexReturn.getStatusCode()); + assertNotNull(indexReturn.getHeaders()); logTheCookie("first"); - HttpReturn httpReturnLogin = this + + HttpReturn loginReturn = this .getHttpPlugin() .post(loginPageUrl, - "username=chentienan12%40otcaix.iscas.ac.cn;password=jingcai2008", + null, "header=Content-Type|value=application/x-www-form-urlencoded|;header=Content-Length|value=63|;header=Accept|value=text/html,application/xhtml+xml,application/xml|;", - null, null); - assertEquals(200, httpReturnLogin.getStatusCode()); - assertNotNull(httpReturnLogin.getHeaders()); + "username=chentienan12%40otcaix.iscas.ac.cn&password=jingcai2008", + null); + assertEquals(302, loginReturn.getStatusCode()); + assertNotNull(loginReturn.getHeaders()); logTheCookie("second"); - this.getHttpPlugin() - .get(loginPageUrl, - "", - "header=Accept|value=text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8|"); - logTheCookie("third"); + HttpReturn homeReturn = this .getHttpPlugin() .get("http://124.16.137.203:7080/cloudshare_web/home", null, - "header=Accept|value=text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8|;header=Accept-Language|value=zh-CN,zh;q=0.8|;"); - assertEquals(302, homeReturn.getStatusCode()); + "header=Accept|value=text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8|;"); + assertEquals(200, homeReturn.getStatusCode()); logTheCookie("fourth"); } From b0cfa330a53df382844ce3a6c7b3bc81414a31aa Mon Sep 17 00:00:00 2001 From: coderfengyun Date: Fri, 7 Mar 2014 10:35:29 +0800 Subject: [PATCH 154/196] add comment --- .../agent/plugin/basic/http/HttpPlugin.java | 21 ++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/src/main/java/org/bench4q/agent/plugin/basic/http/HttpPlugin.java b/src/main/java/org/bench4q/agent/plugin/basic/http/HttpPlugin.java index 2beb74c9..5bde4229 100644 --- a/src/main/java/org/bench4q/agent/plugin/basic/http/HttpPlugin.java +++ b/src/main/java/org/bench4q/agent/plugin/basic/http/HttpPlugin.java @@ -1,3 +1,10 @@ +/* + * Author Coderfengyun + * + * And th parmas has some special split. + * Like, QueryParams and bodyParams should be split by ';' + * And Headers should be split by '|;' + */ package org.bench4q.agent.plugin.basic.http; import java.io.IOException; @@ -84,7 +91,8 @@ public class HttpPlugin { public HttpReturn get(@Parameter("url") String url, @Parameter("queryParams") String queryParams, @Parameter("headers") String headers) { - // QueryParams should be split by ; + // QueryParams should be split by ';' + // headers should be split by '|;' GetMethod method = new GetMethod(completeUri(url)); if (isValidString(queryParams)) { method.setQueryString(queryParams); @@ -131,6 +139,17 @@ public class HttpPlugin { private void setCookies(Header requestHeader, String domain) { } + /** + * + * @param url + * @param queryParams + * @param headers + * @param bodyContent + * , when the Content-Length in header G.T. zero, then use this + * @param bodyParams + * , else use this + * @return + */ @Behavior("Post") public HttpReturn post(@Parameter("url") String url, @Parameter("queryParams") String queryParams, From 17f3f7ab7d2a63fbab54ba86dba1030b56458926 Mon Sep 17 00:00:00 2001 From: coderfengyun Date: Fri, 7 Mar 2014 11:36:07 +0800 Subject: [PATCH 155/196] add responseVar To sessionContext --- .../agent/plugin/basic/http/HttpPlugin.java | 39 ++++++++++++++----- .../plugin/basic/http/SessionContext.java | 24 ++++++++++++ .../agent/test/plugin/Test_HttpPlugin.java | 15 ++++--- 3 files changed, 63 insertions(+), 15 deletions(-) create mode 100644 src/main/java/org/bench4q/agent/plugin/basic/http/SessionContext.java diff --git a/src/main/java/org/bench4q/agent/plugin/basic/http/HttpPlugin.java b/src/main/java/org/bench4q/agent/plugin/basic/http/HttpPlugin.java index 5bde4229..b03738e1 100644 --- a/src/main/java/org/bench4q/agent/plugin/basic/http/HttpPlugin.java +++ b/src/main/java/org/bench4q/agent/plugin/basic/http/HttpPlugin.java @@ -33,6 +33,7 @@ import org.bench4q.agent.plugin.result.HttpReturn; @Plugin("Http") public class HttpPlugin { private HttpClient httpClient; + private SessionContext sessionContext; public HttpClient getHttpClient() { return httpClient; @@ -42,8 +43,17 @@ public class HttpPlugin { this.httpClient = httpClient; } + private SessionContext getSessionContext() { + return sessionContext; + } + + private void setSessionContext(SessionContext sessionContext) { + this.sessionContext = sessionContext; + } + public HttpPlugin() { this.setHttpClient(new HttpClient()); + this.setSessionContext(new SessionContext()); } void setHeaders(HttpMethod method, String headers) { @@ -90,7 +100,8 @@ public class HttpPlugin { @Behavior("Get") public HttpReturn get(@Parameter("url") String url, @Parameter("queryParams") String queryParams, - @Parameter("headers") String headers) { + @Parameter("headers") String headers, + @Parameter("respVarToSaveInSession") String respVarToSaveInSession) { // QueryParams should be split by ';' // headers should be split by '|;' GetMethod method = new GetMethod(completeUri(url)); @@ -100,10 +111,11 @@ public class HttpPlugin { setHeaders(method, headers); method.getParams().makeLenient(); method.setFollowRedirects(false); - return excuteMethod(method); + return excuteMethod(method, respVarToSaveInSession); } - private HttpReturn excuteMethod(HttpMethod method) { + private HttpReturn excuteMethod(HttpMethod method, + String respVarToSaveInSession) { int responseCode = -1; long contentLength = 0; String contentType = ""; @@ -123,6 +135,12 @@ public class HttpPlugin { setCookies(method.getRequestHeader("Set-Cookie"), method .getURI().getHost() + ":" + method.getURI().getPort()); } + if (respVarToSaveInSession != null + && !respVarToSaveInSession.isEmpty()) { + // TODO:Now i just save all the responseBody + this.getSessionContext().addAVariable(respVarToSaveInSession, + method.getResponseBodyAsString()); + } return new HttpReturn(responseCode > 0, responseCode, contentLength, contentType, responseHeaders); } catch (HttpException e) { @@ -155,7 +173,8 @@ public class HttpPlugin { @Parameter("queryParams") String queryParams, @Parameter("headers") String headers, @Parameter("bodyContent") String bodyContent, - @Parameter("bodyparameters") String bodyParams) { + @Parameter("bodyparameters") String bodyParams, + @Parameter("respVarToSaveInSession") String respVarToSaveInSession) { PostMethod method = new PostMethod(completeUri(url)); setHeaders(method, headers); if (isValidString(queryParams)) { @@ -177,7 +196,7 @@ public class HttpPlugin { } method.getParams().makeLenient(); method.setFollowRedirects(false); - return excuteMethod(method); + return excuteMethod(method, respVarToSaveInSession); } private String getMethodContentType(HttpMethod method) { @@ -199,7 +218,8 @@ public class HttpPlugin { @Parameter("queryParams") String queryParams, @Parameter("headers") String headers, @Parameter("bodyContent") String bodyContent, - @Parameter("bodyparameters") String bodyParams) { + @Parameter("bodyparameters") String bodyParams, + @Parameter("respVarToSaveInSession") String respVarToSaveInSession) { PutMethod method = new PutMethod(completeUri(url)); setHeaders(method, headers); if (isValidString(queryParams)) { @@ -216,13 +236,14 @@ public class HttpPlugin { } } method.getParams().makeLenient(); - return excuteMethod(method); + return excuteMethod(method, respVarToSaveInSession); } @Behavior("Delete") public HttpReturn delete(@Parameter("url") String url, @Parameter("queryParams") String queryParams, - @Parameter("headers") String headers) { + @Parameter("headers") String headers, + @Parameter("respVarToSaveInSession") String respVarToSaveInSession) { DeleteMethod method = new DeleteMethod(completeUri(url)); setHeaders(method, headers); if (isValidString(queryParams)) { @@ -230,6 +251,6 @@ public class HttpPlugin { .getNField(queryParams))); } method.getParams().makeLenient(); - return excuteMethod(method); + return excuteMethod(method, respVarToSaveInSession); } } diff --git a/src/main/java/org/bench4q/agent/plugin/basic/http/SessionContext.java b/src/main/java/org/bench4q/agent/plugin/basic/http/SessionContext.java new file mode 100644 index 00000000..c96cc7b4 --- /dev/null +++ b/src/main/java/org/bench4q/agent/plugin/basic/http/SessionContext.java @@ -0,0 +1,24 @@ +package org.bench4q.agent.plugin.basic.http; + +import java.util.HashMap; +import java.util.Map; + +public class SessionContext { + Map variables; + + private Map getVariables() { + return variables; + } + + private void setVariables(Map variables) { + this.variables = variables; + } + + public SessionContext() { + this.setVariables(new HashMap()); + } + + public void addAVariable(String entryName, String entryValue) { + this.getVariables().put(entryName, entryValue); + } +} diff --git a/src/test/java/org/bench4q/agent/test/plugin/Test_HttpPlugin.java b/src/test/java/org/bench4q/agent/test/plugin/Test_HttpPlugin.java index 0c8c6659..8018bbc9 100644 --- a/src/test/java/org/bench4q/agent/test/plugin/Test_HttpPlugin.java +++ b/src/test/java/org/bench4q/agent/test/plugin/Test_HttpPlugin.java @@ -28,7 +28,7 @@ public class Test_HttpPlugin { @Test public void testGet() { PluginReturn return1 = this.getHttpPlugin().get( - "http://www.baidu.com/s", "wd=ok", ""); + "http://www.baidu.com/s", "wd=ok", "", ""); assertTrue(return1.isSuccess()); } @@ -36,7 +36,7 @@ public class Test_HttpPlugin { public void testPost() { PluginReturn result = this.getHttpPlugin().post( "http://133.133.12.2:8080/bench4q-web/login", - "userName=admin;password=admin", null, null, null); + "userName=admin;password=admin", null, null, null, null); assertTrue(result.isSuccess()); } @@ -46,7 +46,8 @@ public class Test_HttpPlugin { .getHttpPlugin() .get("http://133.133.12.2:8080/bench4q-web/index.jsp", "", - "header=Accept|value=text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8|"); + "header=Accept|value=text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8|", + null); assertTrue(result.isSuccess()); } @@ -58,7 +59,8 @@ public class Test_HttpPlugin { .getHttpPlugin() .get(loginPageUrl, "", - "header=Accept|value=text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8|;"); + "header=Accept|value=text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8|;", + null); assertEquals(UnAuthorized, indexReturn.getStatusCode()); assertNotNull(indexReturn.getHeaders()); logTheCookie("first"); @@ -69,7 +71,7 @@ public class Test_HttpPlugin { null, "header=Content-Type|value=application/x-www-form-urlencoded|;header=Content-Length|value=63|;header=Accept|value=text/html,application/xhtml+xml,application/xml|;", "username=chentienan12%40otcaix.iscas.ac.cn&password=jingcai2008", - null); + null, null); assertEquals(302, loginReturn.getStatusCode()); assertNotNull(loginReturn.getHeaders()); logTheCookie("second"); @@ -78,7 +80,8 @@ public class Test_HttpPlugin { .getHttpPlugin() .get("http://124.16.137.203:7080/cloudshare_web/home", null, - "header=Accept|value=text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8|;"); + "header=Accept|value=text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8|;", + null); assertEquals(200, homeReturn.getStatusCode()); logTheCookie("fourth"); } From 469c11d9e542c44a8f1cee25179f588c8d85f6e5 Mon Sep 17 00:00:00 2001 From: coderfengyun Date: Mon, 10 Mar 2014 13:48:26 +0800 Subject: [PATCH 156/196] add things about Parameterization --- .../agent/parameters/InstanceControler.java | 158 +++++++++++++++++ .../agent/parameters/MyFileClassLoader.java | 98 +++++++++++ .../bench4q/agent/parameters/Para_File.java | 15 ++ .../parameters/Para_GetEletronicCombine.java | 24 +++ .../agent/parameters/Para_IteratorNumber.java | 24 +++ .../agent/parameters/Para_RandomNumber.java | 28 +++ .../parameters/Para_UserNameAndPassword.java | 140 +++++++++++++++ .../agent/parameters/ParameterParser.java | 37 ++++ .../agent/parameters/ParametersFactor.java | 63 +++++++ .../agent/parameters/TEST_HelloThread.java | 56 ++++++ .../agent/parameters/TEST_UserName.java | 24 +++ .../agent/plugin/basic/http/HttpPlugin.java | 71 ++++---- .../plugin/basic/http/ParameterConstant.java | 20 +++ .../plugin/basic/http/ParameterParser.java | 113 ++++++------ .../agent/scenario/ScenarioEngine.java | 123 +------------ .../http => scenario}/SessionContext.java | 6 +- .../org/bench4q/agent/scenario/Worker.java | 166 ++++++++++++++++++ .../agent/scenario/behavior/Behavior.java | 131 +++++++------- .../scenario/utils/Test_ParameterParser.java | 50 ++++++ 19 files changed, 1084 insertions(+), 263 deletions(-) create mode 100644 src/main/java/org/bench4q/agent/parameters/InstanceControler.java create mode 100644 src/main/java/org/bench4q/agent/parameters/MyFileClassLoader.java create mode 100644 src/main/java/org/bench4q/agent/parameters/Para_File.java create mode 100644 src/main/java/org/bench4q/agent/parameters/Para_GetEletronicCombine.java create mode 100644 src/main/java/org/bench4q/agent/parameters/Para_IteratorNumber.java create mode 100644 src/main/java/org/bench4q/agent/parameters/Para_RandomNumber.java create mode 100644 src/main/java/org/bench4q/agent/parameters/Para_UserNameAndPassword.java create mode 100644 src/main/java/org/bench4q/agent/parameters/ParameterParser.java create mode 100644 src/main/java/org/bench4q/agent/parameters/ParametersFactor.java create mode 100644 src/main/java/org/bench4q/agent/parameters/TEST_HelloThread.java create mode 100644 src/main/java/org/bench4q/agent/parameters/TEST_UserName.java rename src/main/java/org/bench4q/agent/{plugin/basic/http => scenario}/SessionContext.java (79%) create mode 100644 src/main/java/org/bench4q/agent/scenario/Worker.java diff --git a/src/main/java/org/bench4q/agent/parameters/InstanceControler.java b/src/main/java/org/bench4q/agent/parameters/InstanceControler.java new file mode 100644 index 00000000..81f70a70 --- /dev/null +++ b/src/main/java/org/bench4q/agent/parameters/InstanceControler.java @@ -0,0 +1,158 @@ +package org.bench4q.agent.parameters; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.locks.ReentrantReadWriteLock; + +public class InstanceControler { + private UUID instandid = java.util.UUID.randomUUID(); + private Set usedClassName = new HashSet(); + private Map objMap = new HashMap(); + ReentrantReadWriteLock mapRWLock = new ReentrantReadWriteLock(); + + public String instanceLevelGetParameter(String className, + String functionName, Object[] args) { + + boolean hasThisClass = false; + mapRWLock.readLock().lock(); + hasThisClass = objMap.containsKey(className); + mapRWLock.readLock().unlock(); + if (false == hasThisClass) { + createObj(className); + } + Object instance = getObj(className); + Object result = null; + try { + Class[] argTypeArr = new Class[args.length + 1]; + argTypeArr[0] = instandid.getClass(); + Object[] totalArgs = new Object[args.length + 1]; + totalArgs[0] = instandid; + for (int i = 1; i < args.length; i++) { + argTypeArr[i] = args[i].getClass(); + totalArgs[i] = args[i - 1]; + } + + Method m = instance.getClass().getMethod(functionName, argTypeArr); + + result = m.invoke(instance, totalArgs); + + } catch (Exception ex) { + System.out.println(ex.getMessage() + ex.getStackTrace()); + System.out.println(((InvocationTargetException) ex) + .getTargetException().getMessage()); + return null; + } + return (String) result; + + } + + private String rootFilePath = "/home/yxsh/git/Bench4Q-Agent/parameterClass/"; + + public boolean createObj(String className) { + try { + MyFileClassLoader cl = new MyFileClassLoader(); + cl.setClassPath(rootFilePath); + Class cls = cl.loadClass(className); + Object instance = cls.newInstance(); + mapRWLock.writeLock().lock(); + objMap.put(className, instance); + + } catch (Exception ex) { + return false; + } + mapRWLock.writeLock().unlock(); + return true; + } + + public Object getObj(String className) { + Object result = null; + mapRWLock.readLock().lock(); + objMap.get(className); + mapRWLock.readLock().unlock(); + return result; + } + + public String getParameter(String className, String functionName, + Object[] args) { + + ParametersFactor pf = ParametersFactor.getInstance(); + boolean hasThisClass = pf.containObj(className); + if (false == hasThisClass) { + pf.createObj(className); + } + + Object instance = pf.getObj(className); + Object result = null; + try { + Class[] argTypeArr = new Class[args.length + 1]; + argTypeArr[0] = instandid.getClass(); + Object[] totalArgs = new Object[args.length + 1]; + totalArgs[0] = instandid; + for (int i = 1; i < args.length; i++) { + argTypeArr[i] = args[i].getClass(); + totalArgs[i] = args[i - 1]; + } + + Method m = instance.getClass().getMethod(functionName, argTypeArr); + + result = m.invoke(instance, totalArgs); + + } catch (Exception ex) { + System.out.println(ex.getMessage() + ex.getStackTrace()); + System.out.println(((InvocationTargetException) ex) + .getTargetException().getMessage()); + return null; + } + + usedClassName.add(className); + return (String) result; + } + + public String getParameterByString(String text) { + if (!(text.startsWith(""))) + return text; + ParameterParser p = new ParameterParser(); + return p.parse(text, this); + } + + protected void finalize() { + // releaseAll(); + } + + public void releaseAll() { + for (String xx : usedClassName) { + release(xx); + } + } + + public void release(String className) { + ParametersFactor pf = ParametersFactor.getInstance(); + // for(String s: pf.objMap.keySet()) + // { + // System.out.println(s); + // } + boolean hasThisClass = pf.containObj(className); + if (false == hasThisClass) { + pf.createObj(className); + } + + Object instance = pf.getObj(className); + + try { + + Method m = instance.getClass().getMethod("unreg", + instandid.getClass()); + + m.invoke(instance, instandid); + + } catch (Exception ex) { + System.out.println("realse failed"); + } + + } +} diff --git a/src/main/java/org/bench4q/agent/parameters/MyFileClassLoader.java b/src/main/java/org/bench4q/agent/parameters/MyFileClassLoader.java new file mode 100644 index 00000000..8461eafc --- /dev/null +++ b/src/main/java/org/bench4q/agent/parameters/MyFileClassLoader.java @@ -0,0 +1,98 @@ +package org.bench4q.agent.parameters; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; + +public class MyFileClassLoader extends ClassLoader { + + private String classPath; + + public static void main(String[] args) throws ClassNotFoundException, + InstantiationException, IllegalAccessException, + IllegalArgumentException, InvocationTargetException { + MyFileClassLoader fileClsLoader = new MyFileClassLoader(); + fileClsLoader + .setClassPath("E:\\j2ee_proj\\skythink\\WebContent\\WEB-INF\\classes\\"); + Class cls = fileClsLoader + .loadClass("com.cmw.entity.sys.AccordionEntity"); + Object obj = cls.newInstance(); + Method[] mthds = cls.getMethods(); + for (Method mthd : mthds) { + String methodName = mthd.getName(); + System.out.println("mthd.name=" + methodName); + } + System.out.println("obj.class=" + obj.getClass().getName()); + System.out.println("obj.class=" + cls.getClassLoader().toString()); + System.out.println("obj.class=" + + cls.getClassLoader().getParent().toString()); + } + + /** + * ��������ַ��ָ����Ŀ¼�����࣬����������� + */ + @Override + protected Class findClass(String name) throws ClassNotFoundException { + byte[] classData = null; + try { + classData = loadClassData(name); + } catch (IOException e) { + e.printStackTrace(); + } + return super.defineClass(name, classData, 0, classData.length); + } + + /** + * ��������ַ������ byte ����� + * + * @param name + * �����ַ� ���磺 com.cmw.entity.SysEntity + * @return �������ļ� byte ����� + * @throws IOException + */ + private byte[] loadClassData(String name) throws IOException { + File file = getFile(name); + @SuppressWarnings("resource") + FileInputStream fis = new FileInputStream(file); + byte[] arrData = new byte[(int) file.length()]; + fis.read(arrData); + return arrData; + } + + /** + * ��������ַ���һ�� File ���� + * + * @param name + * �����ַ� + * @return File ���� + * @throws FileNotFoundException + */ + private File getFile(String name) throws FileNotFoundException { + File dir = new File(classPath); + if (!dir.exists()) + throw new FileNotFoundException(classPath + " Ŀ¼�����ڣ�"); + String _classPath = classPath.replaceAll("[\\\\]", "/"); + int offset = _classPath.lastIndexOf("/"); + name = name.replaceAll("[.]", "/"); + if (offset != -1 && offset < _classPath.length() - 1) { + _classPath += "/"; + } + _classPath += name + ".class"; + dir = new File(_classPath); + if (!dir.exists()) + throw new FileNotFoundException(dir + " �����ڣ�"); + return dir; + } + + public String getClassPath() { + return classPath; + } + + public void setClassPath(String classPath) { + this.classPath = classPath; + } + +} diff --git a/src/main/java/org/bench4q/agent/parameters/Para_File.java b/src/main/java/org/bench4q/agent/parameters/Para_File.java new file mode 100644 index 00000000..9f1a180d --- /dev/null +++ b/src/main/java/org/bench4q/agent/parameters/Para_File.java @@ -0,0 +1,15 @@ +package org.bench4q.agent.parameters; + +import java.io.BufferedReader; +import java.util.HashMap; +import java.util.Map; + +public class Para_File_InThread { + private Map readBuffer = new HashMap(); + + public getFromFile(UUID id, String fileName, String column, String firstData, String byNumber) + { + + } + +} diff --git a/src/main/java/org/bench4q/agent/parameters/Para_GetEletronicCombine.java b/src/main/java/org/bench4q/agent/parameters/Para_GetEletronicCombine.java new file mode 100644 index 00000000..118314cf --- /dev/null +++ b/src/main/java/org/bench4q/agent/parameters/Para_GetEletronicCombine.java @@ -0,0 +1,24 @@ +package org.bench4q.agent.parameters; + +import java.util.Date; +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.locks.ReentrantReadWriteLock; + +public class Para_GetEletronicCombine { + static Map useInstanceMap = new HashMap(); + Date currentTimeLoop = new Date("2014-01-01"); + long currentUser = 10001; + ReentrantReadWriteLock timeRWLock = new ReentrantReadWriteLock(); + public Para_GetEletronicCombine() + { + + } + + public String getBeginUser(UUID id) + { + return null; + } + +} diff --git a/src/main/java/org/bench4q/agent/parameters/Para_IteratorNumber.java b/src/main/java/org/bench4q/agent/parameters/Para_IteratorNumber.java new file mode 100644 index 00000000..d8337c90 --- /dev/null +++ b/src/main/java/org/bench4q/agent/parameters/Para_IteratorNumber.java @@ -0,0 +1,24 @@ +package org.bench4q.agent.parameters; + +import java.util.UUID; + +public class Para_IteratorNumber { + public Long iteratorNum = new Long(0); + + public String getIteratorNumber(UUID id) + { + long result = 0; + synchronized(iteratorNum) + { + iteratorNum++; + result = iteratorNum; + } + String ret = String.valueOf(result); + return ret; + } + + public void unreg(UUID id) + { + + } +} diff --git a/src/main/java/org/bench4q/agent/parameters/Para_RandomNumber.java b/src/main/java/org/bench4q/agent/parameters/Para_RandomNumber.java new file mode 100644 index 00000000..56c14d27 --- /dev/null +++ b/src/main/java/org/bench4q/agent/parameters/Para_RandomNumber.java @@ -0,0 +1,28 @@ +package org.bench4q.agent.parameters; + +import java.util.Random; +import java.util.UUID; + +public class Para_RandomNumber { + + public String getRandomIntegerNumber(UUID id,String begin, String end, String stringformat) + { + + Random r = new Random(); + int beginNum = Integer.parseInt(begin); + int endNum = Integer.parseInt(end); + + int result = r.nextInt(endNum-beginNum) +beginNum; + return String.format(stringformat,result); + } + + public String getRandomDouble(UUID id , String begin, String end , String stringformat) + { + Random r = new Random(); + double beginNum = Integer.parseInt(begin); + double endNum = Integer.parseInt(end); + + double result = r.nextDouble()*(endNum-beginNum) +beginNum; + return String.format(stringformat, result); + } +} diff --git a/src/main/java/org/bench4q/agent/parameters/Para_UserNameAndPassword.java b/src/main/java/org/bench4q/agent/parameters/Para_UserNameAndPassword.java new file mode 100644 index 00000000..db29da61 --- /dev/null +++ b/src/main/java/org/bench4q/agent/parameters/Para_UserNameAndPassword.java @@ -0,0 +1,140 @@ +package org.bench4q.agent.parameters; + +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.locks.ReentrantReadWriteLock; + +public class Para_UserNameAndPassword { + String [] Password = new String[]{"a","b","c","d","e"}; + String [] userName= new String[] {"http://www.baidu.com/","http://www.163.com/","http://baike.baidu.com/","http://zhidao.baidu.com/","http://www.sina.com.cn/"}; + UUID [] useUUID = new UUID[5]; + + Map posMap = new HashMap(); + ReentrantReadWriteLock mapRWLock = new ReentrantReadWriteLock(); + ReentrantReadWriteLock idposLock = new ReentrantReadWriteLock(); + public String getUserName(UUID id) + { + mapRWLock.readLock().lock(); + if(posMap.containsKey(id)) + { + mapRWLock.readLock().unlock(); + return userName[posMap.get(id)]; + } + mapRWLock.readLock().unlock(); + + int vaildPos = -1; + int tryNum =0; + while(vaildPos < 0 && tryNum < 100) + { + tryNum++; + idposLock.readLock().lock(); + for(int i =0 ; i < 5;i++) + { + + if(useUUID[i] == null) + { + vaildPos = i; + break; + } + } + idposLock.readLock().unlock(); + if(vaildPos < 0) + { + try + { + Thread.currentThread().sleep(1000); + } + catch(Exception ex) + { + + } + } + } + + idposLock.writeLock().lock(); + useUUID[vaildPos] = id; + idposLock.writeLock().unlock(); + mapRWLock.writeLock().lock(); + posMap.put(id, vaildPos); + mapRWLock.writeLock().unlock(); + return userName[vaildPos]; + } + + public String getPassword(UUID id) + { + mapRWLock.readLock().lock(); + if(posMap.containsKey(id)) + { + mapRWLock.readLock().unlock(); + return Password[posMap.get(id)]; + } + mapRWLock.readLock().unlock(); + + int vaildPos = -1; + int tryNum =0; + while(vaildPos < 0 && tryNum < 100) + { + tryNum++; + idposLock.readLock().lock(); + for(int i =0 ; i < 5;i++) + { + + if(useUUID[i] == null) + { + vaildPos = i; + break; + } + } + idposLock.readLock().unlock(); + if(vaildPos < 0) + { + try + { + Thread.currentThread().sleep(1000); + } + catch(Exception ex) + { + + } + } + } + + idposLock.writeLock().lock(); + useUUID[vaildPos] = id; + idposLock.writeLock().unlock(); + mapRWLock.writeLock().lock(); + posMap.put(id, vaildPos); + mapRWLock.writeLock().unlock(); + return Password[vaildPos]; + } + + public void unreg(UUID id) + { + try + { + //System.out.println("1"); + mapRWLock.writeLock().lock(); + //System.out.println("2"); + int pos = posMap.get(id); + //System.out.println("3"); + posMap.remove(id); + //System.out.println("4"); + mapRWLock.writeLock().unlock(); + //System.out.println("5"); + idposLock.writeLock().lock(); + //System.out.println("6"); + useUUID[pos] = null; + idposLock.writeLock().unlock(); + } + catch(Exception ex) + { + System.out.println(ex.getClass().getName()); + System.out.println(ex.getMessage()); + System.out.println(ex.getStackTrace()); + mapRWLock.writeLock().unlock(); + idposLock.writeLock().unlock(); + } + } + +} diff --git a/src/main/java/org/bench4q/agent/parameters/ParameterParser.java b/src/main/java/org/bench4q/agent/parameters/ParameterParser.java new file mode 100644 index 00000000..8a95107c --- /dev/null +++ b/src/main/java/org/bench4q/agent/parameters/ParameterParser.java @@ -0,0 +1,37 @@ +package org.bench4q.agent.parameters; + +import java.io.StringReader; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; + +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.xml.sax.InputSource; + +public class ParameterParser { + + public String parse(String text, InstanceControler insCon) { + // Pattern pattern = Pattern.compile(""); + String result = ""; + + try { + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + DocumentBuilder db = dbf.newDocumentBuilder(); + Document document = db + .parse(new InputSource(new StringReader(text))); + Element root = document.getDocumentElement(); + String className = root.getAttribute("class"); + String methodName = root.getAttribute("method"); + String argString = root.getAttribute("args"); + + String[] args = argString.split(","); + if (argString.trim().equals("")) + args = new String[0]; + result = insCon.getParameter("org.bench4q.agent.parameters." + + className, methodName, args); + } catch (Exception ex) { + return text; + } + return result; + } +} diff --git a/src/main/java/org/bench4q/agent/parameters/ParametersFactor.java b/src/main/java/org/bench4q/agent/parameters/ParametersFactor.java new file mode 100644 index 00000000..afc87e07 --- /dev/null +++ b/src/main/java/org/bench4q/agent/parameters/ParametersFactor.java @@ -0,0 +1,63 @@ +package org.bench4q.agent.parameters; + +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.locks.ReentrantReadWriteLock; + +public class ParametersFactor { + private ParametersFactor() { + + }; + + static private ParametersFactor instance = null; + static String lockObj = ""; + + static public ParametersFactor getInstance() { + if (instance == null) { + synchronized (lockObj) { + if (instance == null) + instance = new ParametersFactor(); + } + } + return instance; + } + + private Map objMap = new HashMap(); + + public boolean containObj(String className) { + boolean ret = false; + mapRWLock.readLock().lock(); + ret = objMap.containsKey(className); + mapRWLock.readLock().unlock(); + return ret; + } + + public Object getObj(String className) { + Object result = null; + mapRWLock.readLock().lock(); + objMap.get(className); + mapRWLock.readLock().unlock(); + return result; + } + + private String rootFilePath = "/home/yxsh/git/Bench4Q-Agent/parameterClass/"; + + ReentrantReadWriteLock mapRWLock = new ReentrantReadWriteLock(); + + public boolean createObj(String className) { + try { + MyFileClassLoader cl = new MyFileClassLoader(); + cl.setClassPath(rootFilePath); + Class cls = cl.loadClass(className); + Object instance = cls.newInstance(); + mapRWLock.writeLock().lock(); + objMap.put(className, instance); + + } catch (Exception ex) { + + } + mapRWLock.writeLock().unlock(); + return true; + } + +} diff --git a/src/main/java/org/bench4q/agent/parameters/TEST_HelloThread.java b/src/main/java/org/bench4q/agent/parameters/TEST_HelloThread.java new file mode 100644 index 00000000..b370e9a1 --- /dev/null +++ b/src/main/java/org/bench4q/agent/parameters/TEST_HelloThread.java @@ -0,0 +1,56 @@ +package org.bench4q.agent.parameters; + +public class TEST_HelloThread extends Thread { + InstanceControler ic; + public TEST_HelloThread() { + ic = new InstanceControler(); + } + + + + public void run() { + java.util.Random r=new java.util.Random(); + int t = r.nextInt(10000); + System.out.print(Thread.currentThread().getId()); + System.out.println(":"+t); + try { + Thread.currentThread().sleep(t); + } catch (InterruptedException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + System.out.print(Thread.currentThread().getId()); + System.out.print("\t"); + + String userName = ic.getParameterByString(""); + String passwordName = ic.getParameterByString(""); + System.out.print(userName); + System.out.print("\t"); + System.out.println(passwordName); + try { + Thread.currentThread().sleep(r.nextInt(10000)); + } catch (InterruptedException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + ic.releaseAll(); + + } + + public static void main(String[] args) { + while(true) + { + TEST_HelloThread h1=new TEST_HelloThread(); + + h1.start(); + try { + Thread.currentThread().sleep(1000); + } catch (InterruptedException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + } + + private String name; +} diff --git a/src/main/java/org/bench4q/agent/parameters/TEST_UserName.java b/src/main/java/org/bench4q/agent/parameters/TEST_UserName.java new file mode 100644 index 00000000..1b31db4f --- /dev/null +++ b/src/main/java/org/bench4q/agent/parameters/TEST_UserName.java @@ -0,0 +1,24 @@ +package org.bench4q.agent.parameters; + +import java.util.UUID; + +public class TEST_UserName { + + public static void main(String[] args) { + // TODO Auto-generated method stub + // Para_UserNameAndPassword pp = new Para_UserNameAndPassword(); + // UUID temp = java.util.UUID.randomUUID(); + // pp.getUserName(temp); + InstanceControler ic = new InstanceControler(); + String userName = ic + .getParameterByString("!parameters class=\"Para_UserNameAndPassword\" method=\"getUserName\" args=\"\" !!"); + String passwordName = ic + .getParameterByString(""); + System.out.print(userName); + System.out.print("\t"); + System.out.println(passwordName); + // pp.unreg(temp); + ic.releaseAll(); + } + +} diff --git a/src/main/java/org/bench4q/agent/plugin/basic/http/HttpPlugin.java b/src/main/java/org/bench4q/agent/plugin/basic/http/HttpPlugin.java index b03738e1..fdb83012 100644 --- a/src/main/java/org/bench4q/agent/plugin/basic/http/HttpPlugin.java +++ b/src/main/java/org/bench4q/agent/plugin/basic/http/HttpPlugin.java @@ -33,7 +33,6 @@ import org.bench4q.agent.plugin.result.HttpReturn; @Plugin("Http") public class HttpPlugin { private HttpClient httpClient; - private SessionContext sessionContext; public HttpClient getHttpClient() { return httpClient; @@ -43,17 +42,8 @@ public class HttpPlugin { this.httpClient = httpClient; } - private SessionContext getSessionContext() { - return sessionContext; - } - - private void setSessionContext(SessionContext sessionContext) { - this.sessionContext = sessionContext; - } - public HttpPlugin() { this.setHttpClient(new HttpClient()); - this.setSessionContext(new SessionContext()); } void setHeaders(HttpMethod method, String headers) { @@ -97,25 +87,38 @@ public class HttpPlugin { return uri; } + /** + * + * @param url + * @param queryParams + * (List) QueryParams should be split by ';' + * @param headers + * (List)headers should be split by '|;', and in a header key and + * value are split by '|' + * + * @param respVarsToSaveInSession + * (List) should be split by '#!', and in a respVar, the key and + * Regular Expression should be split by '#' + * @return + */ @Behavior("Get") public HttpReturn get(@Parameter("url") String url, @Parameter("queryParams") String queryParams, @Parameter("headers") String headers, - @Parameter("respVarToSaveInSession") String respVarToSaveInSession) { - // QueryParams should be split by ';' - // headers should be split by '|;' + @Parameter("respVarsToSaveInSession") String respVarsToSaveInSession) { + GetMethod method = new GetMethod(completeUri(url)); - if (isValidString(queryParams)) { + if (isValid(queryParams)) { method.setQueryString(queryParams); } setHeaders(method, headers); method.getParams().makeLenient(); method.setFollowRedirects(false); - return excuteMethod(method, respVarToSaveInSession); + return excuteMethod(method, respVarsToSaveInSession); } private HttpReturn excuteMethod(HttpMethod method, - String respVarToSaveInSession) { + String respVarsToSaveInSession) { int responseCode = -1; long contentLength = 0; String contentType = ""; @@ -135,11 +138,14 @@ public class HttpPlugin { setCookies(method.getRequestHeader("Set-Cookie"), method .getURI().getHost() + ":" + method.getURI().getPort()); } - if (respVarToSaveInSession != null - && !respVarToSaveInSession.isEmpty()) { - // TODO:Now i just save all the responseBody - this.getSessionContext().addAVariable(respVarToSaveInSession, + if (isValid(respVarsToSaveInSession)) { + doExtractResponseVariables(respVarsToSaveInSession, method.getResponseBodyAsString()); + List respVars = ParameterParser + .parseResponseVariables(respVarsToSaveInSession); + + // this.getSessionContext().addAVariable(respVarsToSaveInSession, + // method.getResponseBodyAsString()); } return new HttpReturn(responseCode > 0, responseCode, contentLength, contentType, responseHeaders); @@ -154,6 +160,11 @@ public class HttpPlugin { } } + private void doExtractResponseVariables(String respVarsToSaveInSession, + String responseBodyAsString) { + + } + private void setCookies(Header requestHeader, String domain) { } @@ -174,19 +185,19 @@ public class HttpPlugin { @Parameter("headers") String headers, @Parameter("bodyContent") String bodyContent, @Parameter("bodyparameters") String bodyParams, - @Parameter("respVarToSaveInSession") String respVarToSaveInSession) { + @Parameter("respVarsToSaveInSession") String respVarToSaveInSession) { PostMethod method = new PostMethod(completeUri(url)); setHeaders(method, headers); - if (isValidString(queryParams)) { + if (isValid(queryParams)) { method.setQueryString(setInputParameters(ParameterParser .getNField(queryParams))); } - if (isValidString(bodyParams)) { + if (isValid(bodyParams)) { method.setRequestBody(setInputParameters(ParameterParser .getNField(bodyParams))); } String contentType = getMethodContentType(method); - if (isValidString(bodyContent) && isValidString(contentType)) { + if (isValid(bodyContent) && isValid(contentType)) { try { method.setRequestEntity(new StringRequestEntity(bodyContent, contentType, null)); @@ -209,7 +220,7 @@ public class HttpPlugin { return contentType; } - private boolean isValidString(String content) { + private boolean isValid(String content) { return content != null && content.length() != 0; } @@ -219,15 +230,15 @@ public class HttpPlugin { @Parameter("headers") String headers, @Parameter("bodyContent") String bodyContent, @Parameter("bodyparameters") String bodyParams, - @Parameter("respVarToSaveInSession") String respVarToSaveInSession) { + @Parameter("respVarsToSaveInSession") String respVarToSaveInSession) { PutMethod method = new PutMethod(completeUri(url)); setHeaders(method, headers); - if (isValidString(queryParams)) { + if (isValid(queryParams)) { method.setQueryString(setInputParameters(ParameterParser .getNField(queryParams))); } String contentType = getMethodContentType(method); - if (isValidString(bodyContent) && isValidString(contentType)) { + if (isValid(bodyContent) && isValid(contentType)) { try { method.setRequestEntity(new StringRequestEntity(bodyContent, contentType, null)); @@ -243,10 +254,10 @@ public class HttpPlugin { public HttpReturn delete(@Parameter("url") String url, @Parameter("queryParams") String queryParams, @Parameter("headers") String headers, - @Parameter("respVarToSaveInSession") String respVarToSaveInSession) { + @Parameter("respVarsToSaveInSession") String respVarToSaveInSession) { DeleteMethod method = new DeleteMethod(completeUri(url)); setHeaders(method, headers); - if (isValidString(queryParams)) { + if (isValid(queryParams)) { method.setQueryString(setInputParameters(ParameterParser .getNField(queryParams))); } diff --git a/src/main/java/org/bench4q/agent/plugin/basic/http/ParameterConstant.java b/src/main/java/org/bench4q/agent/plugin/basic/http/ParameterConstant.java index fbbe8a60..9bd8ceb8 100644 --- a/src/main/java/org/bench4q/agent/plugin/basic/http/ParameterConstant.java +++ b/src/main/java/org/bench4q/agent/plugin/basic/http/ParameterConstant.java @@ -3,4 +3,24 @@ package org.bench4q.agent.plugin.basic.http; public class ParameterConstant { public static final String HEADER_VALUE_SIGN = "value="; public static final String HEADER_NAME_SIGN = "header="; + + public static final String RESP_VAR_NAMW = "varName="; + public static final String RESP_VAR_REGX = "varReg="; + + public static final String escape = "\\"; + /** + * About table + */ + public static final String TABLE_SEPARATOR = "|;"; + public static final String TABLE_ENTRY_SEPARATOR = "|"; + public static final String TABLE_SEPARATOR_TAIL = ";"; + + public static final String ESCAPE_TABLE_SEPARATOR = escape + + TABLE_SEPARATOR; + public static final String ESCAPE_TABLE_ENTRY_SEPARATOR = escape + + TABLE_ENTRY_SEPARATOR; + + /** + * + */ } diff --git a/src/main/java/org/bench4q/agent/plugin/basic/http/ParameterParser.java b/src/main/java/org/bench4q/agent/plugin/basic/http/ParameterParser.java index 3818297c..aa836d3a 100644 --- a/src/main/java/org/bench4q/agent/plugin/basic/http/ParameterParser.java +++ b/src/main/java/org/bench4q/agent/plugin/basic/http/ParameterParser.java @@ -25,7 +25,7 @@ public abstract class ParameterParser { } static public String getRadioGroup(String value) { - List realTokens = getRealTokens(";", value); + List realTokens = getRealTokens(";", value, false); if (realTokens.size() == 0) { return ""; } else { @@ -43,14 +43,24 @@ public abstract class ParameterParser { static public List parseHeaders(String value) { List nvPairs = new LinkedList(); - String[] entrys = value.split("\\|;"); - - for (String entry : entrys) { - String[] nv = entry.split("\\|"); - if (nv.length != 2) { + for (List entry : getTable(value)) { + if (entry.size() != 2) { + continue; + } + nvPairs.add(distillHeader(entry.get(0).trim(), entry.get(1).trim())); + } + return nvPairs; + } + + public static List parseResponseVariables(String value) { + List nvPairs = new LinkedList(); + String[] entrys = value.split("#!"); + + for (String entry : entrys) { + String[] nv = entry.split("#"); + if (nv.length <= 1) { continue; } - ; nvPairs.add(distillHeader(nv[0].trim(), nv[1].trim())); } return nvPairs; @@ -88,12 +98,16 @@ public abstract class ParameterParser { */ static public List> getTable(String value) { List> result = new ArrayList>(); - List tempEntries = getRealTokens("|;", value); + List tempEntries = getRealTokens( + ParameterConstant.ESCAPE_TABLE_SEPARATOR, value, false); // now analyze all entries values, and get the '|' separator List> allValues = new ArrayList>(); for (int i = 0; i < tempEntries.size(); i++) { String tempEntry = tempEntries.get(i); - List values = getRealTokens("|", tempEntry); + List values = getRealTokens( + ParameterConstant.ESCAPE_TABLE_ENTRY_SEPARATOR, tempEntry, + true); + arrangeTheTableChildSeparator(values); allValues.add(values); } // now analyze all values, and get the '=' separator @@ -102,21 +116,40 @@ public abstract class ParameterParser { List tempValues = allValues.get(i); for (int j = 0; j < tempValues.size(); j++) { String v = tempValues.get(j); - List temp = getRealTokens("=", v); + List temp = getRealTokens("=", v, false); String res; - if (temp.size() > 1) { - res = temp.get(1); - } else { - res = ""; + if (temp.size() <= 1) { + continue; } + res = temp.get(1); res = unescape(res); resultValues.add(res); + } result.add(resultValues); } return result; } + /** + * This method check if the table_separator after escape is split by the + * table_entry_separator + * + * @param values + */ + private static void arrangeTheTableChildSeparator(List values) { + for (int i = 0; i < values.size(); i++) { + + String currentToken = values.get(i); + if (currentToken.equals(ParameterConstant.TABLE_SEPARATOR_TAIL) + && i > 0) { + values.set(i - 1, values.get(i - 1) + + ParameterConstant.TABLE_SEPARATOR_TAIL); + } + } + + } + /** * Get the number of escape character in the end of the string * @@ -124,10 +157,10 @@ public abstract class ParameterParser { * The string to be analyzed * @return 0 if no escape character was found, else the number */ - static private int getNumberOfEscapeCharacter(String value) { + public static int getNumberOfEscapeCharacter(String value) { int result = 0; if (value.length() > 0) { - int last = value.lastIndexOf("\\"); + int last = value.lastIndexOf(ParameterConstant.escape); if (last == value.length() - 1) { result = 1 + getNumberOfEscapeCharacter(value .substring(0, last)); @@ -151,7 +184,7 @@ public abstract class ParameterParser { while (st.hasMoreTokens()) { String token = st.nextToken(); if (token.equals(separator)) { - result = result.concat("\\" + token); + result = result.concat(ParameterConstant.escape + token); } else { result = result.concat(token); } @@ -169,43 +202,19 @@ public abstract class ParameterParser { * The string value to be split * @return The vector containing each token */ - static public List getRealTokens(String separator, String value) { + static public List getRealTokens(String separator, String value, + boolean toUnescape) { List result = new ArrayList(); - if (value != null) { - StringTokenizer st = new StringTokenizer(value, separator, true); - String currentRealToken = ""; - while (st.hasMoreTokens()) { - String token = st.nextToken(); - // the token is the separator - if (token.equals(separator)) { - int nb = getNumberOfEscapeCharacter(currentRealToken); - // if nb is even, we don't have any escape character - if (nb % 2 == 0) { - result.add(currentRealToken); - currentRealToken = ""; - } - // nb is odd - else { - // remove the escape character - currentRealToken = currentRealToken.substring(0, - currentRealToken.length() - 1); - // add the separator character - currentRealToken = currentRealToken.concat(separator); - // if it's the last token add it to the result - if (!st.hasMoreTokens()) { - result.add(currentRealToken); - } - } - } - // the token is a string - else { - currentRealToken = currentRealToken.concat(token); - // if it's the last token add it to the result - if (!st.hasMoreTokens()) { - result.add(currentRealToken); - } + for (String entry : value.split(separator)) { + if (getNumberOfEscapeCharacter(entry) % 2 != 0) { + if (toUnescape) { + entry = entry.substring(0, entry.length() - 1) + + unescape(separator); + } else { + entry = entry.substring(0, entry.length() - 1) + separator; } } + result.add(entry); } return result; } @@ -227,7 +236,7 @@ public abstract class ParameterParser { result.append(c); escape = false; } else { - if (c == '\\') { + if (c == ParameterConstant.escape.charAt(0)) { escape = true; } else { result.append(c); diff --git a/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java b/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java index e97a5c5c..662fcfc4 100644 --- a/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java +++ b/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java @@ -1,9 +1,6 @@ package org.bench4q.agent.scenario; -import java.util.ArrayList; -import java.util.Date; import java.util.HashMap; -import java.util.List; import java.util.Map; import java.util.UUID; import java.util.concurrent.ExecutorService; @@ -14,12 +11,6 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.ThreadPoolExecutor.DiscardPolicy; import org.apache.log4j.Logger; -import org.bench4q.agent.datacollector.interfaces.DataCollector; -import org.bench4q.agent.plugin.Plugin; -import org.bench4q.agent.plugin.PluginManager; -import org.bench4q.agent.plugin.result.HttpReturn; -import org.bench4q.agent.plugin.result.PluginReturn; -import org.bench4q.agent.scenario.behavior.Behavior; import org.bench4q.agent.storage.StorageHelper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @@ -27,7 +18,6 @@ import org.springframework.stereotype.Component; @Component public class ScenarioEngine { private static final long keepAliveTime = 10; - private PluginManager pluginManager; private Map runningTests; private StorageHelper storageHelper; private Logger logger; @@ -46,15 +36,6 @@ public class ScenarioEngine { this.setLogger(Logger.getLogger(ScenarioEngine.class)); } - private PluginManager getPluginManager() { - return pluginManager; - } - - @Autowired - private void setPluginManager(PluginManager pluginManager) { - this.pluginManager = pluginManager; - } - public StorageHelper getStorageHelper() { return storageHelper; } @@ -91,113 +72,15 @@ public class ScenarioEngine { private void executeTasks(final ScenarioContext scenarioContext) { ExecutorService taskMaker = Executors.newSingleThreadExecutor(); + taskMaker.execute(new Runnable() { public void run() { while (!scenarioContext.isFinished()) { - scenarioContext.getExecutor().execute(new Runnable() { - public void run() { - doRunScenario(scenarioContext); - logger.info("end for once!"); - } - }); + scenarioContext.getExecutor().execute( + new Worker(scenarioContext)); } } }); } - public void doRunScenario(ScenarioContext context) { - Map plugins = new HashMap(); - preparePlugins(context.getScenario(), plugins); - for (int i = 0; i < context.getScenario().getPages().length; i++) { - Page page = context.getScenario().getPages()[i]; - context.getDataStatistics().add( - PageResult.buildPageResult( - i, - doRunBatchesInPage(plugins, page, - context.getDataStatistics()))); - } - } - - private List doRunBatchesInPage( - Map plugins, Page page, DataCollector dataCollector) { - List results = new ArrayList(); - for (Batch batch : page.getBatches()) { - results.addAll(doRunBatch(plugins, batch, dataCollector)); - } - return results; - } - - private List doRunBatch(Map plugins, - Batch batch, DataCollector dataCollector) { - List results = new ArrayList(); - for (Behavior behavior : batch.getBehaviors()) { - Object plugin = plugins.get(behavior.getUse()); - Map behaviorParameters = prepareBehaviorParameters(behavior); - Date startDate = new Date(System.currentTimeMillis()); - PluginReturn pluginReturn = (PluginReturn) this.getPluginManager() - .doBehavior(plugin, behavior.getName(), behaviorParameters); - Date endDate = new Date(System.currentTimeMillis()); - if (!behavior.shouldBeCountResponseTime()) { - continue; - } - BehaviorResult behaviorResult = buildBehaviorResult(behavior, - plugin, startDate, pluginReturn, endDate); - dataCollector.add(behaviorResult); - results.add(behaviorResult); - } - return results; - } - - private BehaviorResult buildBehaviorResult(Behavior behavior, - Object plugin, Date startDate, PluginReturn pluginReturn, - Date endDate) { - BehaviorResult result = new BehaviorResult(); - result.setStartDate(startDate); - result.setEndDate(endDate); - result.setSuccess(pluginReturn.isSuccess()); - result.setResponseTime(endDate.getTime() - startDate.getTime()); - result.setBehaviorName(behavior.getName()); - result.setPluginId(behavior.getUse()); - result.setPluginName(plugin.getClass().getAnnotation(Plugin.class) - .value()); - result.setShouldBeCountResponseTime(behavior - .shouldBeCountResponseTime()); - if (pluginReturn instanceof HttpReturn) { - HttpReturn httpReturn = (HttpReturn) pluginReturn; - result.setBehaviorId(behavior.getId()); - for (Parameter parameter : behavior.getParameters()) { - if (parameter.getKey().equals("url")) { - result.setBehaviorUrl(parameter.getValue()); - } - } - result.setContentLength(httpReturn.getContentLength()); - result.setContentType(httpReturn.getContentType()); - result.setStatusCode(httpReturn.getStatusCode()); - } - return result; - } - - private Map prepareBehaviorParameters(Behavior behavior) { - Map behaviorParameters = new HashMap(); - for (Parameter parameter : behavior.getParameters()) { - behaviorParameters.put(parameter.getKey(), parameter.getValue()); - } - return behaviorParameters; - } - - private void preparePlugins(Scenario scenario, Map plugins) { - for (UsePlugin usePlugin : scenario.getUsePlugins()) { - String pluginId = usePlugin.getId(); - Class pluginClass = this.getPluginManager().getPlugins() - .get(usePlugin.getName()); - Map initParameters = new HashMap(); - for (Parameter parameter : usePlugin.getParameters()) { - initParameters.put(parameter.getKey(), parameter.getValue()); - } - Object plugin = this.getPluginManager().initializePlugin( - pluginClass, initParameters); - plugins.put(pluginId, plugin); - } - } - } diff --git a/src/main/java/org/bench4q/agent/plugin/basic/http/SessionContext.java b/src/main/java/org/bench4q/agent/scenario/SessionContext.java similarity index 79% rename from src/main/java/org/bench4q/agent/plugin/basic/http/SessionContext.java rename to src/main/java/org/bench4q/agent/scenario/SessionContext.java index c96cc7b4..ac9813bf 100644 --- a/src/main/java/org/bench4q/agent/plugin/basic/http/SessionContext.java +++ b/src/main/java/org/bench4q/agent/scenario/SessionContext.java @@ -1,4 +1,4 @@ -package org.bench4q.agent.plugin.basic.http; +package org.bench4q.agent.scenario; import java.util.HashMap; import java.util.Map; @@ -21,4 +21,8 @@ public class SessionContext { public void addAVariable(String entryName, String entryValue) { this.getVariables().put(entryName, entryValue); } + + public String getVariable(String entryName) { + return this.getVariable(entryName); + } } diff --git a/src/main/java/org/bench4q/agent/scenario/Worker.java b/src/main/java/org/bench4q/agent/scenario/Worker.java new file mode 100644 index 00000000..4df9c365 --- /dev/null +++ b/src/main/java/org/bench4q/agent/scenario/Worker.java @@ -0,0 +1,166 @@ +package org.bench4q.agent.scenario; + +import java.util.ArrayList; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.bench4q.agent.datacollector.interfaces.DataCollector; +import org.bench4q.agent.helper.ApplicationContextHelper; +import org.bench4q.agent.parameters.InstanceControler; +import org.bench4q.agent.plugin.Plugin; +import org.bench4q.agent.plugin.PluginManager; +import org.bench4q.agent.plugin.result.HttpReturn; +import org.bench4q.agent.plugin.result.PluginReturn; +import org.bench4q.agent.scenario.behavior.Behavior; + +public class Worker implements Runnable { + private ScenarioContext scenarioContext; + private InstanceControler ic; + + private PluginManager pluginManager; + + private ScenarioContext getScenarioContext() { + return scenarioContext; + } + + private void setScenarioContext(ScenarioContext scenarioContext) { + this.scenarioContext = scenarioContext; + } + + private InstanceControler getIc() { + return ic; + } + + private void setIc(InstanceControler ic) { + this.ic = ic; + } + + private PluginManager getPluginManager() { + return pluginManager; + } + + private void setPluginManager(PluginManager pluginManager) { + this.pluginManager = pluginManager; + } + + public Worker(ScenarioContext scenarioContext) { + this.setScenarioContext(scenarioContext); + this.setPluginManager(ApplicationContextHelper.getContext().getBean( + PluginManager.class)); + doPrepare(); + } + + private void doPrepare() { + this.setIc(new InstanceControler()); + } + + public void run() { + doRunScenario(getScenarioContext()); + doCleanUp(); + } + + private void doCleanUp() { + this.ic.releaseAll(); + } + + public void doRunScenario(ScenarioContext context) { + Map plugins = new HashMap(); + preparePlugins(context.getScenario(), plugins); + for (int i = 0; i < context.getScenario().getPages().length; i++) { + Page page = context.getScenario().getPages()[i]; + context.getDataStatistics().add( + PageResult.buildPageResult( + i, + doRunBatchesInPage(plugins, page, + context.getDataStatistics()))); + } + + } + + private List doRunBatchesInPage( + Map plugins, Page page, DataCollector dataCollector) { + List results = new ArrayList(); + for (Batch batch : page.getBatches()) { + results.addAll(doRunBatch(plugins, batch, dataCollector)); + } + return results; + } + + private List doRunBatch(Map plugins, + Batch batch, DataCollector dataCollector) { + List results = new ArrayList(); + for (Behavior behavior : batch.getBehaviors()) { + // each execution should call this + System.out.println("enter doRunBatch"); + behavior.distillParams(this.getIc()); + Object plugin = plugins.get(behavior.getUse()); + Map behaviorParameters = prepareBehaviorParameters(behavior); + Date startDate = new Date(System.currentTimeMillis()); + PluginReturn pluginReturn = (PluginReturn) this.getPluginManager() + .doBehavior(plugin, behavior.getName(), behaviorParameters); + Date endDate = new Date(System.currentTimeMillis()); + if (!behavior.shouldBeCountResponseTime()) { + continue; + } + BehaviorResult behaviorResult = buildBehaviorResult(behavior, + plugin, startDate, pluginReturn, endDate); + dataCollector.add(behaviorResult); + results.add(behaviorResult); + } + return results; + } + + private BehaviorResult buildBehaviorResult(Behavior behavior, + Object plugin, Date startDate, PluginReturn pluginReturn, + Date endDate) { + BehaviorResult result = new BehaviorResult(); + result.setStartDate(startDate); + result.setEndDate(endDate); + result.setSuccess(pluginReturn.isSuccess()); + result.setResponseTime(endDate.getTime() - startDate.getTime()); + result.setBehaviorName(behavior.getName()); + result.setPluginId(behavior.getUse()); + result.setPluginName(plugin.getClass().getAnnotation(Plugin.class) + .value()); + result.setShouldBeCountResponseTime(behavior + .shouldBeCountResponseTime()); + if (pluginReturn instanceof HttpReturn) { + HttpReturn httpReturn = (HttpReturn) pluginReturn; + result.setBehaviorId(behavior.getId()); + for (Parameter parameter : behavior.getParameters()) { + if (parameter.getKey().equals("url")) { + result.setBehaviorUrl(parameter.getValue()); + } + } + result.setContentLength(httpReturn.getContentLength()); + result.setContentType(httpReturn.getContentType()); + result.setStatusCode(httpReturn.getStatusCode()); + } + return result; + } + + private Map prepareBehaviorParameters(Behavior behavior) { + Map behaviorParameters = new HashMap(); + for (Parameter parameter : behavior.getParameters()) { + behaviorParameters.put(parameter.getKey(), parameter.getValue()); + } + return behaviorParameters; + } + + private void preparePlugins(Scenario scenario, Map plugins) { + for (UsePlugin usePlugin : scenario.getUsePlugins()) { + String pluginId = usePlugin.getId(); + Class pluginClass = this.getPluginManager().getPlugins() + .get(usePlugin.getName()); + Map initParameters = new HashMap(); + for (Parameter parameter : usePlugin.getParameters()) { + initParameters.put(parameter.getKey(), parameter.getValue()); + } + Object plugin = this.getPluginManager().initializePlugin( + pluginClass, initParameters); + plugins.put(pluginId, plugin); + } + } +} diff --git a/src/main/java/org/bench4q/agent/scenario/behavior/Behavior.java b/src/main/java/org/bench4q/agent/scenario/behavior/Behavior.java index 2cb07860..556feb23 100644 --- a/src/main/java/org/bench4q/agent/scenario/behavior/Behavior.java +++ b/src/main/java/org/bench4q/agent/scenario/behavior/Behavior.java @@ -1,60 +1,71 @@ -package org.bench4q.agent.scenario.behavior; - -import java.util.Map; - -import org.bench4q.agent.datacollector.impl.BehaviorStatusCodeResult; -import org.bench4q.agent.datacollector.interfaces.DataCollector; -import org.bench4q.agent.scenario.Parameter; - -public abstract class Behavior { - private int id; - private String use; - private String name; - private Parameter[] parameters; - - public int getId() { - return id; - } - - public void setId(int id) { - this.id = id; - } - - public String getUse() { - return use; - } - - public void setUse(String use) { - this.use = use; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public Parameter[] getParameters() { - return parameters; - } - - public void setParameters(Parameter[] parameters) { - this.parameters = parameters; - } - - public abstract boolean shouldBeCountResponseTime(); - - public abstract Map getBehaviorBriefResult( - DataCollector dataStatistics); - - public String getUrl() { - for (Parameter parameter : this.getParameters()) { - if (parameter.getKey().equals("url")) { - return parameter.getValue(); - } - } - return ""; - } -} +package org.bench4q.agent.scenario.behavior; + +import java.util.Map; + +import org.bench4q.agent.datacollector.impl.BehaviorStatusCodeResult; +import org.bench4q.agent.datacollector.interfaces.DataCollector; +import org.bench4q.agent.parameters.InstanceControler; +import org.bench4q.agent.scenario.Parameter; + +public abstract class Behavior { + private int id; + private String use; + private String name; + private Parameter[] parameters; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public String getUse() { + return use; + } + + public void setUse(String use) { + this.use = use; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Parameter[] getParameters() { + return parameters; + } + + public void setParameters(Parameter[] parameters) { + this.parameters = parameters; + } + + public abstract boolean shouldBeCountResponseTime(); + + public abstract Map getBehaviorBriefResult( + DataCollector dataStatistics); + + public String getUrl() { + for (Parameter parameter : this.getParameters()) { + if (parameter.getKey().equals("url")) { + return parameter.getValue(); + } + } + return ""; + } + + public void distillParams(InstanceControler instanceControler) { + for (Parameter parameter : this.getParameters()) { + String s = parameter.getValue(); + System.out.println("before Change :" + s); + String re = instanceControler.getParameterByString(s); + System.out.println("after Change : " + re); + parameter.setValue(re); + } + } +} diff --git a/src/test/java/org/bench4q/agent/test/scenario/utils/Test_ParameterParser.java b/src/test/java/org/bench4q/agent/test/scenario/utils/Test_ParameterParser.java index 8c6efeef..f9fbdea7 100644 --- a/src/test/java/org/bench4q/agent/test/scenario/utils/Test_ParameterParser.java +++ b/src/test/java/org/bench4q/agent/test/scenario/utils/Test_ParameterParser.java @@ -6,6 +6,7 @@ import java.util.ArrayList; import java.util.List; import org.apache.commons.httpclient.NameValuePair; +import org.bench4q.agent.plugin.basic.http.ParameterConstant; import org.bench4q.agent.plugin.basic.http.ParameterParser; import org.junit.Test; @@ -28,6 +29,50 @@ public class Test_ParameterParser { add("_nstm=0"); } }; + private static final String testcase1 = "header=accept|value=asdfasdf\\|;|;"; + private static final String testcase2 = "header=accept|value=fafsd|;varName=abc|varValue=234|;"; + + @Test + public void testGetNumberOfEscapeCharacter() { + assertEquals(3, "\\\\\\".length()); + assertEquals(2, ParameterParser.getNumberOfEscapeCharacter("\\\\")); + } + + @Test + public void testGetRealTokenForEscape() { + List entryList = ParameterParser.getRealTokens( + ParameterConstant.ESCAPE_TABLE_SEPARATOR, testcase1, true); + assertEquals(1, entryList.size()); + assertEquals("header=accept|value=asdfasdf|;", entryList.get(0)); + } + + @Test + public void testGetRealTokensForMultiSeparator() { + List entryList = ParameterParser.getRealTokens( + ParameterConstant.ESCAPE_TABLE_SEPARATOR, testcase2, false); + assertEquals(2, entryList.size()); + assertEquals("header=accept|value=fafsd", entryList.get(0)); + assertEquals("varName=abc|varValue=234", entryList.get(1)); + } + + @Test + public void testGetTableForSeparator() { + List> resultEntries = ParameterParser.getTable(testcase1); + assertEquals(1, resultEntries.size()); + assertEquals(2, resultEntries.get(0).size()); + assertEquals("accept", resultEntries.get(0).get(0)); + assertEquals("asdfasdf|;", resultEntries.get(0).get(1)); + } + + @Test + public void testGetTableForMultipleHeader() { + List> resultEntries = ParameterParser.getTable(testcase2); + assertEquals(2, resultEntries.size()); + assertEquals("fafsd", resultEntries.get(0).get(1)); + assertEquals("accept", resultEntries.get(0).get(0)); + assertEquals("234", resultEntries.get(1).get(1)); + assertEquals("abc", resultEntries.get(1).get(0)); + } @Test public void testParseParam() { @@ -67,4 +112,9 @@ public class Test_ParameterParser { assertEquals("text/html,application/xhtml+xml,application/xml", nvPairs .get(2).getValue()); } + + @Test + public void testParseResponseVariables() { + + } } From 86ec37cc2ae8fbeb388253ed24be51acb91a1ece Mon Sep 17 00:00:00 2001 From: coderfengyun Date: Mon, 10 Mar 2014 14:02:52 +0800 Subject: [PATCH 157/196] debug --- .../org/bench4q/agent/parameters/Para_File.java | 16 +++++++++------- .../parameters/Para_GetEletronicCombine.java | 16 ++++++++-------- 2 files changed, 17 insertions(+), 15 deletions(-) diff --git a/src/main/java/org/bench4q/agent/parameters/Para_File.java b/src/main/java/org/bench4q/agent/parameters/Para_File.java index 9f1a180d..a0de5490 100644 --- a/src/main/java/org/bench4q/agent/parameters/Para_File.java +++ b/src/main/java/org/bench4q/agent/parameters/Para_File.java @@ -3,13 +3,15 @@ package org.bench4q.agent.parameters; import java.io.BufferedReader; import java.util.HashMap; import java.util.Map; +import java.util.UUID; + +public class Para_File { + @SuppressWarnings("unused") + private Map readBuffer = new HashMap(); + + public void getFromFile(UUID id, String fileName, String column, + String firstData, String byNumber) { -public class Para_File_InThread { - private Map readBuffer = new HashMap(); - - public getFromFile(UUID id, String fileName, String column, String firstData, String byNumber) - { - } - + } diff --git a/src/main/java/org/bench4q/agent/parameters/Para_GetEletronicCombine.java b/src/main/java/org/bench4q/agent/parameters/Para_GetEletronicCombine.java index 118314cf..331a49f7 100644 --- a/src/main/java/org/bench4q/agent/parameters/Para_GetEletronicCombine.java +++ b/src/main/java/org/bench4q/agent/parameters/Para_GetEletronicCombine.java @@ -7,18 +7,18 @@ import java.util.UUID; import java.util.concurrent.locks.ReentrantReadWriteLock; public class Para_GetEletronicCombine { - static Map useInstanceMap = new HashMap(); + static Map useInstanceMap = new HashMap(); + @SuppressWarnings("deprecation") Date currentTimeLoop = new Date("2014-01-01"); long currentUser = 10001; ReentrantReadWriteLock timeRWLock = new ReentrantReadWriteLock(); - public Para_GetEletronicCombine() - { - + + public Para_GetEletronicCombine() { + } - - public String getBeginUser(UUID id) - { + + public String getBeginUser(UUID id) { return null; } - + } From 19d86c9a5d812986a747cbfe1f4791d5ca7db945 Mon Sep 17 00:00:00 2001 From: coderfengyun Date: Mon, 10 Mar 2014 14:10:58 +0800 Subject: [PATCH 158/196] refactor and add a new Interface --- .../bench4q/agent/parameters/SessionObject.java | 8 ++++++++ .../parameters/{ => impl}/InstanceControler.java | 7 ++++--- .../parameters/{ => impl}/MyFileClassLoader.java | 2 +- .../agent/parameters/{ => impl}/Para_File.java | 2 +- .../{ => impl}/Para_GetEletronicCombine.java | 2 +- .../{ => impl}/Para_IteratorNumber.java | 2 +- .../parameters/{ => impl}/Para_RandomNumber.java | 2 +- .../{ => impl}/Para_UserNameAndPassword.java | 2 +- .../parameters/{ => impl}/ParameterParser.java | 2 +- .../ParametersFactory.java} | 16 +++++----------- .../parameters/{ => impl}/TEST_HelloThread.java | 2 +- .../parameters/{ => impl}/TEST_UserName.java | 2 +- .../java/org/bench4q/agent/scenario/Worker.java | 2 +- .../agent/scenario/behavior/Behavior.java | 2 +- 14 files changed, 28 insertions(+), 25 deletions(-) create mode 100644 src/main/java/org/bench4q/agent/parameters/SessionObject.java rename src/main/java/org/bench4q/agent/parameters/{ => impl}/InstanceControler.java (96%) rename src/main/java/org/bench4q/agent/parameters/{ => impl}/MyFileClassLoader.java (98%) rename src/main/java/org/bench4q/agent/parameters/{ => impl}/Para_File.java (89%) rename src/main/java/org/bench4q/agent/parameters/{ => impl}/Para_GetEletronicCombine.java (93%) rename src/main/java/org/bench4q/agent/parameters/{ => impl}/Para_IteratorNumber.java (88%) rename src/main/java/org/bench4q/agent/parameters/{ => impl}/Para_RandomNumber.java (94%) rename src/main/java/org/bench4q/agent/parameters/{ => impl}/Para_UserNameAndPassword.java (98%) rename src/main/java/org/bench4q/agent/parameters/{ => impl}/ParameterParser.java (96%) rename src/main/java/org/bench4q/agent/parameters/{ParametersFactor.java => impl/ParametersFactory.java} (77%) rename src/main/java/org/bench4q/agent/parameters/{ => impl}/TEST_HelloThread.java (97%) rename src/main/java/org/bench4q/agent/parameters/{ => impl}/TEST_UserName.java (94%) diff --git a/src/main/java/org/bench4q/agent/parameters/SessionObject.java b/src/main/java/org/bench4q/agent/parameters/SessionObject.java new file mode 100644 index 00000000..90880f44 --- /dev/null +++ b/src/main/java/org/bench4q/agent/parameters/SessionObject.java @@ -0,0 +1,8 @@ +package org.bench4q.agent.parameters; + +public interface SessionObject { + + public String getParam(String name); + + public void saveParam(String name, String value); +} diff --git a/src/main/java/org/bench4q/agent/parameters/InstanceControler.java b/src/main/java/org/bench4q/agent/parameters/impl/InstanceControler.java similarity index 96% rename from src/main/java/org/bench4q/agent/parameters/InstanceControler.java rename to src/main/java/org/bench4q/agent/parameters/impl/InstanceControler.java index 81f70a70..b5726222 100644 --- a/src/main/java/org/bench4q/agent/parameters/InstanceControler.java +++ b/src/main/java/org/bench4q/agent/parameters/impl/InstanceControler.java @@ -1,4 +1,4 @@ -package org.bench4q.agent.parameters; +package org.bench4q.agent.parameters.impl; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; @@ -13,6 +13,7 @@ public class InstanceControler { private UUID instandid = java.util.UUID.randomUUID(); private Set usedClassName = new HashSet(); private Map objMap = new HashMap(); + ReentrantReadWriteLock mapRWLock = new ReentrantReadWriteLock(); public String instanceLevelGetParameter(String className, @@ -80,7 +81,7 @@ public class InstanceControler { public String getParameter(String className, String functionName, Object[] args) { - ParametersFactor pf = ParametersFactor.getInstance(); + ParametersFactory pf = ParametersFactory.getInstance(); boolean hasThisClass = pf.containObj(className); if (false == hasThisClass) { pf.createObj(className); @@ -131,7 +132,7 @@ public class InstanceControler { } public void release(String className) { - ParametersFactor pf = ParametersFactor.getInstance(); + ParametersFactory pf = ParametersFactory.getInstance(); // for(String s: pf.objMap.keySet()) // { // System.out.println(s); diff --git a/src/main/java/org/bench4q/agent/parameters/MyFileClassLoader.java b/src/main/java/org/bench4q/agent/parameters/impl/MyFileClassLoader.java similarity index 98% rename from src/main/java/org/bench4q/agent/parameters/MyFileClassLoader.java rename to src/main/java/org/bench4q/agent/parameters/impl/MyFileClassLoader.java index 8461eafc..64ac1991 100644 --- a/src/main/java/org/bench4q/agent/parameters/MyFileClassLoader.java +++ b/src/main/java/org/bench4q/agent/parameters/impl/MyFileClassLoader.java @@ -1,4 +1,4 @@ -package org.bench4q.agent.parameters; +package org.bench4q.agent.parameters.impl; import java.io.File; import java.io.FileInputStream; diff --git a/src/main/java/org/bench4q/agent/parameters/Para_File.java b/src/main/java/org/bench4q/agent/parameters/impl/Para_File.java similarity index 89% rename from src/main/java/org/bench4q/agent/parameters/Para_File.java rename to src/main/java/org/bench4q/agent/parameters/impl/Para_File.java index a0de5490..897a19e2 100644 --- a/src/main/java/org/bench4q/agent/parameters/Para_File.java +++ b/src/main/java/org/bench4q/agent/parameters/impl/Para_File.java @@ -1,4 +1,4 @@ -package org.bench4q.agent.parameters; +package org.bench4q.agent.parameters.impl; import java.io.BufferedReader; import java.util.HashMap; diff --git a/src/main/java/org/bench4q/agent/parameters/Para_GetEletronicCombine.java b/src/main/java/org/bench4q/agent/parameters/impl/Para_GetEletronicCombine.java similarity index 93% rename from src/main/java/org/bench4q/agent/parameters/Para_GetEletronicCombine.java rename to src/main/java/org/bench4q/agent/parameters/impl/Para_GetEletronicCombine.java index 331a49f7..861fbdcd 100644 --- a/src/main/java/org/bench4q/agent/parameters/Para_GetEletronicCombine.java +++ b/src/main/java/org/bench4q/agent/parameters/impl/Para_GetEletronicCombine.java @@ -1,4 +1,4 @@ -package org.bench4q.agent.parameters; +package org.bench4q.agent.parameters.impl; import java.util.Date; import java.util.HashMap; diff --git a/src/main/java/org/bench4q/agent/parameters/Para_IteratorNumber.java b/src/main/java/org/bench4q/agent/parameters/impl/Para_IteratorNumber.java similarity index 88% rename from src/main/java/org/bench4q/agent/parameters/Para_IteratorNumber.java rename to src/main/java/org/bench4q/agent/parameters/impl/Para_IteratorNumber.java index d8337c90..07e77c5e 100644 --- a/src/main/java/org/bench4q/agent/parameters/Para_IteratorNumber.java +++ b/src/main/java/org/bench4q/agent/parameters/impl/Para_IteratorNumber.java @@ -1,4 +1,4 @@ -package org.bench4q.agent.parameters; +package org.bench4q.agent.parameters.impl; import java.util.UUID; diff --git a/src/main/java/org/bench4q/agent/parameters/Para_RandomNumber.java b/src/main/java/org/bench4q/agent/parameters/impl/Para_RandomNumber.java similarity index 94% rename from src/main/java/org/bench4q/agent/parameters/Para_RandomNumber.java rename to src/main/java/org/bench4q/agent/parameters/impl/Para_RandomNumber.java index 56c14d27..ce21e135 100644 --- a/src/main/java/org/bench4q/agent/parameters/Para_RandomNumber.java +++ b/src/main/java/org/bench4q/agent/parameters/impl/Para_RandomNumber.java @@ -1,4 +1,4 @@ -package org.bench4q.agent.parameters; +package org.bench4q.agent.parameters.impl; import java.util.Random; import java.util.UUID; diff --git a/src/main/java/org/bench4q/agent/parameters/Para_UserNameAndPassword.java b/src/main/java/org/bench4q/agent/parameters/impl/Para_UserNameAndPassword.java similarity index 98% rename from src/main/java/org/bench4q/agent/parameters/Para_UserNameAndPassword.java rename to src/main/java/org/bench4q/agent/parameters/impl/Para_UserNameAndPassword.java index db29da61..797ed2e8 100644 --- a/src/main/java/org/bench4q/agent/parameters/Para_UserNameAndPassword.java +++ b/src/main/java/org/bench4q/agent/parameters/impl/Para_UserNameAndPassword.java @@ -1,4 +1,4 @@ -package org.bench4q.agent.parameters; +package org.bench4q.agent.parameters.impl; import java.util.HashMap; import java.util.Map; diff --git a/src/main/java/org/bench4q/agent/parameters/ParameterParser.java b/src/main/java/org/bench4q/agent/parameters/impl/ParameterParser.java similarity index 96% rename from src/main/java/org/bench4q/agent/parameters/ParameterParser.java rename to src/main/java/org/bench4q/agent/parameters/impl/ParameterParser.java index 8a95107c..937b3b8d 100644 --- a/src/main/java/org/bench4q/agent/parameters/ParameterParser.java +++ b/src/main/java/org/bench4q/agent/parameters/impl/ParameterParser.java @@ -1,4 +1,4 @@ -package org.bench4q.agent.parameters; +package org.bench4q.agent.parameters.impl; import java.io.StringReader; import javax.xml.parsers.DocumentBuilder; diff --git a/src/main/java/org/bench4q/agent/parameters/ParametersFactor.java b/src/main/java/org/bench4q/agent/parameters/impl/ParametersFactory.java similarity index 77% rename from src/main/java/org/bench4q/agent/parameters/ParametersFactor.java rename to src/main/java/org/bench4q/agent/parameters/impl/ParametersFactory.java index afc87e07..b9ccdc1b 100644 --- a/src/main/java/org/bench4q/agent/parameters/ParametersFactor.java +++ b/src/main/java/org/bench4q/agent/parameters/impl/ParametersFactory.java @@ -1,24 +1,18 @@ -package org.bench4q.agent.parameters; +package org.bench4q.agent.parameters.impl; import java.util.HashMap; import java.util.Map; import java.util.concurrent.locks.ReentrantReadWriteLock; -public class ParametersFactor { - private ParametersFactor() { +public class ParametersFactory { + private ParametersFactory() { }; - static private ParametersFactor instance = null; + static private final ParametersFactory instance = new ParametersFactory(); static String lockObj = ""; - static public ParametersFactor getInstance() { - if (instance == null) { - synchronized (lockObj) { - if (instance == null) - instance = new ParametersFactor(); - } - } + static public ParametersFactory getInstance() { return instance; } diff --git a/src/main/java/org/bench4q/agent/parameters/TEST_HelloThread.java b/src/main/java/org/bench4q/agent/parameters/impl/TEST_HelloThread.java similarity index 97% rename from src/main/java/org/bench4q/agent/parameters/TEST_HelloThread.java rename to src/main/java/org/bench4q/agent/parameters/impl/TEST_HelloThread.java index b370e9a1..d123b5ed 100644 --- a/src/main/java/org/bench4q/agent/parameters/TEST_HelloThread.java +++ b/src/main/java/org/bench4q/agent/parameters/impl/TEST_HelloThread.java @@ -1,4 +1,4 @@ -package org.bench4q.agent.parameters; +package org.bench4q.agent.parameters.impl; public class TEST_HelloThread extends Thread { InstanceControler ic; diff --git a/src/main/java/org/bench4q/agent/parameters/TEST_UserName.java b/src/main/java/org/bench4q/agent/parameters/impl/TEST_UserName.java similarity index 94% rename from src/main/java/org/bench4q/agent/parameters/TEST_UserName.java rename to src/main/java/org/bench4q/agent/parameters/impl/TEST_UserName.java index 1b31db4f..bb40cd65 100644 --- a/src/main/java/org/bench4q/agent/parameters/TEST_UserName.java +++ b/src/main/java/org/bench4q/agent/parameters/impl/TEST_UserName.java @@ -1,4 +1,4 @@ -package org.bench4q.agent.parameters; +package org.bench4q.agent.parameters.impl; import java.util.UUID; diff --git a/src/main/java/org/bench4q/agent/scenario/Worker.java b/src/main/java/org/bench4q/agent/scenario/Worker.java index 4df9c365..79f23b50 100644 --- a/src/main/java/org/bench4q/agent/scenario/Worker.java +++ b/src/main/java/org/bench4q/agent/scenario/Worker.java @@ -8,7 +8,7 @@ import java.util.Map; import org.bench4q.agent.datacollector.interfaces.DataCollector; import org.bench4q.agent.helper.ApplicationContextHelper; -import org.bench4q.agent.parameters.InstanceControler; +import org.bench4q.agent.parameters.impl.InstanceControler; import org.bench4q.agent.plugin.Plugin; import org.bench4q.agent.plugin.PluginManager; import org.bench4q.agent.plugin.result.HttpReturn; diff --git a/src/main/java/org/bench4q/agent/scenario/behavior/Behavior.java b/src/main/java/org/bench4q/agent/scenario/behavior/Behavior.java index 556feb23..6cc78410 100644 --- a/src/main/java/org/bench4q/agent/scenario/behavior/Behavior.java +++ b/src/main/java/org/bench4q/agent/scenario/behavior/Behavior.java @@ -4,7 +4,7 @@ import java.util.Map; import org.bench4q.agent.datacollector.impl.BehaviorStatusCodeResult; import org.bench4q.agent.datacollector.interfaces.DataCollector; -import org.bench4q.agent.parameters.InstanceControler; +import org.bench4q.agent.parameters.impl.InstanceControler; import org.bench4q.agent.scenario.Parameter; public abstract class Behavior { From b37f979b34923d81d61271d47976a3739b215662 Mon Sep 17 00:00:00 2001 From: coderfengyun Date: Mon, 10 Mar 2014 14:11:53 +0800 Subject: [PATCH 159/196] change the package name --- .../agent/{parameters => parameterization}/SessionObject.java | 2 +- .../impl/InstanceControler.java | 2 +- .../impl/MyFileClassLoader.java | 2 +- .../agent/{parameters => parameterization}/impl/Para_File.java | 2 +- .../impl/Para_GetEletronicCombine.java | 2 +- .../impl/Para_IteratorNumber.java | 2 +- .../impl/Para_RandomNumber.java | 2 +- .../impl/Para_UserNameAndPassword.java | 2 +- .../{parameters => parameterization}/impl/ParameterParser.java | 2 +- .../impl/ParametersFactory.java | 2 +- .../{parameters => parameterization}/impl/TEST_HelloThread.java | 2 +- .../{parameters => parameterization}/impl/TEST_UserName.java | 2 +- src/main/java/org/bench4q/agent/scenario/Worker.java | 2 +- src/main/java/org/bench4q/agent/scenario/behavior/Behavior.java | 2 +- 14 files changed, 14 insertions(+), 14 deletions(-) rename src/main/java/org/bench4q/agent/{parameters => parameterization}/SessionObject.java (74%) rename src/main/java/org/bench4q/agent/{parameters => parameterization}/impl/InstanceControler.java (98%) rename src/main/java/org/bench4q/agent/{parameters => parameterization}/impl/MyFileClassLoader.java (98%) rename src/main/java/org/bench4q/agent/{parameters => parameterization}/impl/Para_File.java (88%) rename src/main/java/org/bench4q/agent/{parameters => parameterization}/impl/Para_GetEletronicCombine.java (92%) rename src/main/java/org/bench4q/agent/{parameters => parameterization}/impl/Para_IteratorNumber.java (87%) rename src/main/java/org/bench4q/agent/{parameters => parameterization}/impl/Para_RandomNumber.java (93%) rename src/main/java/org/bench4q/agent/{parameters => parameterization}/impl/Para_UserNameAndPassword.java (98%) rename src/main/java/org/bench4q/agent/{parameters => parameterization}/impl/ParameterParser.java (95%) rename src/main/java/org/bench4q/agent/{parameters => parameterization}/impl/ParametersFactory.java (96%) rename src/main/java/org/bench4q/agent/{parameters => parameterization}/impl/TEST_HelloThread.java (96%) rename src/main/java/org/bench4q/agent/{parameters => parameterization}/impl/TEST_UserName.java (93%) diff --git a/src/main/java/org/bench4q/agent/parameters/SessionObject.java b/src/main/java/org/bench4q/agent/parameterization/SessionObject.java similarity index 74% rename from src/main/java/org/bench4q/agent/parameters/SessionObject.java rename to src/main/java/org/bench4q/agent/parameterization/SessionObject.java index 90880f44..7ab8af91 100644 --- a/src/main/java/org/bench4q/agent/parameters/SessionObject.java +++ b/src/main/java/org/bench4q/agent/parameterization/SessionObject.java @@ -1,4 +1,4 @@ -package org.bench4q.agent.parameters; +package org.bench4q.agent.parameterization; public interface SessionObject { diff --git a/src/main/java/org/bench4q/agent/parameters/impl/InstanceControler.java b/src/main/java/org/bench4q/agent/parameterization/impl/InstanceControler.java similarity index 98% rename from src/main/java/org/bench4q/agent/parameters/impl/InstanceControler.java rename to src/main/java/org/bench4q/agent/parameterization/impl/InstanceControler.java index b5726222..fa9514c4 100644 --- a/src/main/java/org/bench4q/agent/parameters/impl/InstanceControler.java +++ b/src/main/java/org/bench4q/agent/parameterization/impl/InstanceControler.java @@ -1,4 +1,4 @@ -package org.bench4q.agent.parameters.impl; +package org.bench4q.agent.parameterization.impl; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; diff --git a/src/main/java/org/bench4q/agent/parameters/impl/MyFileClassLoader.java b/src/main/java/org/bench4q/agent/parameterization/impl/MyFileClassLoader.java similarity index 98% rename from src/main/java/org/bench4q/agent/parameters/impl/MyFileClassLoader.java rename to src/main/java/org/bench4q/agent/parameterization/impl/MyFileClassLoader.java index 64ac1991..44448d68 100644 --- a/src/main/java/org/bench4q/agent/parameters/impl/MyFileClassLoader.java +++ b/src/main/java/org/bench4q/agent/parameterization/impl/MyFileClassLoader.java @@ -1,4 +1,4 @@ -package org.bench4q.agent.parameters.impl; +package org.bench4q.agent.parameterization.impl; import java.io.File; import java.io.FileInputStream; diff --git a/src/main/java/org/bench4q/agent/parameters/impl/Para_File.java b/src/main/java/org/bench4q/agent/parameterization/impl/Para_File.java similarity index 88% rename from src/main/java/org/bench4q/agent/parameters/impl/Para_File.java rename to src/main/java/org/bench4q/agent/parameterization/impl/Para_File.java index 897a19e2..3cd4a1b9 100644 --- a/src/main/java/org/bench4q/agent/parameters/impl/Para_File.java +++ b/src/main/java/org/bench4q/agent/parameterization/impl/Para_File.java @@ -1,4 +1,4 @@ -package org.bench4q.agent.parameters.impl; +package org.bench4q.agent.parameterization.impl; import java.io.BufferedReader; import java.util.HashMap; diff --git a/src/main/java/org/bench4q/agent/parameters/impl/Para_GetEletronicCombine.java b/src/main/java/org/bench4q/agent/parameterization/impl/Para_GetEletronicCombine.java similarity index 92% rename from src/main/java/org/bench4q/agent/parameters/impl/Para_GetEletronicCombine.java rename to src/main/java/org/bench4q/agent/parameterization/impl/Para_GetEletronicCombine.java index 861fbdcd..9b557e61 100644 --- a/src/main/java/org/bench4q/agent/parameters/impl/Para_GetEletronicCombine.java +++ b/src/main/java/org/bench4q/agent/parameterization/impl/Para_GetEletronicCombine.java @@ -1,4 +1,4 @@ -package org.bench4q.agent.parameters.impl; +package org.bench4q.agent.parameterization.impl; import java.util.Date; import java.util.HashMap; diff --git a/src/main/java/org/bench4q/agent/parameters/impl/Para_IteratorNumber.java b/src/main/java/org/bench4q/agent/parameterization/impl/Para_IteratorNumber.java similarity index 87% rename from src/main/java/org/bench4q/agent/parameters/impl/Para_IteratorNumber.java rename to src/main/java/org/bench4q/agent/parameterization/impl/Para_IteratorNumber.java index 07e77c5e..a696f7d9 100644 --- a/src/main/java/org/bench4q/agent/parameters/impl/Para_IteratorNumber.java +++ b/src/main/java/org/bench4q/agent/parameterization/impl/Para_IteratorNumber.java @@ -1,4 +1,4 @@ -package org.bench4q.agent.parameters.impl; +package org.bench4q.agent.parameterization.impl; import java.util.UUID; diff --git a/src/main/java/org/bench4q/agent/parameters/impl/Para_RandomNumber.java b/src/main/java/org/bench4q/agent/parameterization/impl/Para_RandomNumber.java similarity index 93% rename from src/main/java/org/bench4q/agent/parameters/impl/Para_RandomNumber.java rename to src/main/java/org/bench4q/agent/parameterization/impl/Para_RandomNumber.java index ce21e135..f0b6f360 100644 --- a/src/main/java/org/bench4q/agent/parameters/impl/Para_RandomNumber.java +++ b/src/main/java/org/bench4q/agent/parameterization/impl/Para_RandomNumber.java @@ -1,4 +1,4 @@ -package org.bench4q.agent.parameters.impl; +package org.bench4q.agent.parameterization.impl; import java.util.Random; import java.util.UUID; diff --git a/src/main/java/org/bench4q/agent/parameters/impl/Para_UserNameAndPassword.java b/src/main/java/org/bench4q/agent/parameterization/impl/Para_UserNameAndPassword.java similarity index 98% rename from src/main/java/org/bench4q/agent/parameters/impl/Para_UserNameAndPassword.java rename to src/main/java/org/bench4q/agent/parameterization/impl/Para_UserNameAndPassword.java index 797ed2e8..b6dd4049 100644 --- a/src/main/java/org/bench4q/agent/parameters/impl/Para_UserNameAndPassword.java +++ b/src/main/java/org/bench4q/agent/parameterization/impl/Para_UserNameAndPassword.java @@ -1,4 +1,4 @@ -package org.bench4q.agent.parameters.impl; +package org.bench4q.agent.parameterization.impl; import java.util.HashMap; import java.util.Map; diff --git a/src/main/java/org/bench4q/agent/parameters/impl/ParameterParser.java b/src/main/java/org/bench4q/agent/parameterization/impl/ParameterParser.java similarity index 95% rename from src/main/java/org/bench4q/agent/parameters/impl/ParameterParser.java rename to src/main/java/org/bench4q/agent/parameterization/impl/ParameterParser.java index 937b3b8d..94723539 100644 --- a/src/main/java/org/bench4q/agent/parameters/impl/ParameterParser.java +++ b/src/main/java/org/bench4q/agent/parameterization/impl/ParameterParser.java @@ -1,4 +1,4 @@ -package org.bench4q.agent.parameters.impl; +package org.bench4q.agent.parameterization.impl; import java.io.StringReader; import javax.xml.parsers.DocumentBuilder; diff --git a/src/main/java/org/bench4q/agent/parameters/impl/ParametersFactory.java b/src/main/java/org/bench4q/agent/parameterization/impl/ParametersFactory.java similarity index 96% rename from src/main/java/org/bench4q/agent/parameters/impl/ParametersFactory.java rename to src/main/java/org/bench4q/agent/parameterization/impl/ParametersFactory.java index b9ccdc1b..4902a66d 100644 --- a/src/main/java/org/bench4q/agent/parameters/impl/ParametersFactory.java +++ b/src/main/java/org/bench4q/agent/parameterization/impl/ParametersFactory.java @@ -1,4 +1,4 @@ -package org.bench4q.agent.parameters.impl; +package org.bench4q.agent.parameterization.impl; import java.util.HashMap; import java.util.Map; diff --git a/src/main/java/org/bench4q/agent/parameters/impl/TEST_HelloThread.java b/src/main/java/org/bench4q/agent/parameterization/impl/TEST_HelloThread.java similarity index 96% rename from src/main/java/org/bench4q/agent/parameters/impl/TEST_HelloThread.java rename to src/main/java/org/bench4q/agent/parameterization/impl/TEST_HelloThread.java index d123b5ed..2410fb68 100644 --- a/src/main/java/org/bench4q/agent/parameters/impl/TEST_HelloThread.java +++ b/src/main/java/org/bench4q/agent/parameterization/impl/TEST_HelloThread.java @@ -1,4 +1,4 @@ -package org.bench4q.agent.parameters.impl; +package org.bench4q.agent.parameterization.impl; public class TEST_HelloThread extends Thread { InstanceControler ic; diff --git a/src/main/java/org/bench4q/agent/parameters/impl/TEST_UserName.java b/src/main/java/org/bench4q/agent/parameterization/impl/TEST_UserName.java similarity index 93% rename from src/main/java/org/bench4q/agent/parameters/impl/TEST_UserName.java rename to src/main/java/org/bench4q/agent/parameterization/impl/TEST_UserName.java index bb40cd65..2078e851 100644 --- a/src/main/java/org/bench4q/agent/parameters/impl/TEST_UserName.java +++ b/src/main/java/org/bench4q/agent/parameterization/impl/TEST_UserName.java @@ -1,4 +1,4 @@ -package org.bench4q.agent.parameters.impl; +package org.bench4q.agent.parameterization.impl; import java.util.UUID; diff --git a/src/main/java/org/bench4q/agent/scenario/Worker.java b/src/main/java/org/bench4q/agent/scenario/Worker.java index 79f23b50..04f0d3cf 100644 --- a/src/main/java/org/bench4q/agent/scenario/Worker.java +++ b/src/main/java/org/bench4q/agent/scenario/Worker.java @@ -8,7 +8,7 @@ import java.util.Map; import org.bench4q.agent.datacollector.interfaces.DataCollector; import org.bench4q.agent.helper.ApplicationContextHelper; -import org.bench4q.agent.parameters.impl.InstanceControler; +import org.bench4q.agent.parameterization.impl.InstanceControler; import org.bench4q.agent.plugin.Plugin; import org.bench4q.agent.plugin.PluginManager; import org.bench4q.agent.plugin.result.HttpReturn; diff --git a/src/main/java/org/bench4q/agent/scenario/behavior/Behavior.java b/src/main/java/org/bench4q/agent/scenario/behavior/Behavior.java index 6cc78410..c3f6845c 100644 --- a/src/main/java/org/bench4q/agent/scenario/behavior/Behavior.java +++ b/src/main/java/org/bench4q/agent/scenario/behavior/Behavior.java @@ -4,7 +4,7 @@ import java.util.Map; import org.bench4q.agent.datacollector.impl.BehaviorStatusCodeResult; import org.bench4q.agent.datacollector.interfaces.DataCollector; -import org.bench4q.agent.parameters.impl.InstanceControler; +import org.bench4q.agent.parameterization.impl.InstanceControler; import org.bench4q.agent.scenario.Parameter; public abstract class Behavior { From 774604ca1ef1333f186e5e9e9ffacb8c2e262bed Mon Sep 17 00:00:00 2001 From: coderfengyun Date: Mon, 10 Mar 2014 14:29:37 +0800 Subject: [PATCH 160/196] remove dependencies towards SessionObject --- .../agent/parameterization/SessionObject.java | 4 ++- .../impl/InstanceControler.java | 28 +++++++++++++++---- .../impl/TEST_HelloThread.java | 4 +-- .../parameterization/impl/TEST_UserName.java | 4 +-- .../org/bench4q/agent/scenario/Worker.java | 17 +++++------ .../agent/scenario/behavior/Behavior.java | 6 ++-- 6 files changed, 41 insertions(+), 22 deletions(-) diff --git a/src/main/java/org/bench4q/agent/parameterization/SessionObject.java b/src/main/java/org/bench4q/agent/parameterization/SessionObject.java index 7ab8af91..29cde272 100644 --- a/src/main/java/org/bench4q/agent/parameterization/SessionObject.java +++ b/src/main/java/org/bench4q/agent/parameterization/SessionObject.java @@ -4,5 +4,7 @@ public interface SessionObject { public String getParam(String name); - public void saveParam(String name, String value); + public void saveRuntimeParam(String name, String value); + + public void doCleanUp(); } diff --git a/src/main/java/org/bench4q/agent/parameterization/impl/InstanceControler.java b/src/main/java/org/bench4q/agent/parameterization/impl/InstanceControler.java index fa9514c4..056f6eb2 100644 --- a/src/main/java/org/bench4q/agent/parameterization/impl/InstanceControler.java +++ b/src/main/java/org/bench4q/agent/parameterization/impl/InstanceControler.java @@ -9,11 +9,13 @@ import java.util.Set; import java.util.UUID; import java.util.concurrent.locks.ReentrantReadWriteLock; -public class InstanceControler { +import org.bench4q.agent.parameterization.SessionObject; + +public class InstanceControler implements SessionObject { private UUID instandid = java.util.UUID.randomUUID(); private Set usedClassName = new HashSet(); private Map objMap = new HashMap(); - + ReentrantReadWriteLock mapRWLock = new ReentrantReadWriteLock(); public String instanceLevelGetParameter(String className, @@ -114,13 +116,27 @@ public class InstanceControler { return (String) result; } - public String getParameterByString(String text) { - if (!(text.startsWith(""))) - return text; + /** + * Implement SessionObject start + */ + public String getParam(String name) { + if (!(name.startsWith(""))) + return name; ParameterParser p = new ParameterParser(); - return p.parse(text, this); + return p.parse(name, this); } + public void saveRuntimeParam(String name, String value) { + + } + + public void doCleanUp() { + this.releaseAll(); + } + + /** + * Implement SessionObject end + */ protected void finalize() { // releaseAll(); } diff --git a/src/main/java/org/bench4q/agent/parameterization/impl/TEST_HelloThread.java b/src/main/java/org/bench4q/agent/parameterization/impl/TEST_HelloThread.java index 2410fb68..2108f37c 100644 --- a/src/main/java/org/bench4q/agent/parameterization/impl/TEST_HelloThread.java +++ b/src/main/java/org/bench4q/agent/parameterization/impl/TEST_HelloThread.java @@ -22,8 +22,8 @@ public class TEST_HelloThread extends Thread { System.out.print(Thread.currentThread().getId()); System.out.print("\t"); - String userName = ic.getParameterByString(""); - String passwordName = ic.getParameterByString(""); + String userName = ic.getParam(""); + String passwordName = ic.getParam(""); System.out.print(userName); System.out.print("\t"); System.out.println(passwordName); diff --git a/src/main/java/org/bench4q/agent/parameterization/impl/TEST_UserName.java b/src/main/java/org/bench4q/agent/parameterization/impl/TEST_UserName.java index 2078e851..e92de731 100644 --- a/src/main/java/org/bench4q/agent/parameterization/impl/TEST_UserName.java +++ b/src/main/java/org/bench4q/agent/parameterization/impl/TEST_UserName.java @@ -11,9 +11,9 @@ public class TEST_UserName { // pp.getUserName(temp); InstanceControler ic = new InstanceControler(); String userName = ic - .getParameterByString("!parameters class=\"Para_UserNameAndPassword\" method=\"getUserName\" args=\"\" !!"); + .getParam("!parameters class=\"Para_UserNameAndPassword\" method=\"getUserName\" args=\"\" !!"); String passwordName = ic - .getParameterByString(""); + .getParam(""); System.out.print(userName); System.out.print("\t"); System.out.println(passwordName); diff --git a/src/main/java/org/bench4q/agent/scenario/Worker.java b/src/main/java/org/bench4q/agent/scenario/Worker.java index 04f0d3cf..e4dfc522 100644 --- a/src/main/java/org/bench4q/agent/scenario/Worker.java +++ b/src/main/java/org/bench4q/agent/scenario/Worker.java @@ -8,6 +8,7 @@ import java.util.Map; import org.bench4q.agent.datacollector.interfaces.DataCollector; import org.bench4q.agent.helper.ApplicationContextHelper; +import org.bench4q.agent.parameterization.SessionObject; import org.bench4q.agent.parameterization.impl.InstanceControler; import org.bench4q.agent.plugin.Plugin; import org.bench4q.agent.plugin.PluginManager; @@ -17,7 +18,7 @@ import org.bench4q.agent.scenario.behavior.Behavior; public class Worker implements Runnable { private ScenarioContext scenarioContext; - private InstanceControler ic; + private SessionObject sessionObject; private PluginManager pluginManager; @@ -29,12 +30,12 @@ public class Worker implements Runnable { this.scenarioContext = scenarioContext; } - private InstanceControler getIc() { - return ic; + private SessionObject getSessionObject() { + return sessionObject; } - private void setIc(InstanceControler ic) { - this.ic = ic; + private void setSessionObject(SessionObject sessionObject) { + this.sessionObject = sessionObject; } private PluginManager getPluginManager() { @@ -53,7 +54,7 @@ public class Worker implements Runnable { } private void doPrepare() { - this.setIc(new InstanceControler()); + this.setSessionObject(new InstanceControler()); } public void run() { @@ -62,7 +63,7 @@ public class Worker implements Runnable { } private void doCleanUp() { - this.ic.releaseAll(); + this.sessionObject.doCleanUp(); } public void doRunScenario(ScenarioContext context) { @@ -94,7 +95,7 @@ public class Worker implements Runnable { for (Behavior behavior : batch.getBehaviors()) { // each execution should call this System.out.println("enter doRunBatch"); - behavior.distillParams(this.getIc()); + behavior.distillParams(this.getSessionObject()); Object plugin = plugins.get(behavior.getUse()); Map behaviorParameters = prepareBehaviorParameters(behavior); Date startDate = new Date(System.currentTimeMillis()); diff --git a/src/main/java/org/bench4q/agent/scenario/behavior/Behavior.java b/src/main/java/org/bench4q/agent/scenario/behavior/Behavior.java index c3f6845c..705233ef 100644 --- a/src/main/java/org/bench4q/agent/scenario/behavior/Behavior.java +++ b/src/main/java/org/bench4q/agent/scenario/behavior/Behavior.java @@ -4,7 +4,7 @@ import java.util.Map; import org.bench4q.agent.datacollector.impl.BehaviorStatusCodeResult; import org.bench4q.agent.datacollector.interfaces.DataCollector; -import org.bench4q.agent.parameterization.impl.InstanceControler; +import org.bench4q.agent.parameterization.SessionObject; import org.bench4q.agent.scenario.Parameter; public abstract class Behavior { @@ -59,11 +59,11 @@ public abstract class Behavior { return ""; } - public void distillParams(InstanceControler instanceControler) { + public void distillParams(SessionObject session) { for (Parameter parameter : this.getParameters()) { String s = parameter.getValue(); System.out.println("before Change :" + s); - String re = instanceControler.getParameterByString(s); + String re = session.getParam(s); System.out.println("after Change : " + re); parameter.setValue(re); } From 90dc1cafbfd656a5380b7adbd31f074f7cbfd133 Mon Sep 17 00:00:00 2001 From: coderfengyun Date: Mon, 10 Mar 2014 14:33:43 +0800 Subject: [PATCH 161/196] remove dependency between worker and InstanceControler --- .../java/org/bench4q/agent/scenario/ScenarioEngine.java | 7 +++++-- src/main/java/org/bench4q/agent/scenario/Worker.java | 8 ++------ 2 files changed, 7 insertions(+), 8 deletions(-) diff --git a/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java b/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java index 662fcfc4..4cba7820 100644 --- a/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java +++ b/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java @@ -11,6 +11,7 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.ThreadPoolExecutor.DiscardPolicy; import org.apache.log4j.Logger; +import org.bench4q.agent.parameterization.impl.InstanceControler; import org.bench4q.agent.storage.StorageHelper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @@ -76,8 +77,10 @@ public class ScenarioEngine { taskMaker.execute(new Runnable() { public void run() { while (!scenarioContext.isFinished()) { - scenarioContext.getExecutor().execute( - new Worker(scenarioContext)); + scenarioContext.getExecutor() + .execute( + new Worker(scenarioContext, + new InstanceControler())); } } }); diff --git a/src/main/java/org/bench4q/agent/scenario/Worker.java b/src/main/java/org/bench4q/agent/scenario/Worker.java index e4dfc522..c50b60c4 100644 --- a/src/main/java/org/bench4q/agent/scenario/Worker.java +++ b/src/main/java/org/bench4q/agent/scenario/Worker.java @@ -46,15 +46,11 @@ public class Worker implements Runnable { this.pluginManager = pluginManager; } - public Worker(ScenarioContext scenarioContext) { + public Worker(ScenarioContext scenarioContext, SessionObject sessionObject) { this.setScenarioContext(scenarioContext); this.setPluginManager(ApplicationContextHelper.getContext().getBean( PluginManager.class)); - doPrepare(); - } - - private void doPrepare() { - this.setSessionObject(new InstanceControler()); + this.setSessionObject(sessionObject); } public void run() { From 226bff996fcc9dec93073a5a16fe0556bae00f37 Mon Sep 17 00:00:00 2001 From: coderfengyun Date: Mon, 10 Mar 2014 14:35:02 +0800 Subject: [PATCH 162/196] remove a warning --- src/main/java/org/bench4q/agent/scenario/Worker.java | 1 - 1 file changed, 1 deletion(-) diff --git a/src/main/java/org/bench4q/agent/scenario/Worker.java b/src/main/java/org/bench4q/agent/scenario/Worker.java index c50b60c4..1d693d2c 100644 --- a/src/main/java/org/bench4q/agent/scenario/Worker.java +++ b/src/main/java/org/bench4q/agent/scenario/Worker.java @@ -9,7 +9,6 @@ import java.util.Map; import org.bench4q.agent.datacollector.interfaces.DataCollector; import org.bench4q.agent.helper.ApplicationContextHelper; import org.bench4q.agent.parameterization.SessionObject; -import org.bench4q.agent.parameterization.impl.InstanceControler; import org.bench4q.agent.plugin.Plugin; import org.bench4q.agent.plugin.PluginManager; import org.bench4q.agent.plugin.result.HttpReturn; From 12868da0bacabaaf0825df3ca7678a2ae7b340f6 Mon Sep 17 00:00:00 2001 From: coderfengyun Date: Mon, 10 Mar 2014 14:50:34 +0800 Subject: [PATCH 163/196] add save params to worker --- .../agent/parameterization/SessionObject.java | 4 ++ .../impl/InstanceControler.java | 4 ++ .../agent/plugin/basic/http/HttpPlugin.java | 11 ++--- .../plugin/basic/http/ParameterParser.java | 9 ++-- .../agent/plugin/result/HttpReturn.java | 6 ++- .../agent/plugin/result/PluginReturn.java | 42 +++++++++++++------ .../org/bench4q/agent/scenario/Worker.java | 6 +++ 7 files changed, 60 insertions(+), 22 deletions(-) diff --git a/src/main/java/org/bench4q/agent/parameterization/SessionObject.java b/src/main/java/org/bench4q/agent/parameterization/SessionObject.java index 29cde272..a96586f4 100644 --- a/src/main/java/org/bench4q/agent/parameterization/SessionObject.java +++ b/src/main/java/org/bench4q/agent/parameterization/SessionObject.java @@ -1,5 +1,7 @@ package org.bench4q.agent.parameterization; +import java.util.Map; + public interface SessionObject { public String getParam(String name); @@ -7,4 +9,6 @@ public interface SessionObject { public void saveRuntimeParam(String name, String value); public void doCleanUp(); + + public void saveRuntimeParams(Map runTimeParams); } diff --git a/src/main/java/org/bench4q/agent/parameterization/impl/InstanceControler.java b/src/main/java/org/bench4q/agent/parameterization/impl/InstanceControler.java index 056f6eb2..37c901e9 100644 --- a/src/main/java/org/bench4q/agent/parameterization/impl/InstanceControler.java +++ b/src/main/java/org/bench4q/agent/parameterization/impl/InstanceControler.java @@ -130,6 +130,10 @@ public class InstanceControler implements SessionObject { } + public void saveRuntimeParams(Map runTimeParams) { + + } + public void doCleanUp() { this.releaseAll(); } diff --git a/src/main/java/org/bench4q/agent/plugin/basic/http/HttpPlugin.java b/src/main/java/org/bench4q/agent/plugin/basic/http/HttpPlugin.java index fdb83012..32958e35 100644 --- a/src/main/java/org/bench4q/agent/plugin/basic/http/HttpPlugin.java +++ b/src/main/java/org/bench4q/agent/plugin/basic/http/HttpPlugin.java @@ -11,7 +11,9 @@ import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.HashSet; import java.util.Iterator; +import java.util.LinkedHashMap; import java.util.List; +import java.util.Map; import java.util.Set; import org.apache.commons.httpclient.Cookie; @@ -122,6 +124,8 @@ public class HttpPlugin { int responseCode = -1; long contentLength = 0; String contentType = ""; + Map respVars = new LinkedHashMap(); + try { responseCode = this.getHttpClient().executeMethod(method); method.getStatusLine().toString(); @@ -141,14 +145,11 @@ public class HttpPlugin { if (isValid(respVarsToSaveInSession)) { doExtractResponseVariables(respVarsToSaveInSession, method.getResponseBodyAsString()); - List respVars = ParameterParser + respVars = ParameterParser .parseResponseVariables(respVarsToSaveInSession); - - // this.getSessionContext().addAVariable(respVarsToSaveInSession, - // method.getResponseBodyAsString()); } return new HttpReturn(responseCode > 0, responseCode, - contentLength, contentType, responseHeaders); + contentLength, contentType, responseHeaders, respVars); } catch (HttpException e) { e.printStackTrace(); return new HttpReturn(false, 400, contentLength, contentType); diff --git a/src/main/java/org/bench4q/agent/plugin/basic/http/ParameterParser.java b/src/main/java/org/bench4q/agent/plugin/basic/http/ParameterParser.java index aa836d3a..44662de6 100644 --- a/src/main/java/org/bench4q/agent/plugin/basic/http/ParameterParser.java +++ b/src/main/java/org/bench4q/agent/plugin/basic/http/ParameterParser.java @@ -1,8 +1,10 @@ package org.bench4q.agent.plugin.basic.http; import java.util.ArrayList; +import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; +import java.util.Map; import java.util.StringTokenizer; import org.apache.commons.httpclient.NameValuePair; @@ -52,8 +54,8 @@ public abstract class ParameterParser { return nvPairs; } - public static List parseResponseVariables(String value) { - List nvPairs = new LinkedList(); + public static Map parseResponseVariables(String value) { + Map nvPairs = new LinkedHashMap(); String[] entrys = value.split("#!"); for (String entry : entrys) { @@ -61,7 +63,8 @@ public abstract class ParameterParser { if (nv.length <= 1) { continue; } - nvPairs.add(distillHeader(nv[0].trim(), nv[1].trim())); + nvPairs.put(extractHeaderValue(nv[0].trim()), + extractHeaderValue(nv[1].trim())); } return nvPairs; } diff --git a/src/main/java/org/bench4q/agent/plugin/result/HttpReturn.java b/src/main/java/org/bench4q/agent/plugin/result/HttpReturn.java index a82a5be9..bee2dcce 100644 --- a/src/main/java/org/bench4q/agent/plugin/result/HttpReturn.java +++ b/src/main/java/org/bench4q/agent/plugin/result/HttpReturn.java @@ -1,5 +1,7 @@ package org.bench4q.agent.plugin.result; +import java.util.Map; + import org.apache.commons.httpclient.Header; /*** @@ -55,8 +57,10 @@ public class HttpReturn extends PluginReturn { } public HttpReturn(boolean success, int responseCode, long contentLength2, - String contentType2, Header[] responseHeaders) { + String contentType2, Header[] responseHeaders, + Map runTimeParams) { this(success, responseCode, contentLength2, contentType2); this.setHeaders(responseHeaders); + this.getRunTimeParams().putAll(runTimeParams); } } diff --git a/src/main/java/org/bench4q/agent/plugin/result/PluginReturn.java b/src/main/java/org/bench4q/agent/plugin/result/PluginReturn.java index a0b84163..b931dcb0 100644 --- a/src/main/java/org/bench4q/agent/plugin/result/PluginReturn.java +++ b/src/main/java/org/bench4q/agent/plugin/result/PluginReturn.java @@ -1,13 +1,29 @@ -package org.bench4q.agent.plugin.result; - -public abstract class PluginReturn { - private boolean success; - - public boolean isSuccess() { - return success; - } - - public void setSuccess(boolean success) { - this.success = success; - } -} +package org.bench4q.agent.plugin.result; + +import java.util.LinkedHashMap; +import java.util.Map; + +public abstract class PluginReturn { + private boolean success; + private Map runTimeParams; + + public boolean isSuccess() { + return success; + } + + public void setSuccess(boolean success) { + this.success = success; + } + + public Map getRunTimeParams() { + return runTimeParams; + } + + public void setRunTimeParams(Map runTimeParams) { + this.runTimeParams = runTimeParams; + } + + public PluginReturn() { + this.setRunTimeParams(new LinkedHashMap()); + } +} diff --git a/src/main/java/org/bench4q/agent/scenario/Worker.java b/src/main/java/org/bench4q/agent/scenario/Worker.java index 1d693d2c..31a490a0 100644 --- a/src/main/java/org/bench4q/agent/scenario/Worker.java +++ b/src/main/java/org/bench4q/agent/scenario/Worker.java @@ -96,6 +96,7 @@ public class Worker implements Runnable { Date startDate = new Date(System.currentTimeMillis()); PluginReturn pluginReturn = (PluginReturn) this.getPluginManager() .doBehavior(plugin, behavior.getName(), behaviorParameters); + extractRunTimeParams(pluginReturn); Date endDate = new Date(System.currentTimeMillis()); if (!behavior.shouldBeCountResponseTime()) { continue; @@ -108,6 +109,11 @@ public class Worker implements Runnable { return results; } + private void extractRunTimeParams(PluginReturn pluginReturn) { + this.getSessionObject().saveRuntimeParams( + pluginReturn.getRunTimeParams()); + } + private BehaviorResult buildBehaviorResult(Behavior behavior, Object plugin, Date startDate, PluginReturn pluginReturn, Date endDate) { From a43b1b3de793518e3c68c8a516d6f3c98ed037a1 Mon Sep 17 00:00:00 2001 From: yxsh Date: Mon, 10 Mar 2014 14:59:08 +0800 Subject: [PATCH 164/196] add the instance controller context parameter --- .../parameterization/impl/InstanceControler.java | 12 ++++++++++++ .../parameterization/impl/ParameterParser.java | 14 +++++++++++++- .../agent/parameterization/impl/TEST_UserName.java | 2 -- 3 files changed, 25 insertions(+), 3 deletions(-) diff --git a/src/main/java/org/bench4q/agent/parameterization/impl/InstanceControler.java b/src/main/java/org/bench4q/agent/parameterization/impl/InstanceControler.java index 056f6eb2..5e9fd5a7 100644 --- a/src/main/java/org/bench4q/agent/parameterization/impl/InstanceControler.java +++ b/src/main/java/org/bench4q/agent/parameterization/impl/InstanceControler.java @@ -15,6 +15,7 @@ public class InstanceControler implements SessionObject { private UUID instandid = java.util.UUID.randomUUID(); private Set usedClassName = new HashSet(); private Map objMap = new HashMap(); + private Map runtimeParaMap = new HashMap(); ReentrantReadWriteLock mapRWLock = new ReentrantReadWriteLock(); @@ -56,6 +57,13 @@ public class InstanceControler implements SessionObject { private String rootFilePath = "/home/yxsh/git/Bench4Q-Agent/parameterClass/"; + public String getParameterByContext(String name) { + if (false == this.runtimeParaMap.containsKey(name)) { + return name; + } + return runtimeParaMap.get(name); + } + public boolean createObj(String className) { try { MyFileClassLoader cl = new MyFileClassLoader(); @@ -127,6 +135,10 @@ public class InstanceControler implements SessionObject { } public void saveRuntimeParam(String name, String value) { + runtimeParaMap.put(name, value); + } + + public void saveRuntimeParams(Map runTimeParams) { } diff --git a/src/main/java/org/bench4q/agent/parameterization/impl/ParameterParser.java b/src/main/java/org/bench4q/agent/parameterization/impl/ParameterParser.java index 94723539..2d59ab04 100644 --- a/src/main/java/org/bench4q/agent/parameterization/impl/ParameterParser.java +++ b/src/main/java/org/bench4q/agent/parameterization/impl/ParameterParser.java @@ -23,12 +23,24 @@ public class ParameterParser { String className = root.getAttribute("class"); String methodName = root.getAttribute("method"); String argString = root.getAttribute("args"); - + String type = root.getAttribute("type"); String[] args = argString.split(","); if (argString.trim().equals("")) args = new String[0]; + if(type == "crossThread") + { result = insCon.getParameter("org.bench4q.agent.parameters." + className, methodName, args); + } + else if(type == "inThread") + { + result = insCon.instanceLevelGetParameter(className, methodName, args); + } + else if(type == "context") + { + String name = root.getAttribute("name"); + result = insCon.getParameterByContext(name); + } } catch (Exception ex) { return text; } diff --git a/src/main/java/org/bench4q/agent/parameterization/impl/TEST_UserName.java b/src/main/java/org/bench4q/agent/parameterization/impl/TEST_UserName.java index e92de731..65b92b50 100644 --- a/src/main/java/org/bench4q/agent/parameterization/impl/TEST_UserName.java +++ b/src/main/java/org/bench4q/agent/parameterization/impl/TEST_UserName.java @@ -1,7 +1,5 @@ package org.bench4q.agent.parameterization.impl; -import java.util.UUID; - public class TEST_UserName { public static void main(String[] args) { From 816fa5973e8e994b6b23c40dabefab961c9b4c00 Mon Sep 17 00:00:00 2001 From: yxsh Date: Mon, 10 Mar 2014 16:55:46 +0800 Subject: [PATCH 165/196] optimize the cache machinenism --- .../impl/InstanceControler.java | 22 +++++++++++-------- .../impl/Para_GetEletronicCombine.java | 12 ++++++++-- 2 files changed, 23 insertions(+), 11 deletions(-) diff --git a/src/main/java/org/bench4q/agent/parameterization/impl/InstanceControler.java b/src/main/java/org/bench4q/agent/parameterization/impl/InstanceControler.java index 5e9fd5a7..3a8811ef 100644 --- a/src/main/java/org/bench4q/agent/parameterization/impl/InstanceControler.java +++ b/src/main/java/org/bench4q/agent/parameterization/impl/InstanceControler.java @@ -16,7 +16,7 @@ public class InstanceControler implements SessionObject { private Set usedClassName = new HashSet(); private Map objMap = new HashMap(); private Map runtimeParaMap = new HashMap(); - + public Map cacheObjMap = new HashMap(); ReentrantReadWriteLock mapRWLock = new ReentrantReadWriteLock(); public String instanceLevelGetParameter(String className, @@ -32,13 +32,15 @@ public class InstanceControler implements SessionObject { Object instance = getObj(className); Object result = null; try { - Class[] argTypeArr = new Class[args.length + 1]; + Class[] argTypeArr = new Class[args.length + 2]; argTypeArr[0] = instandid.getClass(); - Object[] totalArgs = new Object[args.length + 1]; + argTypeArr[1] = this.cacheObjMap.getClass(); + Object[] totalArgs = new Object[args.length + 2]; totalArgs[0] = instandid; - for (int i = 1; i < args.length; i++) { - argTypeArr[i] = args[i].getClass(); - totalArgs[i] = args[i - 1]; + totalArgs[1] = this.cacheObjMap; + for (int i = 2; i < args.length+2; i++) { + argTypeArr[i] = args[i-2].getClass(); + totalArgs[i] = args[i - 2]; } Method m = instance.getClass().getMethod(functionName, argTypeArr); @@ -102,11 +104,13 @@ public class InstanceControler implements SessionObject { try { Class[] argTypeArr = new Class[args.length + 1]; argTypeArr[0] = instandid.getClass(); + argTypeArr[1] = this.cacheObjMap.getClass(); Object[] totalArgs = new Object[args.length + 1]; totalArgs[0] = instandid; - for (int i = 1; i < args.length; i++) { - argTypeArr[i] = args[i].getClass(); - totalArgs[i] = args[i - 1]; + totalArgs[1] = this.cacheObjMap; + for (int i = 2; i < args.length+2; i++) { + argTypeArr[i] = args[i-2].getClass(); + totalArgs[i] = args[i-2]; } Method m = instance.getClass().getMethod(functionName, argTypeArr); diff --git a/src/main/java/org/bench4q/agent/parameterization/impl/Para_GetEletronicCombine.java b/src/main/java/org/bench4q/agent/parameterization/impl/Para_GetEletronicCombine.java index 9b557e61..16295ae5 100644 --- a/src/main/java/org/bench4q/agent/parameterization/impl/Para_GetEletronicCombine.java +++ b/src/main/java/org/bench4q/agent/parameterization/impl/Para_GetEletronicCombine.java @@ -7,12 +7,20 @@ import java.util.UUID; import java.util.concurrent.locks.ReentrantReadWriteLock; public class Para_GetEletronicCombine { - static Map useInstanceMap = new HashMap(); + + public class eletronicParas + { + String beginUser; + String endUser; + String beginTime; + String endTime; + } + public Map useInstanceMap = new HashMap(); @SuppressWarnings("deprecation") Date currentTimeLoop = new Date("2014-01-01"); long currentUser = 10001; ReentrantReadWriteLock timeRWLock = new ReentrantReadWriteLock(); - + public Para_GetEletronicCombine() { } From 9e5405a32d96fe3944787e03e95f3703de5df67a Mon Sep 17 00:00:00 2001 From: yxsh Date: Tue, 11 Mar 2014 09:38:17 +0800 Subject: [PATCH 166/196] modify parser --- .../parameterization/impl/Para_UniqueNumber.java | 12 ++++++++++++ .../agent/parameterization/impl/ParameterParser.java | 1 + 2 files changed, 13 insertions(+) create mode 100644 src/main/java/org/bench4q/agent/parameterization/impl/Para_UniqueNumber.java diff --git a/src/main/java/org/bench4q/agent/parameterization/impl/Para_UniqueNumber.java b/src/main/java/org/bench4q/agent/parameterization/impl/Para_UniqueNumber.java new file mode 100644 index 00000000..24bcb320 --- /dev/null +++ b/src/main/java/org/bench4q/agent/parameterization/impl/Para_UniqueNumber.java @@ -0,0 +1,12 @@ +package org.bench4q.agent.parameterization.impl; + +import java.util.UUID; + +public class Para_UniqueNumber { + int currentNumber = 0; + + synchronized String getNumber(UUID id) + { + return String.valueOf(currentNumber++); + } +} diff --git a/src/main/java/org/bench4q/agent/parameterization/impl/ParameterParser.java b/src/main/java/org/bench4q/agent/parameterization/impl/ParameterParser.java index 2d59ab04..a6f880fc 100644 --- a/src/main/java/org/bench4q/agent/parameterization/impl/ParameterParser.java +++ b/src/main/java/org/bench4q/agent/parameterization/impl/ParameterParser.java @@ -27,6 +27,7 @@ public class ParameterParser { String[] args = argString.split(","); if (argString.trim().equals("")) args = new String[0]; + if(type == "crossThread") { result = insCon.getParameter("org.bench4q.agent.parameters." From 2a9e07fe1695b38ce842a24205f69db2401ce6e2 Mon Sep 17 00:00:00 2001 From: yxsh Date: Tue, 11 Mar 2014 09:42:57 +0800 Subject: [PATCH 167/196] modify instanceControler --- .../parameterization/impl/InstanceControler.java | 12 +++++------- .../agent/parameterization/impl/ParameterParser.java | 1 + 2 files changed, 6 insertions(+), 7 deletions(-) diff --git a/src/main/java/org/bench4q/agent/parameterization/impl/InstanceControler.java b/src/main/java/org/bench4q/agent/parameterization/impl/InstanceControler.java index 408715c8..d4651a78 100644 --- a/src/main/java/org/bench4q/agent/parameterization/impl/InstanceControler.java +++ b/src/main/java/org/bench4q/agent/parameterization/impl/InstanceControler.java @@ -142,13 +142,6 @@ public class InstanceControler implements SessionObject { runtimeParaMap.put(name, value); } - public void saveRuntimeParams(Map runTimeParams) { - - } - - public void saveRuntimeParams(Map runTimeParams) { - - } public void doCleanUp() { this.releaseAll(); @@ -192,4 +185,9 @@ public class InstanceControler implements SessionObject { } } + + public void saveRuntimeParams(Map runTimeParams) { + // TODO Auto-generated method stub + runtimeParaMap.putAll(runTimeParams); + } } diff --git a/src/main/java/org/bench4q/agent/parameterization/impl/ParameterParser.java b/src/main/java/org/bench4q/agent/parameterization/impl/ParameterParser.java index a6f880fc..3d475102 100644 --- a/src/main/java/org/bench4q/agent/parameterization/impl/ParameterParser.java +++ b/src/main/java/org/bench4q/agent/parameterization/impl/ParameterParser.java @@ -28,6 +28,7 @@ public class ParameterParser { if (argString.trim().equals("")) args = new String[0]; + if(type == "crossThread") { result = insCon.getParameter("org.bench4q.agent.parameters." From aaad57ac3dcb62eb7fe2f4a76149512bd6130515 Mon Sep 17 00:00:00 2001 From: yxsh Date: Tue, 11 Mar 2014 11:08:51 +0800 Subject: [PATCH 168/196] finish type and variable --- .../impl/InstanceControler.java | 8 +++-- .../parameterization/impl/Para_File.java | 3 ++ .../impl/ParameterParser.java | 20 ++++++++----- .../impl/ParameterThreadOption.java | 30 +++++++++++++++++++ 4 files changed, 50 insertions(+), 11 deletions(-) create mode 100644 src/main/java/org/bench4q/agent/parameterization/impl/ParameterThreadOption.java diff --git a/src/main/java/org/bench4q/agent/parameterization/impl/InstanceControler.java b/src/main/java/org/bench4q/agent/parameterization/impl/InstanceControler.java index d4651a78..9df9f78d 100644 --- a/src/main/java/org/bench4q/agent/parameterization/impl/InstanceControler.java +++ b/src/main/java/org/bench4q/agent/parameterization/impl/InstanceControler.java @@ -19,7 +19,7 @@ public class InstanceControler implements SessionObject { public Map cacheObjMap = new HashMap(); ReentrantReadWriteLock mapRWLock = new ReentrantReadWriteLock(); - public String instanceLevelGetParameter(String className, + public String instanceLevelGetParameter(String name,String className, String functionName, Object[] args) { boolean hasThisClass = false; @@ -53,6 +53,7 @@ public class InstanceControler implements SessionObject { .getTargetException().getMessage()); return null; } + runtimeParaMap.put(name, (String) result); return (String) result; } @@ -61,7 +62,7 @@ public class InstanceControler implements SessionObject { public String getParameterByContext(String name) { if (false == this.runtimeParaMap.containsKey(name)) { - return name; + return null; } return runtimeParaMap.get(name); } @@ -90,7 +91,7 @@ public class InstanceControler implements SessionObject { return result; } - public String getParameter(String className, String functionName, + public String getParameter(String name , String className, String functionName, Object[] args) { ParametersFactory pf = ParametersFactory.getInstance(); @@ -125,6 +126,7 @@ public class InstanceControler implements SessionObject { } usedClassName.add(className); + runtimeParaMap.put(name, (String) result); return (String) result; } diff --git a/src/main/java/org/bench4q/agent/parameterization/impl/Para_File.java b/src/main/java/org/bench4q/agent/parameterization/impl/Para_File.java index 3cd4a1b9..36c3c754 100644 --- a/src/main/java/org/bench4q/agent/parameterization/impl/Para_File.java +++ b/src/main/java/org/bench4q/agent/parameterization/impl/Para_File.java @@ -1,11 +1,14 @@ package org.bench4q.agent.parameterization.impl; import java.io.BufferedReader; +import java.util.ArrayList; import java.util.HashMap; +import java.util.List; import java.util.Map; import java.util.UUID; public class Para_File { + @SuppressWarnings("unused") private Map readBuffer = new HashMap(); diff --git a/src/main/java/org/bench4q/agent/parameterization/impl/ParameterParser.java b/src/main/java/org/bench4q/agent/parameterization/impl/ParameterParser.java index 3d475102..ceb05cbc 100644 --- a/src/main/java/org/bench4q/agent/parameterization/impl/ParameterParser.java +++ b/src/main/java/org/bench4q/agent/parameterization/impl/ParameterParser.java @@ -1,6 +1,10 @@ package org.bench4q.agent.parameterization.impl; import java.io.StringReader; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; @@ -12,6 +16,7 @@ public class ParameterParser { public String parse(String text, InstanceControler insCon) { // Pattern pattern = Pattern.compile(""); + String result = ""; try { @@ -28,21 +33,20 @@ public class ParameterParser { if (argString.trim().equals("")) args = new String[0]; - + String name = root.getAttribute("name"); + result = insCon.getParameterByContext(name); + if(result != null) + return result; if(type == "crossThread") { - result = insCon.getParameter("org.bench4q.agent.parameters." + result = insCon.getParameter(name,"org.bench4q.agent.parameters." + className, methodName, args); } else if(type == "inThread") { - result = insCon.instanceLevelGetParameter(className, methodName, args); - } - else if(type == "context") - { - String name = root.getAttribute("name"); - result = insCon.getParameterByContext(name); + result = insCon.instanceLevelGetParameter(name,className, methodName, args); } + } catch (Exception ex) { return text; } diff --git a/src/main/java/org/bench4q/agent/parameterization/impl/ParameterThreadOption.java b/src/main/java/org/bench4q/agent/parameterization/impl/ParameterThreadOption.java new file mode 100644 index 00000000..d22ea8b5 --- /dev/null +++ b/src/main/java/org/bench4q/agent/parameterization/impl/ParameterThreadOption.java @@ -0,0 +1,30 @@ +package org.bench4q.agent.parameterization.impl; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class ParameterThreadOption { + public final ParameterThreadOption instance = new ParameterThreadOption(); + Map> optionMap = new HashMap>(); + private List all = Arrays.asList("crossThread", "inThread"); + private List justIn = Arrays.asList( "inThread"); + private List justCross = Arrays.asList("crossThread"); + private ParameterThreadOption() + { + + optionMap.put("Para_File", all); + optionMap.put("Para_IteratorNumber",justCross); + optionMap.put("Para_RandomNumber", all); + optionMap.put("Para_UniqueNumber", all); + optionMap.put("Para_UserNameAndPassword", justCross); + } + public List getThreadOption(String classname) + { + if(this.optionMap.containsKey(classname)== false) + return all; + return optionMap.get(classname); + } +} From eafd5aa28adf1b36384eaa91074b1e9aa6b380ba Mon Sep 17 00:00:00 2001 From: coderfengyun Date: Tue, 11 Mar 2014 14:55:27 +0800 Subject: [PATCH 169/196] add more tests --- .../agent/plugin/basic/http/HttpPlugin.java | 26 ++++-- .../plugin/basic/http/ParameterConstant.java | 14 ++-- .../plugin/basic/http/ParameterParser.java | 82 +++++++++---------- .../bench4q/agent/test/HttpPluginTest.java | 5 -- .../agent/test/plugin/Test_HttpPlugin.java | 21 +++++ .../scenario/utils/Test_ParameterParser.java | 18 ++-- .../utils/Test_RegularExpression.java | 31 +++++++ 7 files changed, 133 insertions(+), 64 deletions(-) delete mode 100644 src/test/java/org/bench4q/agent/test/HttpPluginTest.java create mode 100644 src/test/java/org/bench4q/agent/test/scenario/utils/Test_RegularExpression.java diff --git a/src/main/java/org/bench4q/agent/plugin/basic/http/HttpPlugin.java b/src/main/java/org/bench4q/agent/plugin/basic/http/HttpPlugin.java index 32958e35..c7baec12 100644 --- a/src/main/java/org/bench4q/agent/plugin/basic/http/HttpPlugin.java +++ b/src/main/java/org/bench4q/agent/plugin/basic/http/HttpPlugin.java @@ -15,6 +15,8 @@ import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; +import java.util.regex.Matcher; +import java.util.regex.Pattern; import org.apache.commons.httpclient.Cookie; import org.apache.commons.httpclient.Header; @@ -143,10 +145,8 @@ public class HttpPlugin { .getURI().getHost() + ":" + method.getURI().getPort()); } if (isValid(respVarsToSaveInSession)) { - doExtractResponseVariables(respVarsToSaveInSession, + respVars = doExtractResponseVariables(respVarsToSaveInSession, method.getResponseBodyAsString()); - respVars = ParameterParser - .parseResponseVariables(respVarsToSaveInSession); } return new HttpReturn(responseCode > 0, responseCode, contentLength, contentType, responseHeaders, respVars); @@ -161,9 +161,23 @@ public class HttpPlugin { } } - private void doExtractResponseVariables(String respVarsToSaveInSession, - String responseBodyAsString) { - + private Map doExtractResponseVariables( + String respVarsToSaveInSession, String responseBodyAsString) { + Map keyValues = new LinkedHashMap(); + List> varExtractExpressionList = ParameterParser + .getTable(respVarsToSaveInSession); + for (List row : varExtractExpressionList) { + if (row.size() <= 1) { + continue; + } + String varName = row.get(0); + String varExpression = row.get(1); + Matcher matcher = Pattern.compile(varExpression).matcher( + responseBodyAsString); + if (matcher.find()) + keyValues.put(varName, matcher.group()); + } + return keyValues; } private void setCookies(Header requestHeader, String domain) { diff --git a/src/main/java/org/bench4q/agent/plugin/basic/http/ParameterConstant.java b/src/main/java/org/bench4q/agent/plugin/basic/http/ParameterConstant.java index 9bd8ceb8..96c18334 100644 --- a/src/main/java/org/bench4q/agent/plugin/basic/http/ParameterConstant.java +++ b/src/main/java/org/bench4q/agent/plugin/basic/http/ParameterConstant.java @@ -11,14 +11,14 @@ public class ParameterConstant { /** * About table */ - public static final String TABLE_SEPARATOR = "|;"; - public static final String TABLE_ENTRY_SEPARATOR = "|"; - public static final String TABLE_SEPARATOR_TAIL = ";"; + public static final String TABLE_ROW_SEPARATOR = "|;"; + public static final String TABLE_COLUMN_SEPARATOR = "|"; + public static final String TABLE_ROW_SEPARATOR_TAIL = ";"; - public static final String ESCAPE_TABLE_SEPARATOR = escape - + TABLE_SEPARATOR; - public static final String ESCAPE_TABLE_ENTRY_SEPARATOR = escape - + TABLE_ENTRY_SEPARATOR; + public static final String ESCAPE_TABLE_ROW_SEPARATOR = escape + + TABLE_ROW_SEPARATOR; + public static final String ESCAPE_TABLE_COLUMN_SEPARATOR = escape + + TABLE_COLUMN_SEPARATOR; /** * diff --git a/src/main/java/org/bench4q/agent/plugin/basic/http/ParameterParser.java b/src/main/java/org/bench4q/agent/plugin/basic/http/ParameterParser.java index 44662de6..1b26eebf 100644 --- a/src/main/java/org/bench4q/agent/plugin/basic/http/ParameterParser.java +++ b/src/main/java/org/bench4q/agent/plugin/basic/http/ParameterParser.java @@ -1,10 +1,8 @@ package org.bench4q.agent.plugin.basic.http; import java.util.ArrayList; -import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; -import java.util.Map; import java.util.StringTokenizer; import org.apache.commons.httpclient.NameValuePair; @@ -49,45 +47,47 @@ public abstract class ParameterParser { if (entry.size() != 2) { continue; } - nvPairs.add(distillHeader(entry.get(0).trim(), entry.get(1).trim())); + nvPairs.add(new NameValuePair(entry.get(0).trim(), entry.get(1) + .trim())); } return nvPairs; } - public static Map parseResponseVariables(String value) { - Map nvPairs = new LinkedHashMap(); - String[] entrys = value.split("#!"); - - for (String entry : entrys) { - String[] nv = entry.split("#"); - if (nv.length <= 1) { - continue; - } - nvPairs.put(extractHeaderValue(nv[0].trim()), - extractHeaderValue(nv[1].trim())); - } - return nvPairs; + public static List> parseResponseVariables(String value) { + return getTable(value); + // Map nvPairs = new LinkedHashMap(); + // String[] entrys = value.split("#!"); + // + // for (String entry : entrys) { + // String[] nv = entry.split("#"); + // if (nv.length <= 1) { + // continue; + // } + // nvPairs.put(extractHeaderValue(nv[0].trim()), + // extractHeaderValue(nv[1].trim())); + // } + // return nvPairs; } - private static NameValuePair distillHeader(String name, String value) { - return new NameValuePair(extractHeaderName(name), - extractHeaderValue(value)); - } - - private static String extractHeaderValue(String value) { - if (!value.toLowerCase() - .startsWith(ParameterConstant.HEADER_VALUE_SIGN)) { - return value; - } - return value.substring(ParameterConstant.HEADER_VALUE_SIGN.length()); - } - - private static String extractHeaderName(String name) { - if (!name.toLowerCase().startsWith(ParameterConstant.HEADER_NAME_SIGN)) { - return name; - } - return name.substring(ParameterConstant.HEADER_NAME_SIGN.length()); - } + // private static NameValuePair distillHeader(String name, String value) { + // return new NameValuePair(extractHeaderName(name), + // extractHeaderValue(value)); + // } + // + // private static String extractHeaderValue(String value) { + // if (!value.toLowerCase() + // .startsWith(ParameterConstant.HEADER_VALUE_SIGN)) { + // return value; + // } + // return value.substring(ParameterConstant.HEADER_VALUE_SIGN.length()); + // } + // + // private static String extractHeaderName(String name) { + // if (!name.toLowerCase().startsWith(ParameterConstant.HEADER_NAME_SIGN)) { + // return name; + // } + // return name.substring(ParameterConstant.HEADER_NAME_SIGN.length()); + // } /** * This method analyzes the value to be set in the table, and remove all @@ -102,13 +102,13 @@ public abstract class ParameterParser { static public List> getTable(String value) { List> result = new ArrayList>(); List tempEntries = getRealTokens( - ParameterConstant.ESCAPE_TABLE_SEPARATOR, value, false); + ParameterConstant.ESCAPE_TABLE_ROW_SEPARATOR, value, false); // now analyze all entries values, and get the '|' separator List> allValues = new ArrayList>(); for (int i = 0; i < tempEntries.size(); i++) { String tempEntry = tempEntries.get(i); List values = getRealTokens( - ParameterConstant.ESCAPE_TABLE_ENTRY_SEPARATOR, tempEntry, + ParameterConstant.ESCAPE_TABLE_COLUMN_SEPARATOR, tempEntry, true); arrangeTheTableChildSeparator(values); allValues.add(values); @@ -144,10 +144,10 @@ public abstract class ParameterParser { for (int i = 0; i < values.size(); i++) { String currentToken = values.get(i); - if (currentToken.equals(ParameterConstant.TABLE_SEPARATOR_TAIL) + if (currentToken.equals(ParameterConstant.TABLE_ROW_SEPARATOR_TAIL) && i > 0) { values.set(i - 1, values.get(i - 1) - + ParameterConstant.TABLE_SEPARATOR_TAIL); + + ParameterConstant.TABLE_ROW_SEPARATOR_TAIL); } } @@ -206,11 +206,11 @@ public abstract class ParameterParser { * @return The vector containing each token */ static public List getRealTokens(String separator, String value, - boolean toUnescape) { + boolean toUnescapeSeparator) { List result = new ArrayList(); for (String entry : value.split(separator)) { if (getNumberOfEscapeCharacter(entry) % 2 != 0) { - if (toUnescape) { + if (toUnescapeSeparator) { entry = entry.substring(0, entry.length() - 1) + unescape(separator); } else { diff --git a/src/test/java/org/bench4q/agent/test/HttpPluginTest.java b/src/test/java/org/bench4q/agent/test/HttpPluginTest.java deleted file mode 100644 index c7849cc1..00000000 --- a/src/test/java/org/bench4q/agent/test/HttpPluginTest.java +++ /dev/null @@ -1,5 +0,0 @@ -package org.bench4q.agent.test; - -public class HttpPluginTest { - -} diff --git a/src/test/java/org/bench4q/agent/test/plugin/Test_HttpPlugin.java b/src/test/java/org/bench4q/agent/test/plugin/Test_HttpPlugin.java index 8018bbc9..cc62ca50 100644 --- a/src/test/java/org/bench4q/agent/test/plugin/Test_HttpPlugin.java +++ b/src/test/java/org/bench4q/agent/test/plugin/Test_HttpPlugin.java @@ -1,10 +1,13 @@ package org.bench4q.agent.test.plugin; +import java.util.Map; + import org.apache.commons.httpclient.Cookie; import org.apache.commons.httpclient.cookie.MalformedCookieException; import org.bench4q.agent.plugin.basic.http.HttpPlugin; import org.bench4q.agent.plugin.result.HttpReturn; import org.bench4q.agent.plugin.result.PluginReturn; +import org.bench4q.share.helper.TestHelper; import org.junit.Test; import static org.junit.Assert.*; @@ -94,4 +97,22 @@ public class Test_HttpPlugin { } } + @Test + public void testDoExtractResponseVariables() throws Exception { + String respVarsToSave = "varName=ticket|varExpression=\"ticket\":\\s*?\"\\w+\",|;"; + String responseBodyAsString = "{" + "\n" + + "\"ticket\": \"e55de793fc934001b156e97f94ff3eb6\"," + "\n" + + "\"parentId\": 3273," + "\n" + "\"expiresIn\": 300000" + "\n" + + "}"; + @SuppressWarnings("unchecked") + Map nameValueMap = (Map) TestHelper + .invokePrivateMethod(this.getHttpPlugin().getClass(), + this.getHttpPlugin(), "doExtractResponseVariables", + new Class[] { String.class, String.class }, + new Object[] { respVarsToSave, responseBodyAsString }); + assertEquals(1, nameValueMap.size()); + assertTrue(nameValueMap.containsKey("ticket")); + assertEquals("e55de793fc934001b156e97f94ff3eb6", + nameValueMap.get("ticket")); + } } diff --git a/src/test/java/org/bench4q/agent/test/scenario/utils/Test_ParameterParser.java b/src/test/java/org/bench4q/agent/test/scenario/utils/Test_ParameterParser.java index f9fbdea7..4c0fd89c 100644 --- a/src/test/java/org/bench4q/agent/test/scenario/utils/Test_ParameterParser.java +++ b/src/test/java/org/bench4q/agent/test/scenario/utils/Test_ParameterParser.java @@ -14,6 +14,7 @@ public class Test_ParameterParser { private String testcase = " _nacc=yeah ;_nvid=525d29a534e918cbf04ea7159706a93d;_nvtm=0;_nvsf=0;_nvfi=1;_nlag=zh-cn;_nlmf=1389570024;_nres=1440x900;_nscd=32-bit;_nstm=0;"; private String testHeaders = "header=Content-Type|value=application/x-www-form-urlencoded|;header=Content-Length|value=63|;header=Accept|value=text/html,application/xhtml+xml,application/xml|;"; private String testheaderWithUpperCase = "HEADER=Content-Type|Value=application/x-www-form-urlencoded|;header=Content-Length|value=63|;header=Accept|value=text/html,application/xhtml+xml,application/xml|;"; + private String testcaseWithEscapes = "varName=ticket|varExpression=\"ticket\":\\s*?\"\\w+\",|;"; private List expectedNFField = new ArrayList() { private static final long serialVersionUID = 1L; { @@ -29,7 +30,7 @@ public class Test_ParameterParser { add("_nstm=0"); } }; - private static final String testcase1 = "header=accept|value=asdfasdf\\|;|;"; + private static final String TESTCASE1_CONTAIN_SEPARATOR = "header=accept|value=asdfasdf\\|;|;"; private static final String testcase2 = "header=accept|value=fafsd|;varName=abc|varValue=234|;"; @Test @@ -39,17 +40,23 @@ public class Test_ParameterParser { } @Test - public void testGetRealTokenForEscape() { + public void testGetRealTokenForContainSeparator() { List entryList = ParameterParser.getRealTokens( - ParameterConstant.ESCAPE_TABLE_SEPARATOR, testcase1, true); + ParameterConstant.ESCAPE_TABLE_ROW_SEPARATOR, + TESTCASE1_CONTAIN_SEPARATOR, true); assertEquals(1, entryList.size()); assertEquals("header=accept|value=asdfasdf|;", entryList.get(0)); } + @Test + public void testGetRealTokenForContainManyEscapse() { + System.out.println(testcaseWithEscapes); + } + @Test public void testGetRealTokensForMultiSeparator() { List entryList = ParameterParser.getRealTokens( - ParameterConstant.ESCAPE_TABLE_SEPARATOR, testcase2, false); + ParameterConstant.ESCAPE_TABLE_ROW_SEPARATOR, testcase2, false); assertEquals(2, entryList.size()); assertEquals("header=accept|value=fafsd", entryList.get(0)); assertEquals("varName=abc|varValue=234", entryList.get(1)); @@ -57,7 +64,8 @@ public class Test_ParameterParser { @Test public void testGetTableForSeparator() { - List> resultEntries = ParameterParser.getTable(testcase1); + List> resultEntries = ParameterParser + .getTable(TESTCASE1_CONTAIN_SEPARATOR); assertEquals(1, resultEntries.size()); assertEquals(2, resultEntries.get(0).size()); assertEquals("accept", resultEntries.get(0).get(0)); diff --git a/src/test/java/org/bench4q/agent/test/scenario/utils/Test_RegularExpression.java b/src/test/java/org/bench4q/agent/test/scenario/utils/Test_RegularExpression.java new file mode 100644 index 00000000..0597fc4d --- /dev/null +++ b/src/test/java/org/bench4q/agent/test/scenario/utils/Test_RegularExpression.java @@ -0,0 +1,31 @@ +package org.bench4q.agent.test.scenario.utils; + +import static org.junit.Assert.*; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.junit.Test; + +public class Test_RegularExpression { + String regex1 = "(?i)((^[aeiou])|(\\s+[aeiou]))\\w+?[aeiou]\\b"; + String regex2 = "(?i)\\w+?[aeiou]"; + String regex3 = "(?i)(\\s+[aeiou])\\w+?[aeiou]\b"; + String regex4 = "(?i)(^[aeiou])\\w+?[aeiou]\b"; + String target1 = "Arline ate eight apples and one orange while anita hadn't any"; + String target2 = "Arline ate"; + + @Test + public void test() { + + Pattern pattern = Pattern.compile(regex2); + + Matcher matcher = pattern.matcher(target1); + System.out.println(matcher.matches()); + matcher.reset(); + while (matcher.find()) { + System.out.println(matcher.group()); + } + fail(); + } +} From 5e8479b61430c25cf81489e19eed043ac90d6aae Mon Sep 17 00:00:00 2001 From: coderfengyun Date: Tue, 11 Mar 2014 16:56:24 +0800 Subject: [PATCH 170/196] add ways to extract parameter from httpResponse --- .../agent/plugin/basic/http/HttpPlugin.java | 22 +++++----- .../plugin/basic/http/ParameterParser.java | 10 +++-- .../agent/test/plugin/Test_HttpPlugin.java | 3 +- .../scenario/utils/Test_ParameterParser.java | 42 +++++++++++++++++-- 4 files changed, 60 insertions(+), 17 deletions(-) diff --git a/src/main/java/org/bench4q/agent/plugin/basic/http/HttpPlugin.java b/src/main/java/org/bench4q/agent/plugin/basic/http/HttpPlugin.java index c7baec12..99d6f9dd 100644 --- a/src/main/java/org/bench4q/agent/plugin/basic/http/HttpPlugin.java +++ b/src/main/java/org/bench4q/agent/plugin/basic/http/HttpPlugin.java @@ -140,10 +140,6 @@ public class HttpPlugin { contentType = method.getResponseHeader("Content-Type") .getValue(); } - if (method.getRequestHeader("Set-Cookie") != null) { - setCookies(method.getRequestHeader("Set-Cookie"), method - .getURI().getHost() + ":" + method.getURI().getPort()); - } if (isValid(respVarsToSaveInSession)) { respVars = doExtractResponseVariables(respVarsToSaveInSession, method.getResponseBodyAsString()); @@ -167,22 +163,28 @@ public class HttpPlugin { List> varExtractExpressionList = ParameterParser .getTable(respVarsToSaveInSession); for (List row : varExtractExpressionList) { - if (row.size() <= 1) { + if (row.size() <= 3) { continue; } String varName = row.get(0); String varExpression = row.get(1); + String varLeftBoundry = row.get(2); + String varRightBoundry = row.get(3); Matcher matcher = Pattern.compile(varExpression).matcher( responseBodyAsString); - if (matcher.find()) - keyValues.put(varName, matcher.group()); + if (matcher.find()) { + String matchedVariable = matcher.group(); + int indexOfLB = matchedVariable.indexOf(varLeftBoundry); + int indexOfRB = matchedVariable.indexOf(varRightBoundry); + keyValues + .put(varName, + matchedVariable.substring(indexOfLB + + varLeftBoundry.length(), indexOfRB)); + } } return keyValues; } - private void setCookies(Header requestHeader, String domain) { - } - /** * * @param url diff --git a/src/main/java/org/bench4q/agent/plugin/basic/http/ParameterParser.java b/src/main/java/org/bench4q/agent/plugin/basic/http/ParameterParser.java index 1b26eebf..2a62ddb0 100644 --- a/src/main/java/org/bench4q/agent/plugin/basic/http/ParameterParser.java +++ b/src/main/java/org/bench4q/agent/plugin/basic/http/ParameterParser.java @@ -100,7 +100,6 @@ public abstract class ParameterParser { * vector, which contains the string values */ static public List> getTable(String value) { - List> result = new ArrayList>(); List tempEntries = getRealTokens( ParameterConstant.ESCAPE_TABLE_ROW_SEPARATOR, value, false); // now analyze all entries values, and get the '|' separator @@ -114,6 +113,12 @@ public abstract class ParameterParser { allValues.add(values); } // now analyze all values, and get the '=' separator + return extractValueFromWellFormedTable(allValues); + } + + public static List> extractValueFromWellFormedTable( + List> allValues) { + List> result = new LinkedList>(); for (int i = 0; i < allValues.size(); i++) { List resultValues = new ArrayList(); List tempValues = allValues.get(i); @@ -125,9 +130,8 @@ public abstract class ParameterParser { continue; } res = temp.get(1); - res = unescape(res); + // res = unescape(res); resultValues.add(res); - } result.add(resultValues); } diff --git a/src/test/java/org/bench4q/agent/test/plugin/Test_HttpPlugin.java b/src/test/java/org/bench4q/agent/test/plugin/Test_HttpPlugin.java index cc62ca50..25419afa 100644 --- a/src/test/java/org/bench4q/agent/test/plugin/Test_HttpPlugin.java +++ b/src/test/java/org/bench4q/agent/test/plugin/Test_HttpPlugin.java @@ -99,7 +99,7 @@ public class Test_HttpPlugin { @Test public void testDoExtractResponseVariables() throws Exception { - String respVarsToSave = "varName=ticket|varExpression=\"ticket\":\\s*?\"\\w+\",|;"; + String respVarsToSave = "varName=ticket|varExpression=\"ticket\":\\s*?\"\\w+\",|leftBoundry=\"ticket\"\": \"|rightBoundry=\",|;"; String responseBodyAsString = "{" + "\n" + "\"ticket\": \"e55de793fc934001b156e97f94ff3eb6\"," + "\n" + "\"parentId\": 3273," + "\n" + "\"expiresIn\": 300000" + "\n" @@ -112,6 +112,7 @@ public class Test_HttpPlugin { new Object[] { respVarsToSave, responseBodyAsString }); assertEquals(1, nameValueMap.size()); assertTrue(nameValueMap.containsKey("ticket")); + System.out.println(nameValueMap.get("ticket")); assertEquals("e55de793fc934001b156e97f94ff3eb6", nameValueMap.get("ticket")); } diff --git a/src/test/java/org/bench4q/agent/test/scenario/utils/Test_ParameterParser.java b/src/test/java/org/bench4q/agent/test/scenario/utils/Test_ParameterParser.java index 4c0fd89c..f8cd12ed 100644 --- a/src/test/java/org/bench4q/agent/test/scenario/utils/Test_ParameterParser.java +++ b/src/test/java/org/bench4q/agent/test/scenario/utils/Test_ParameterParser.java @@ -3,17 +3,22 @@ package org.bench4q.agent.test.scenario.utils; import static org.junit.Assert.*; import java.util.ArrayList; +import java.util.LinkedList; import java.util.List; import org.apache.commons.httpclient.NameValuePair; import org.bench4q.agent.plugin.basic.http.ParameterConstant; import org.bench4q.agent.plugin.basic.http.ParameterParser; +import org.bench4q.share.helper.TestHelper; import org.junit.Test; public class Test_ParameterParser { private String testcase = " _nacc=yeah ;_nvid=525d29a534e918cbf04ea7159706a93d;_nvtm=0;_nvsf=0;_nvfi=1;_nlag=zh-cn;_nlmf=1389570024;_nres=1440x900;_nscd=32-bit;_nstm=0;"; private String testHeaders = "header=Content-Type|value=application/x-www-form-urlencoded|;header=Content-Length|value=63|;header=Accept|value=text/html,application/xhtml+xml,application/xml|;"; private String testheaderWithUpperCase = "HEADER=Content-Type|Value=application/x-www-form-urlencoded|;header=Content-Length|value=63|;header=Accept|value=text/html,application/xhtml+xml,application/xml|;"; + private static final String TESTCASE1_CONTAIN_SEPARATOR = "header=accept|value=asdfasdf\\|;|;"; + private static final String testcase2 = "header=accept|value=fafsd|;varName=abc|varValue=234|;"; + private String testcaseWithEscapes = "varName=ticket|varExpression=\"ticket\":\\s*?\"\\w+\",|;"; private List expectedNFField = new ArrayList() { private static final long serialVersionUID = 1L; @@ -30,8 +35,6 @@ public class Test_ParameterParser { add("_nstm=0"); } }; - private static final String TESTCASE1_CONTAIN_SEPARATOR = "header=accept|value=asdfasdf\\|;|;"; - private static final String testcase2 = "header=accept|value=fafsd|;varName=abc|varValue=234|;"; @Test public void testGetNumberOfEscapeCharacter() { @@ -50,7 +53,30 @@ public class Test_ParameterParser { @Test public void testGetRealTokenForContainManyEscapse() { - System.out.println(testcaseWithEscapes); + List rowList = ParameterParser.getRealTokens( + ParameterConstant.ESCAPE_TABLE_ROW_SEPARATOR, + testcaseWithEscapes, false); + assertEquals(1, rowList.size()); + assertEquals("varName=ticket|varExpression=\"ticket\":\\s*?\"\\w+\",", + rowList.get(0)); + final List columnList = ParameterParser.getRealTokens( + ParameterConstant.ESCAPE_TABLE_COLUMN_SEPARATOR, + rowList.get(0), true); + assertEquals(2, columnList.size()); + assertEquals("varName=ticket", columnList.get(0)); + assertEquals("varExpression=\"ticket\":\\s*?\"\\w+\",", + columnList.get(1)); + List> result = ParameterParser + .extractValueFromWellFormedTable(new LinkedList>() { + private static final long serialVersionUID = 1L; + { + add(columnList); + } + }); + assertEquals(1, result.size()); + assertEquals(2, result.get(0).size()); + assertEquals("ticket", result.get(0).get(0)); + assertEquals("\"ticket\":\\s*?\"\\w+\",", result.get(0).get(1)); } @Test @@ -82,6 +108,16 @@ public class Test_ParameterParser { assertEquals("abc", resultEntries.get(1).get(0)); } + @Test + public void testGetTableWithManyEscapse() { + List> resultTable = ParameterParser + .getTable(testcaseWithEscapes); + assertEquals(1, resultTable.size()); + assertEquals(2, resultTable.get(0).size()); + assertEquals("ticket", resultTable.get(0).get(0)); + assertEquals("\"ticket\":\\s*?\"\\w+\",", resultTable.get(0).get(1)); + } + @Test public void testParseParam() { List result = ParameterParser.getNField(testcase); From ef622a7eedac36b170f31d76827f851c665a3004 Mon Sep 17 00:00:00 2001 From: coderfengyun Date: Tue, 11 Mar 2014 17:33:11 +0800 Subject: [PATCH 171/196] now i can extract parameters from cloud share's response --- .../java/org/bench4q/agent/scenario/Worker.java | 2 +- .../agent/test/plugin/Test_HttpPlugin.java | 17 ++++++++++++++++- 2 files changed, 17 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/bench4q/agent/scenario/Worker.java b/src/main/java/org/bench4q/agent/scenario/Worker.java index 31a490a0..b782036b 100644 --- a/src/main/java/org/bench4q/agent/scenario/Worker.java +++ b/src/main/java/org/bench4q/agent/scenario/Worker.java @@ -89,7 +89,6 @@ public class Worker implements Runnable { List results = new ArrayList(); for (Behavior behavior : batch.getBehaviors()) { // each execution should call this - System.out.println("enter doRunBatch"); behavior.distillParams(this.getSessionObject()); Object plugin = plugins.get(behavior.getUse()); Map behaviorParameters = prepareBehaviorParameters(behavior); @@ -103,6 +102,7 @@ public class Worker implements Runnable { } BehaviorResult behaviorResult = buildBehaviorResult(behavior, plugin, startDate, pluginReturn, endDate); + pluginReturn = null; dataCollector.add(behaviorResult); results.add(behaviorResult); } diff --git a/src/test/java/org/bench4q/agent/test/plugin/Test_HttpPlugin.java b/src/test/java/org/bench4q/agent/test/plugin/Test_HttpPlugin.java index 25419afa..575db67e 100644 --- a/src/test/java/org/bench4q/agent/test/plugin/Test_HttpPlugin.java +++ b/src/test/java/org/bench4q/agent/test/plugin/Test_HttpPlugin.java @@ -86,7 +86,22 @@ public class Test_HttpPlugin { "header=Accept|value=text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8|;", null); assertEquals(200, homeReturn.getStatusCode()); - logTheCookie("fourth"); + logTheCookie("third"); + + HttpReturn ticketReturn = this + .getHttpPlugin() + .post("http://124.16.137.203:7080/cloudshare_web/v2/file/ajax/uploadFiles/-1", + null, + "header=Accept|value=*/*|;" + + "header=Content-Length|value=0|;" + + "header=X-Requested-With|value=XMLHttpRequest|;", + "", + null, + "varName=ticket|varExpression=\"ticket\":\\s*?\"\\w+\",|leftBoundry=\"ticket\"\": \"|rightBoundry=\",|;"); + assertEquals(200, ticketReturn.getStatusCode()); + assertNotNull(ticketReturn.getRunTimeParams()); + assertEquals(1, ticketReturn.getRunTimeParams().size()); + System.out.println(ticketReturn.getRunTimeParams().get("ticket")); } private void logTheCookie(String times) { From 51ae22fa05402914b0a060c794d5b6b37ca581db Mon Sep 17 00:00:00 2001 From: coderfengyun Date: Wed, 12 Mar 2014 10:57:50 +0800 Subject: [PATCH 172/196] add briefAll function for master, it's a facade interface --- .../org/bench4q/agent/api/TestController.java | 11 ++++ .../agent/plugin/basic/http/HttpPlugin.java | 61 +++++++++++++------ .../plugin/basic/http/ParameterParser.java | 32 ---------- .../agent/plugin/basic/http/format/Table.java | 5 ++ .../scenario/utils/Test_ParameterParser.java | 1 - 5 files changed, 59 insertions(+), 51 deletions(-) create mode 100644 src/main/java/org/bench4q/agent/plugin/basic/http/format/Table.java diff --git a/src/main/java/org/bench4q/agent/api/TestController.java b/src/main/java/org/bench4q/agent/api/TestController.java index 4d9d9bc6..d8c96a75 100644 --- a/src/main/java/org/bench4q/agent/api/TestController.java +++ b/src/main/java/org/bench4q/agent/api/TestController.java @@ -24,6 +24,7 @@ import org.bench4q.share.models.agent.CleanTestResultModel; import org.bench4q.share.models.agent.RunScenarioModel; import org.bench4q.share.models.agent.RunScenarioResultModel; import org.bench4q.share.models.agent.StopTestModel; +import org.bench4q.share.models.agent.TestBriefStatusModel; import org.bench4q.share.models.agent.statistics.AgentBriefStatusModel; import org.bench4q.share.models.agent.statistics.AgentBehaviorsBriefModel; import org.bench4q.share.models.agent.statistics.AgentPageBriefModel; @@ -86,6 +87,16 @@ public class TestController { } + @RequestMapping(value = "/briefAll/{runId}", method = RequestMethod.GET) + @ResponseBody + public TestBriefStatusModel briefAll(@PathVariable UUID runId) { + TestBriefStatusModel result = new TestBriefStatusModel(); + result.setScenarioBriefModel(this.brief(runId)); + result.setPagesBriefModel(this.pagesBrief(runId)); + result.setBehaviorsBriefModel(this.behaviorsBrief(runId)); + return result; + } + @RequestMapping(value = "/brief/{runId}/{behaviorId}", method = RequestMethod.GET) @ResponseBody public BehaviorBriefModel behaviorBrief(@PathVariable UUID runId, diff --git a/src/main/java/org/bench4q/agent/plugin/basic/http/HttpPlugin.java b/src/main/java/org/bench4q/agent/plugin/basic/http/HttpPlugin.java index 99d6f9dd..77792ea9 100644 --- a/src/main/java/org/bench4q/agent/plugin/basic/http/HttpPlugin.java +++ b/src/main/java/org/bench4q/agent/plugin/basic/http/HttpPlugin.java @@ -163,28 +163,53 @@ public class HttpPlugin { List> varExtractExpressionList = ParameterParser .getTable(respVarsToSaveInSession); for (List row : varExtractExpressionList) { - if (row.size() <= 3) { - continue; - } - String varName = row.get(0); - String varExpression = row.get(1); - String varLeftBoundry = row.get(2); - String varRightBoundry = row.get(3); - Matcher matcher = Pattern.compile(varExpression).matcher( - responseBodyAsString); - if (matcher.find()) { - String matchedVariable = matcher.group(); - int indexOfLB = matchedVariable.indexOf(varLeftBoundry); - int indexOfRB = matchedVariable.indexOf(varRightBoundry); - keyValues - .put(varName, - matchedVariable.substring(indexOfLB - + varLeftBoundry.length(), indexOfRB)); - } + keyValues.putAll(doExtractParamByRow(row, responseBodyAsString)); } return keyValues; } + private Map doExtractParamByRow(List row, + String responseBody) { + Map result = new LinkedHashMap(); + if (row.size() <= 3) { + return result; + } + String varName = row.get(0); + String varExpression = row.get(1); + String varLeftBoundry = row.get(2); + String varRightBoundry = row.get(3); + + if (!isValid(varExpression)) { + result.put( + varName, + extractExactlyValueWith(varLeftBoundry, varRightBoundry, + responseBody)); + return result; + } + + Matcher matcher = Pattern.compile(varExpression).matcher(responseBody); + if (!matcher.find()) { + result.put( + varName, + extractExactlyValueWith(varLeftBoundry, varRightBoundry, + responseBody)); + return result; + } + result.put( + varName, + extractExactlyValueWith(varLeftBoundry, varRightBoundry, + matcher.group())); + return result; + } + + private String extractExactlyValueWith(String varLeftBoundry, + String varRightBoundry, String matchedVariable) { + int indexOfLB = matchedVariable.indexOf(varLeftBoundry); + int indexOfRB = matchedVariable.indexOf(varRightBoundry); + return matchedVariable.substring(indexOfLB + varLeftBoundry.length(), + indexOfRB); + } + /** * * @param url diff --git a/src/main/java/org/bench4q/agent/plugin/basic/http/ParameterParser.java b/src/main/java/org/bench4q/agent/plugin/basic/http/ParameterParser.java index 2a62ddb0..253c9fd3 100644 --- a/src/main/java/org/bench4q/agent/plugin/basic/http/ParameterParser.java +++ b/src/main/java/org/bench4q/agent/plugin/basic/http/ParameterParser.java @@ -55,40 +55,8 @@ public abstract class ParameterParser { public static List> parseResponseVariables(String value) { return getTable(value); - // Map nvPairs = new LinkedHashMap(); - // String[] entrys = value.split("#!"); - // - // for (String entry : entrys) { - // String[] nv = entry.split("#"); - // if (nv.length <= 1) { - // continue; - // } - // nvPairs.put(extractHeaderValue(nv[0].trim()), - // extractHeaderValue(nv[1].trim())); - // } - // return nvPairs; } - // private static NameValuePair distillHeader(String name, String value) { - // return new NameValuePair(extractHeaderName(name), - // extractHeaderValue(value)); - // } - // - // private static String extractHeaderValue(String value) { - // if (!value.toLowerCase() - // .startsWith(ParameterConstant.HEADER_VALUE_SIGN)) { - // return value; - // } - // return value.substring(ParameterConstant.HEADER_VALUE_SIGN.length()); - // } - // - // private static String extractHeaderName(String name) { - // if (!name.toLowerCase().startsWith(ParameterConstant.HEADER_NAME_SIGN)) { - // return name; - // } - // return name.substring(ParameterConstant.HEADER_NAME_SIGN.length()); - // } - /** * This method analyzes the value to be set in the table, and remove all * escape characters diff --git a/src/main/java/org/bench4q/agent/plugin/basic/http/format/Table.java b/src/main/java/org/bench4q/agent/plugin/basic/http/format/Table.java new file mode 100644 index 00000000..db598bd0 --- /dev/null +++ b/src/main/java/org/bench4q/agent/plugin/basic/http/format/Table.java @@ -0,0 +1,5 @@ +package org.bench4q.agent.plugin.basic.http.format; + +public class Table { + +} diff --git a/src/test/java/org/bench4q/agent/test/scenario/utils/Test_ParameterParser.java b/src/test/java/org/bench4q/agent/test/scenario/utils/Test_ParameterParser.java index f8cd12ed..d3690e3a 100644 --- a/src/test/java/org/bench4q/agent/test/scenario/utils/Test_ParameterParser.java +++ b/src/test/java/org/bench4q/agent/test/scenario/utils/Test_ParameterParser.java @@ -9,7 +9,6 @@ import java.util.List; import org.apache.commons.httpclient.NameValuePair; import org.bench4q.agent.plugin.basic.http.ParameterConstant; import org.bench4q.agent.plugin.basic.http.ParameterParser; -import org.bench4q.share.helper.TestHelper; import org.junit.Test; public class Test_ParameterParser { From 72ab634758e5443eabb0e6893189d9b52a66867d Mon Sep 17 00:00:00 2001 From: coderfengyun Date: Wed, 12 Mar 2014 16:45:17 +0800 Subject: [PATCH 173/196] refactor out the table class --- .../agent/plugin/basic/http/HttpPlugin.java | 24 +- .../plugin/basic/http/ParameterConstant.java | 21 - .../agent/plugin/basic/http/format/Table.java | 5 - .../util}/ParameterParser.java | 94 +--- .../bench4q/agent/scenario/util/Table.java | 116 +++++ .../agent/test/plugin/Test_HttpPlugin.java | 2 +- .../scenario/utils/Test_ParameterParser.java | 64 ++- .../test/storage/TestDoubleBufferStorage.java | 408 +++++++++--------- 8 files changed, 397 insertions(+), 337 deletions(-) delete mode 100644 src/main/java/org/bench4q/agent/plugin/basic/http/format/Table.java rename src/main/java/org/bench4q/agent/{plugin/basic/http => scenario/util}/ParameterParser.java (59%) create mode 100644 src/main/java/org/bench4q/agent/scenario/util/Table.java diff --git a/src/main/java/org/bench4q/agent/plugin/basic/http/HttpPlugin.java b/src/main/java/org/bench4q/agent/plugin/basic/http/HttpPlugin.java index 77792ea9..9d7dacee 100644 --- a/src/main/java/org/bench4q/agent/plugin/basic/http/HttpPlugin.java +++ b/src/main/java/org/bench4q/agent/plugin/basic/http/HttpPlugin.java @@ -12,6 +12,7 @@ import java.io.UnsupportedEncodingException; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; +import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; @@ -33,6 +34,8 @@ import org.bench4q.agent.plugin.Behavior; import org.bench4q.agent.plugin.Parameter; import org.bench4q.agent.plugin.Plugin; import org.bench4q.agent.plugin.result.HttpReturn; +import org.bench4q.agent.scenario.util.ParameterParser; +import org.bench4q.agent.scenario.util.Table; @Plugin("Http") public class HttpPlugin { @@ -95,14 +98,13 @@ public class HttpPlugin { * * @param url * @param queryParams - * (List) QueryParams should be split by ';' + * (NField) QueryParams should be split by ';' * @param headers - * (List)headers should be split by '|;', and in a header key and - * value are split by '|' + * (Table)has two columns, such as header and value * * @param respVarsToSaveInSession - * (List) should be split by '#!', and in a respVar, the key and - * Regular Expression should be split by '#' + * (Table) has four columns, such as varName, + * varRegularExpression, leftBoundry, and rightBoundry * @return */ @Behavior("Get") @@ -160,8 +162,16 @@ public class HttpPlugin { private Map doExtractResponseVariables( String respVarsToSaveInSession, String responseBodyAsString) { Map keyValues = new LinkedHashMap(); - List> varExtractExpressionList = ParameterParser - .getTable(respVarsToSaveInSession); + List> varExtractExpressionList = Table.buildTable( + respVarsToSaveInSession, new LinkedList() { + private static final long serialVersionUID = -923211006660227362L; + { + add("varName"); + add("varRegularExpression"); + add("leftBoundry"); + add("rightBoundry"); + } + }).getRealContent(); for (List row : varExtractExpressionList) { keyValues.putAll(doExtractParamByRow(row, responseBodyAsString)); } diff --git a/src/main/java/org/bench4q/agent/plugin/basic/http/ParameterConstant.java b/src/main/java/org/bench4q/agent/plugin/basic/http/ParameterConstant.java index 96c18334..691565f5 100644 --- a/src/main/java/org/bench4q/agent/plugin/basic/http/ParameterConstant.java +++ b/src/main/java/org/bench4q/agent/plugin/basic/http/ParameterConstant.java @@ -1,26 +1,5 @@ package org.bench4q.agent.plugin.basic.http; public class ParameterConstant { - public static final String HEADER_VALUE_SIGN = "value="; - public static final String HEADER_NAME_SIGN = "header="; - - public static final String RESP_VAR_NAMW = "varName="; - public static final String RESP_VAR_REGX = "varReg="; - public static final String escape = "\\"; - /** - * About table - */ - public static final String TABLE_ROW_SEPARATOR = "|;"; - public static final String TABLE_COLUMN_SEPARATOR = "|"; - public static final String TABLE_ROW_SEPARATOR_TAIL = ";"; - - public static final String ESCAPE_TABLE_ROW_SEPARATOR = escape - + TABLE_ROW_SEPARATOR; - public static final String ESCAPE_TABLE_COLUMN_SEPARATOR = escape - + TABLE_COLUMN_SEPARATOR; - - /** - * - */ } diff --git a/src/main/java/org/bench4q/agent/plugin/basic/http/format/Table.java b/src/main/java/org/bench4q/agent/plugin/basic/http/format/Table.java deleted file mode 100644 index db598bd0..00000000 --- a/src/main/java/org/bench4q/agent/plugin/basic/http/format/Table.java +++ /dev/null @@ -1,5 +0,0 @@ -package org.bench4q.agent.plugin.basic.http.format; - -public class Table { - -} diff --git a/src/main/java/org/bench4q/agent/plugin/basic/http/ParameterParser.java b/src/main/java/org/bench4q/agent/scenario/util/ParameterParser.java similarity index 59% rename from src/main/java/org/bench4q/agent/plugin/basic/http/ParameterParser.java rename to src/main/java/org/bench4q/agent/scenario/util/ParameterParser.java index 253c9fd3..44fce3af 100644 --- a/src/main/java/org/bench4q/agent/plugin/basic/http/ParameterParser.java +++ b/src/main/java/org/bench4q/agent/scenario/util/ParameterParser.java @@ -1,4 +1,4 @@ -package org.bench4q.agent.plugin.basic.http; +package org.bench4q.agent.scenario.util; import java.util.ArrayList; import java.util.LinkedList; @@ -6,6 +6,7 @@ import java.util.List; import java.util.StringTokenizer; import org.apache.commons.httpclient.NameValuePair; +import org.bench4q.agent.plugin.basic.http.ParameterConstant; /** * @@ -14,8 +15,11 @@ import org.apache.commons.httpclient.NameValuePair; */ public abstract class ParameterParser { + private static final String RadioGroup_SEPARATOR = ";"; + private static final String NFIELD_SEPARATOR = RadioGroup_SEPARATOR; + static public List getNField(String value) { - StringTokenizer st = new StringTokenizer(value, ";", false); + StringTokenizer st = new StringTokenizer(value, NFIELD_SEPARATOR, false); List result = new ArrayList(); while (st.hasMoreTokens()) { String token = st.nextToken(); @@ -25,7 +29,8 @@ public abstract class ParameterParser { } static public String getRadioGroup(String value) { - List realTokens = getRealTokens(";", value, false); + List realTokens = getRealTokens(RadioGroup_SEPARATOR, value, + false); if (realTokens.size() == 0) { return ""; } else { @@ -43,8 +48,15 @@ public abstract class ParameterParser { static public List parseHeaders(String value) { List nvPairs = new LinkedList(); - for (List entry : getTable(value)) { - if (entry.size() != 2) { + Table headerTable = Table.buildTable(value, new LinkedList() { + private static final long serialVersionUID = 3498984411571605459L; + { + add("header"); + add("value"); + } + }); + for (List entry : headerTable.getRealContent()) { + if (entry.size() != headerTable.getColumnCount()) { continue; } nvPairs.add(new NameValuePair(entry.get(0).trim(), entry.get(1) @@ -53,78 +65,6 @@ public abstract class ParameterParser { return nvPairs; } - public static List> parseResponseVariables(String value) { - return getTable(value); - } - - /** - * This method analyzes the value to be set in the table, and remove all - * escape characters - * - * @param value - * The value containing the serialization of all values of the - * table - * @return The vector containing all the entries, each entries is in a - * vector, which contains the string values - */ - static public List> getTable(String value) { - List tempEntries = getRealTokens( - ParameterConstant.ESCAPE_TABLE_ROW_SEPARATOR, value, false); - // now analyze all entries values, and get the '|' separator - List> allValues = new ArrayList>(); - for (int i = 0; i < tempEntries.size(); i++) { - String tempEntry = tempEntries.get(i); - List values = getRealTokens( - ParameterConstant.ESCAPE_TABLE_COLUMN_SEPARATOR, tempEntry, - true); - arrangeTheTableChildSeparator(values); - allValues.add(values); - } - // now analyze all values, and get the '=' separator - return extractValueFromWellFormedTable(allValues); - } - - public static List> extractValueFromWellFormedTable( - List> allValues) { - List> result = new LinkedList>(); - for (int i = 0; i < allValues.size(); i++) { - List resultValues = new ArrayList(); - List tempValues = allValues.get(i); - for (int j = 0; j < tempValues.size(); j++) { - String v = tempValues.get(j); - List temp = getRealTokens("=", v, false); - String res; - if (temp.size() <= 1) { - continue; - } - res = temp.get(1); - // res = unescape(res); - resultValues.add(res); - } - result.add(resultValues); - } - return result; - } - - /** - * This method check if the table_separator after escape is split by the - * table_entry_separator - * - * @param values - */ - private static void arrangeTheTableChildSeparator(List values) { - for (int i = 0; i < values.size(); i++) { - - String currentToken = values.get(i); - if (currentToken.equals(ParameterConstant.TABLE_ROW_SEPARATOR_TAIL) - && i > 0) { - values.set(i - 1, values.get(i - 1) - + ParameterConstant.TABLE_ROW_SEPARATOR_TAIL); - } - } - - } - /** * Get the number of escape character in the end of the string * diff --git a/src/main/java/org/bench4q/agent/scenario/util/Table.java b/src/main/java/org/bench4q/agent/scenario/util/Table.java new file mode 100644 index 00000000..0cbe3628 --- /dev/null +++ b/src/main/java/org/bench4q/agent/scenario/util/Table.java @@ -0,0 +1,116 @@ +package org.bench4q.agent.scenario.util; + +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.List; + +import org.bench4q.agent.plugin.basic.http.ParameterConstant; + +public class Table { + public static final String ROW_SEPARATOR = "|;"; + public static final String COLUMN_SEPARATOR = "|"; + public static final String ROW_SEPARATOR_TAIL = ";"; + + public static final String ESCAPE_ROW_SEPARATOR = ParameterConstant.escape + + ROW_SEPARATOR; + public static final String ESCAPE_COLUMN_SEPARATOR = ParameterConstant.escape + + COLUMN_SEPARATOR; + private List> realContent; + private List columnLables; + + public List> getRealContent() { + return realContent; + } + + private void setRealContent(List> realContent) { + this.realContent = realContent; + } + + private List getColumnLables() { + return columnLables; + } + + private void setColumnLables(List columnLables) { + this.columnLables = columnLables; + } + + private Table() { + this.setColumnLables(new LinkedList()); + } + + public static Table buildTable(String value, + List columnLablesInSequence) { + Table result = new Table(); + result.setRealContent(buildTableContent(value)); + result.setColumnLables(columnLablesInSequence); + return result; + } + + /** + * This method analyzes the value to be set in the table, and remove all + * escape characters + * + * @param value + * The value containing the serialization of all values of the + * table + * @return The vector containing all the entries, each entries is in a + * vector, which contains the string values + */ + private static List> buildTableContent(String value) { + List tempEntries = ParameterParser.getRealTokens( + Table.ESCAPE_ROW_SEPARATOR, value, false); + List> allValues = new ArrayList>(); + for (int i = 0; i < tempEntries.size(); i++) { + String tempEntry = tempEntries.get(i); + List values = ParameterParser.getRealTokens( + Table.ESCAPE_COLUMN_SEPARATOR, tempEntry, true); + arrangeTableWithRowSeparatorTail(values); + allValues.add(values); + } + // now analyze all values, and get the '=' separator + return extractValueFromWellFormedTable(allValues); + } + + private static List> extractValueFromWellFormedTable( + List> allValues) { + List> result = new LinkedList>(); + for (int i = 0; i < allValues.size(); i++) { + List resultValues = new ArrayList(); + List tempValues = allValues.get(i); + for (int j = 0; j < tempValues.size(); j++) { + String v = tempValues.get(j); + List temp = ParameterParser + .getRealTokens("=", v, false); + String res; + if (temp.size() <= 1) { + continue; + } + res = temp.get(1); + resultValues.add(res); + } + result.add(resultValues); + } + return result; + } + + /** + * This method check if the table_separator after escape is split by the + * table_entry_separator + * + * @param values + */ + private static void arrangeTableWithRowSeparatorTail(List values) { + for (int i = 0; i < values.size(); i++) { + + String currentToken = values.get(i); + if (currentToken.equals(Table.ROW_SEPARATOR_TAIL) && i > 0) { + values.set(i - 1, values.get(i - 1) + Table.ROW_SEPARATOR_TAIL); + } + } + + } + + public int getColumnCount() { + return this.getColumnLables().size(); + } +} diff --git a/src/test/java/org/bench4q/agent/test/plugin/Test_HttpPlugin.java b/src/test/java/org/bench4q/agent/test/plugin/Test_HttpPlugin.java index 575db67e..c7a89826 100644 --- a/src/test/java/org/bench4q/agent/test/plugin/Test_HttpPlugin.java +++ b/src/test/java/org/bench4q/agent/test/plugin/Test_HttpPlugin.java @@ -121,7 +121,7 @@ public class Test_HttpPlugin { + "}"; @SuppressWarnings("unchecked") Map nameValueMap = (Map) TestHelper - .invokePrivateMethod(this.getHttpPlugin().getClass(), + .invokePrivate(this.getHttpPlugin().getClass(), this.getHttpPlugin(), "doExtractResponseVariables", new Class[] { String.class, String.class }, new Object[] { respVarsToSave, responseBodyAsString }); diff --git a/src/test/java/org/bench4q/agent/test/scenario/utils/Test_ParameterParser.java b/src/test/java/org/bench4q/agent/test/scenario/utils/Test_ParameterParser.java index d3690e3a..c3e5153d 100644 --- a/src/test/java/org/bench4q/agent/test/scenario/utils/Test_ParameterParser.java +++ b/src/test/java/org/bench4q/agent/test/scenario/utils/Test_ParameterParser.java @@ -7,8 +7,9 @@ import java.util.LinkedList; import java.util.List; import org.apache.commons.httpclient.NameValuePair; -import org.bench4q.agent.plugin.basic.http.ParameterConstant; -import org.bench4q.agent.plugin.basic.http.ParameterParser; +import org.bench4q.agent.scenario.util.ParameterParser; +import org.bench4q.agent.scenario.util.Table; +import org.bench4q.share.helper.TestHelper; import org.junit.Test; public class Test_ParameterParser { @@ -44,34 +45,42 @@ public class Test_ParameterParser { @Test public void testGetRealTokenForContainSeparator() { List entryList = ParameterParser.getRealTokens( - ParameterConstant.ESCAPE_TABLE_ROW_SEPARATOR, - TESTCASE1_CONTAIN_SEPARATOR, true); + Table.ESCAPE_ROW_SEPARATOR, TESTCASE1_CONTAIN_SEPARATOR, true); assertEquals(1, entryList.size()); assertEquals("header=accept|value=asdfasdf|;", entryList.get(0)); } @Test - public void testGetRealTokenForContainManyEscapse() { + public void testGetRealTokenForContainManyEscapse() throws Exception { List rowList = ParameterParser.getRealTokens( - ParameterConstant.ESCAPE_TABLE_ROW_SEPARATOR, - testcaseWithEscapes, false); + Table.ESCAPE_ROW_SEPARATOR, testcaseWithEscapes, false); assertEquals(1, rowList.size()); assertEquals("varName=ticket|varExpression=\"ticket\":\\s*?\"\\w+\",", rowList.get(0)); final List columnList = ParameterParser.getRealTokens( - ParameterConstant.ESCAPE_TABLE_COLUMN_SEPARATOR, - rowList.get(0), true); + Table.ESCAPE_COLUMN_SEPARATOR, rowList.get(0), true); assertEquals(2, columnList.size()); assertEquals("varName=ticket", columnList.get(0)); assertEquals("varExpression=\"ticket\":\\s*?\"\\w+\",", columnList.get(1)); - List> result = ParameterParser - .extractValueFromWellFormedTable(new LinkedList>() { - private static final long serialVersionUID = 1L; - { - add(columnList); - } - }); + @SuppressWarnings("unchecked") + List> result = (List>) TestHelper + .invokePrivate(Table.class, null, + "extractValueFromWellFormedTable", + new Class[] { List.class }, + new Object[] { new LinkedList>() { + private static final long serialVersionUID = 1L; + { + add(columnList); + } + } }); + // Table.extractValueFromWellFormedTable(new LinkedList>() + // { + // private static final long serialVersionUID = 1L; + // { + // add(columnList); + // } + // }); assertEquals(1, result.size()); assertEquals(2, result.get(0).size()); assertEquals("ticket", result.get(0).get(0)); @@ -81,7 +90,7 @@ public class Test_ParameterParser { @Test public void testGetRealTokensForMultiSeparator() { List entryList = ParameterParser.getRealTokens( - ParameterConstant.ESCAPE_TABLE_ROW_SEPARATOR, testcase2, false); + Table.ESCAPE_ROW_SEPARATOR, testcase2, false); assertEquals(2, entryList.size()); assertEquals("header=accept|value=fafsd", entryList.get(0)); assertEquals("varName=abc|varValue=234", entryList.get(1)); @@ -89,8 +98,8 @@ public class Test_ParameterParser { @Test public void testGetTableForSeparator() { - List> resultEntries = ParameterParser - .getTable(TESTCASE1_CONTAIN_SEPARATOR); + List> resultEntries = buildHeaderTable( + TESTCASE1_CONTAIN_SEPARATOR).getRealContent(); assertEquals(1, resultEntries.size()); assertEquals(2, resultEntries.get(0).size()); assertEquals("accept", resultEntries.get(0).get(0)); @@ -99,7 +108,8 @@ public class Test_ParameterParser { @Test public void testGetTableForMultipleHeader() { - List> resultEntries = ParameterParser.getTable(testcase2); + List> resultEntries = buildHeaderTable(testcase2) + .getRealContent(); assertEquals(2, resultEntries.size()); assertEquals("fafsd", resultEntries.get(0).get(1)); assertEquals("accept", resultEntries.get(0).get(0)); @@ -107,10 +117,20 @@ public class Test_ParameterParser { assertEquals("abc", resultEntries.get(1).get(0)); } + private Table buildHeaderTable(String value) { + return Table.buildTable(value, new LinkedList() { + private static final long serialVersionUID = -6734367739974282326L; + { + add("header"); + add("value"); + } + }); + } + @Test public void testGetTableWithManyEscapse() { - List> resultTable = ParameterParser - .getTable(testcaseWithEscapes); + List> resultTable = buildHeaderTable(testcaseWithEscapes) + .getRealContent(); assertEquals(1, resultTable.size()); assertEquals(2, resultTable.get(0).size()); assertEquals("ticket", resultTable.get(0).get(0)); diff --git a/src/test/java/org/bench4q/agent/test/storage/TestDoubleBufferStorage.java b/src/test/java/org/bench4q/agent/test/storage/TestDoubleBufferStorage.java index f7f4cf86..cc068736 100644 --- a/src/test/java/org/bench4q/agent/test/storage/TestDoubleBufferStorage.java +++ b/src/test/java/org/bench4q/agent/test/storage/TestDoubleBufferStorage.java @@ -1,204 +1,204 @@ -package org.bench4q.agent.test.storage; - -import static org.junit.Assert.*; - -import java.io.File; -import java.io.IOException; -import java.util.List; - -import org.bench4q.agent.storage.Buffer; -import org.bench4q.agent.storage.DoubleBufferStorage; -import org.bench4q.share.helper.TestHelper; -import org.junit.After; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.annotation.DirtiesContext.ClassMode; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(locations = { "classpath*:/org/bench4q/agent/config/application-context.xml" }) -public class TestDoubleBufferStorage { - private DoubleBufferStorage doubleBufferStorage; - private static String SAVE_DIR = "StorageTest" - + System.getProperty("file.separator"); - private static final String INPUT_FILE_PATH = SAVE_DIR + "testInput.txt"; - private static String SAVE_PATH = SAVE_DIR + "test.txt"; - - private DoubleBufferStorage getDoubleBufferStorage() { - return doubleBufferStorage; - } - - @Autowired - private void setDoubleBufferStorage(DoubleBufferStorage doubleBufferStorage) { - this.doubleBufferStorage = doubleBufferStorage; - } - - public TestDoubleBufferStorage() throws IOException { - File dir = new File(SAVE_DIR); - if (!dir.exists()) { - dir.mkdirs(); - } - File outPutFile = new File(SAVE_PATH); - if (!outPutFile.exists()) { - outPutFile.createNewFile(); - } - File inputFile = new File(INPUT_FILE_PATH); - if (!inputFile.exists()) { - inputFile.createNewFile(); - } - } - - @After - public void cleanUp() { - File file = new File(SAVE_DIR + "test.txt"); - if (file.exists()) { - file.delete(); - } - for (int i = 0; i < 4; ++i) { - String realSavePathString = this.getDoubleBufferStorage() - .calculateSavePath(SAVE_PATH, i); - File output = new File(realSavePathString); - if (output.exists()) { - output.delete(); - } - } - } - - @SuppressWarnings("unchecked") - @Test - public void testWriteWithLittleContent() throws Exception { - this.getDoubleBufferStorage().writeFile("test", SAVE_PATH); - assertEquals( - 48 * 1024 - 4, - ((Buffer) invokePrivateMethod(this.getDoubleBufferStorage() - .getClass(), this.getDoubleBufferStorage(), - "getCurrentBuffer", null, null)).getRemainSize()); - List buffers = ((List) invokePrivateMethod(this - .getDoubleBufferStorage().getClass(), - this.getDoubleBufferStorage(), "getBufferList", null, null)); - for (int i = 0; i < buffers.size() - && i != (Integer) invokePrivateMethod(this - .getDoubleBufferStorage().getClass(), - this.getDoubleBufferStorage(), "getCurrentBufferIndex", - null, null); i++) { - assertEquals(48 * 1024, buffers.get(i).getRemainSize()); - } - } - - @Test - @DirtiesContext(classMode = ClassMode.AFTER_EACH_TEST_METHOD) - public void testWriteWithJustLargerThanOneBufferContent() throws Exception { - String realSavePathString = this.getDoubleBufferStorage() - .calculateSavePath( - SAVE_PATH, - (Integer) invokePrivateMethod(this - .getDoubleBufferStorage().getClass(), this - .getDoubleBufferStorage(), - "getCurrentBufferIndex", null, null)); - doWriteFile(95); - while (!this.getDoubleBufferStorage().forTest.isSuccess()) { - Thread.sleep(1000); - } - String readContent = this.getDoubleBufferStorage().readFiles( - realSavePathString); - assertTrue(readContent.length() <= 48 * 1024); - assertTrue(readContent.length() >= 46 * 1024); - assertTrue(readContent.indexOf("encoding") > 0); - Buffer currentBuffer = (Buffer) invokePrivateMethod(this - .getDoubleBufferStorage().getClass(), - this.getDoubleBufferStorage(), "getCurrentBuffer", null, null); - System.out.println(currentBuffer.getCurrentPos()); - System.out - .println((Integer) invokePrivateMethod(this - .getDoubleBufferStorage().getClass(), this - .getDoubleBufferStorage(), "getCurrentBufferIndex", - null, null)); - assertTrue(currentBuffer.getCurrentPos() == 1563); - } - - private void doWriteFile(int size) { - String saveContent = this.getDoubleBufferStorage().readFiles( - INPUT_FILE_PATH); - for (int i = 0; i < size; i++) { - this.getDoubleBufferStorage().writeFile(saveContent, SAVE_PATH); - } - } - - @Test - @DirtiesContext(classMode = ClassMode.AFTER_EACH_TEST_METHOD) - public void testWriteWithJustLargerThanTwoBufferContent() - throws InterruptedException { - doWriteFile(92 * 2 + 2); - while (!this.getDoubleBufferStorage().forTest.isSuccess()) { - Thread.sleep(1000); - } - assertEquals(47932 * 2, getResultLength()); - } - - @Test - @DirtiesContext(classMode = ClassMode.AFTER_EACH_TEST_METHOD) - public void testWriteContentLargerThanThree() throws InterruptedException { - doWriteFile(92 * 3 + 2); - while (!this.getDoubleBufferStorage().forTest.isSuccess()) { - Thread.sleep(1000); - } - int resultLength = getResultLength(); - assertEquals(47932 * 3, resultLength); - } - - private int getResultLength() { - int resultLength = 0; - for (int i = 0; i < 4; i++) { - String path = this.getDoubleBufferStorage().calculateSavePath( - SAVE_PATH, i); - if (!new File(path).exists()) { - continue; - } - String readContentString = this.getDoubleBufferStorage().readFiles( - path); - resultLength += readContentString.length(); - } - return resultLength; - } - - @Test - public void testChangeBuffer() throws Exception { - @SuppressWarnings("unchecked") - List buffers = (List) invokePrivateMethod(this - .getDoubleBufferStorage().getClass(), - this.getDoubleBufferStorage(), "getBufferList", null, null); - buffers.get(0).setCurrentPos(48 * 1024 - 1220); - buffers.get(1).setCurrentPos(0); - invokePrivateMethod(getDoubleBufferStorage().getClass(), - this.getDoubleBufferStorage(), "setCurrentBufferIndex", - new Class[] { int.class }, new Object[] { 0 }); - invokePrivateMethod(this.getDoubleBufferStorage().getClass(), - this.getDoubleBufferStorage(), "changeToTheMaxRemainBuffer", - null, null); - - assertEquals(1220, buffers.get(0).getRemainSize()); - assertEquals(48 * 1024, buffers.get(1).getRemainSize()); - assertEquals( - 1, - invokePrivateMethod(this.getDoubleBufferStorage().getClass(), - this.getDoubleBufferStorage(), "getCurrentBufferIndex", - null, null)); - } - - private static Object invokePrivateMethod(Class containerClass, - Object targetObject, String methodName, Class[] paramClasses, - Object[] params) throws Exception { - return TestHelper.invokePrivateMethod(containerClass, targetObject, - methodName, paramClasses, params); - } - - @Test - public void testReadFiles() { - String content = this.getDoubleBufferStorage().readFiles( - INPUT_FILE_PATH); - assertEquals(content.length(), 521); - } -} +package org.bench4q.agent.test.storage; + +import static org.junit.Assert.*; + +import java.io.File; +import java.io.IOException; +import java.util.List; + +import org.bench4q.agent.storage.Buffer; +import org.bench4q.agent.storage.DoubleBufferStorage; +import org.bench4q.share.helper.TestHelper; +import org.junit.After; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.annotation.DirtiesContext.ClassMode; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(locations = { "classpath*:/org/bench4q/agent/config/application-context.xml" }) +public class TestDoubleBufferStorage { + private DoubleBufferStorage doubleBufferStorage; + private static String SAVE_DIR = "StorageTest" + + System.getProperty("file.separator"); + private static final String INPUT_FILE_PATH = SAVE_DIR + "testInput.txt"; + private static String SAVE_PATH = SAVE_DIR + "test.txt"; + + private DoubleBufferStorage getDoubleBufferStorage() { + return doubleBufferStorage; + } + + @Autowired + private void setDoubleBufferStorage(DoubleBufferStorage doubleBufferStorage) { + this.doubleBufferStorage = doubleBufferStorage; + } + + public TestDoubleBufferStorage() throws IOException { + File dir = new File(SAVE_DIR); + if (!dir.exists()) { + dir.mkdirs(); + } + File outPutFile = new File(SAVE_PATH); + if (!outPutFile.exists()) { + outPutFile.createNewFile(); + } + File inputFile = new File(INPUT_FILE_PATH); + if (!inputFile.exists()) { + inputFile.createNewFile(); + } + } + + @After + public void cleanUp() { + File file = new File(SAVE_DIR + "test.txt"); + if (file.exists()) { + file.delete(); + } + for (int i = 0; i < 4; ++i) { + String realSavePathString = this.getDoubleBufferStorage() + .calculateSavePath(SAVE_PATH, i); + File output = new File(realSavePathString); + if (output.exists()) { + output.delete(); + } + } + } + + @SuppressWarnings("unchecked") + @Test + public void testWriteWithLittleContent() throws Exception { + this.getDoubleBufferStorage().writeFile("test", SAVE_PATH); + assertEquals( + 48 * 1024 - 4, + ((Buffer) invokePrivateMethod(this.getDoubleBufferStorage() + .getClass(), this.getDoubleBufferStorage(), + "getCurrentBuffer", null, null)).getRemainSize()); + List buffers = ((List) invokePrivateMethod(this + .getDoubleBufferStorage().getClass(), + this.getDoubleBufferStorage(), "getBufferList", null, null)); + for (int i = 0; i < buffers.size() + && i != (Integer) invokePrivateMethod(this + .getDoubleBufferStorage().getClass(), + this.getDoubleBufferStorage(), "getCurrentBufferIndex", + null, null); i++) { + assertEquals(48 * 1024, buffers.get(i).getRemainSize()); + } + } + + @Test + @DirtiesContext(classMode = ClassMode.AFTER_EACH_TEST_METHOD) + public void testWriteWithJustLargerThanOneBufferContent() throws Exception { + String realSavePathString = this.getDoubleBufferStorage() + .calculateSavePath( + SAVE_PATH, + (Integer) invokePrivateMethod(this + .getDoubleBufferStorage().getClass(), this + .getDoubleBufferStorage(), + "getCurrentBufferIndex", null, null)); + doWriteFile(95); + while (!this.getDoubleBufferStorage().forTest.isSuccess()) { + Thread.sleep(1000); + } + String readContent = this.getDoubleBufferStorage().readFiles( + realSavePathString); + assertTrue(readContent.length() <= 48 * 1024); + assertTrue(readContent.length() >= 46 * 1024); + assertTrue(readContent.indexOf("encoding") > 0); + Buffer currentBuffer = (Buffer) invokePrivateMethod(this + .getDoubleBufferStorage().getClass(), + this.getDoubleBufferStorage(), "getCurrentBuffer", null, null); + System.out.println(currentBuffer.getCurrentPos()); + System.out + .println((Integer) invokePrivateMethod(this + .getDoubleBufferStorage().getClass(), this + .getDoubleBufferStorage(), "getCurrentBufferIndex", + null, null)); + assertTrue(currentBuffer.getCurrentPos() == 1563); + } + + private void doWriteFile(int size) { + String saveContent = this.getDoubleBufferStorage().readFiles( + INPUT_FILE_PATH); + for (int i = 0; i < size; i++) { + this.getDoubleBufferStorage().writeFile(saveContent, SAVE_PATH); + } + } + + @Test + @DirtiesContext(classMode = ClassMode.AFTER_EACH_TEST_METHOD) + public void testWriteWithJustLargerThanTwoBufferContent() + throws InterruptedException { + doWriteFile(92 * 2 + 2); + while (!this.getDoubleBufferStorage().forTest.isSuccess()) { + Thread.sleep(1000); + } + assertEquals(47932 * 2, getResultLength()); + } + + @Test + @DirtiesContext(classMode = ClassMode.AFTER_EACH_TEST_METHOD) + public void testWriteContentLargerThanThree() throws InterruptedException { + doWriteFile(92 * 3 + 2); + while (!this.getDoubleBufferStorage().forTest.isSuccess()) { + Thread.sleep(1000); + } + int resultLength = getResultLength(); + assertEquals(47932 * 3, resultLength); + } + + private int getResultLength() { + int resultLength = 0; + for (int i = 0; i < 4; i++) { + String path = this.getDoubleBufferStorage().calculateSavePath( + SAVE_PATH, i); + if (!new File(path).exists()) { + continue; + } + String readContentString = this.getDoubleBufferStorage().readFiles( + path); + resultLength += readContentString.length(); + } + return resultLength; + } + + @Test + public void testChangeBuffer() throws Exception { + @SuppressWarnings("unchecked") + List buffers = (List) invokePrivateMethod(this + .getDoubleBufferStorage().getClass(), + this.getDoubleBufferStorage(), "getBufferList", null, null); + buffers.get(0).setCurrentPos(48 * 1024 - 1220); + buffers.get(1).setCurrentPos(0); + invokePrivateMethod(getDoubleBufferStorage().getClass(), + this.getDoubleBufferStorage(), "setCurrentBufferIndex", + new Class[] { int.class }, new Object[] { 0 }); + invokePrivateMethod(this.getDoubleBufferStorage().getClass(), + this.getDoubleBufferStorage(), "changeToTheMaxRemainBuffer", + null, null); + + assertEquals(1220, buffers.get(0).getRemainSize()); + assertEquals(48 * 1024, buffers.get(1).getRemainSize()); + assertEquals( + 1, + invokePrivateMethod(this.getDoubleBufferStorage().getClass(), + this.getDoubleBufferStorage(), "getCurrentBufferIndex", + null, null)); + } + + private static Object invokePrivateMethod(Class containerClass, + Object targetObject, String methodName, Class[] paramClasses, + Object[] params) throws Exception { + return TestHelper.invokePrivate(containerClass, targetObject, + methodName, paramClasses, params); + } + + @Test + public void testReadFiles() { + String content = this.getDoubleBufferStorage().readFiles( + INPUT_FILE_PATH); + assertEquals(content.length(), 521); + } +} From 733a2acfafaab2307d3fce449fba295c286ab1da Mon Sep 17 00:00:00 2001 From: coderfengyun Date: Wed, 12 Mar 2014 17:16:41 +0800 Subject: [PATCH 174/196] refactor --- .../agent/plugin/basic/http/HttpPlugin.java | 34 +++++++--- .../agent/scenario/util/ParameterParser.java | 63 ++++--------------- .../bench4q/agent/scenario/util/Table.java | 3 +- .../scenario/utils/Test_ParameterParser.java | 55 +++++++++++----- 4 files changed, 77 insertions(+), 78 deletions(-) diff --git a/src/main/java/org/bench4q/agent/plugin/basic/http/HttpPlugin.java b/src/main/java/org/bench4q/agent/plugin/basic/http/HttpPlugin.java index 9d7dacee..3d41a5d9 100644 --- a/src/main/java/org/bench4q/agent/plugin/basic/http/HttpPlugin.java +++ b/src/main/java/org/bench4q/agent/plugin/basic/http/HttpPlugin.java @@ -55,7 +55,7 @@ public class HttpPlugin { void setHeaders(HttpMethod method, String headers) { if (headers != null) { - List nvPairs = ParameterParser.parseHeaders(headers); + List nvPairs = parseHeaders(headers); for (NameValuePair nv : nvPairs) { method.addRequestHeader(nv.getName(), nv.getValue()); } @@ -73,6 +73,26 @@ public class HttpPlugin { } } + List parseHeaders(String value) { + List nvPairs = new LinkedList(); + Table headerTable = ParameterParser.buildTable(value, + new LinkedList() { + private static final long serialVersionUID = 3498984411571605459L; + { + add("header"); + add("value"); + } + }); + for (List entry : headerTable.getRealContent()) { + if (entry.size() != headerTable.getColumnCount()) { + continue; + } + nvPairs.add(new NameValuePair(entry.get(0).trim(), entry.get(1) + .trim())); + } + return nvPairs; + } + private static NameValuePair[] setInputParameters( List inputParameters) { Set res = new HashSet(); @@ -162,8 +182,8 @@ public class HttpPlugin { private Map doExtractResponseVariables( String respVarsToSaveInSession, String responseBodyAsString) { Map keyValues = new LinkedHashMap(); - List> varExtractExpressionList = Table.buildTable( - respVarsToSaveInSession, new LinkedList() { + List> varExtractExpressionList = ParameterParser + .buildTable(respVarsToSaveInSession, new LinkedList() { private static final long serialVersionUID = -923211006660227362L; { add("varName"); @@ -242,11 +262,11 @@ public class HttpPlugin { setHeaders(method, headers); if (isValid(queryParams)) { method.setQueryString(setInputParameters(ParameterParser - .getNField(queryParams))); + .buildNField(queryParams))); } if (isValid(bodyParams)) { method.setRequestBody(setInputParameters(ParameterParser - .getNField(bodyParams))); + .buildNField(bodyParams))); } String contentType = getMethodContentType(method); if (isValid(bodyContent) && isValid(contentType)) { @@ -287,7 +307,7 @@ public class HttpPlugin { setHeaders(method, headers); if (isValid(queryParams)) { method.setQueryString(setInputParameters(ParameterParser - .getNField(queryParams))); + .buildNField(queryParams))); } String contentType = getMethodContentType(method); if (isValid(bodyContent) && isValid(contentType)) { @@ -311,7 +331,7 @@ public class HttpPlugin { setHeaders(method, headers); if (isValid(queryParams)) { method.setQueryString(setInputParameters(ParameterParser - .getNField(queryParams))); + .buildNField(queryParams))); } method.getParams().makeLenient(); return excuteMethod(method, respVarToSaveInSession); diff --git a/src/main/java/org/bench4q/agent/scenario/util/ParameterParser.java b/src/main/java/org/bench4q/agent/scenario/util/ParameterParser.java index 44fce3af..e8c81bf2 100644 --- a/src/main/java/org/bench4q/agent/scenario/util/ParameterParser.java +++ b/src/main/java/org/bench4q/agent/scenario/util/ParameterParser.java @@ -1,11 +1,9 @@ package org.bench4q.agent.scenario.util; import java.util.ArrayList; -import java.util.LinkedList; import java.util.List; import java.util.StringTokenizer; -import org.apache.commons.httpclient.NameValuePair; import org.bench4q.agent.plugin.basic.http.ParameterConstant; /** @@ -14,11 +12,10 @@ import org.bench4q.agent.plugin.basic.http.ParameterConstant; * */ public abstract class ParameterParser { - private static final String RadioGroup_SEPARATOR = ";"; private static final String NFIELD_SEPARATOR = RadioGroup_SEPARATOR; - static public List getNField(String value) { + static public List buildNField(String value) { StringTokenizer st = new StringTokenizer(value, NFIELD_SEPARATOR, false); List result = new ArrayList(); while (st.hasMoreTokens()) { @@ -28,7 +25,7 @@ public abstract class ParameterParser { return result; } - static public String getRadioGroup(String value) { + static public String buildRadioGroup(String value) { List realTokens = getRealTokens(RadioGroup_SEPARATOR, value, false); if (realTokens.size() == 0) { @@ -38,31 +35,16 @@ public abstract class ParameterParser { } } - static public List getCheckBox(String value) { - return getNField(value); + static public List buildCheckBox(String value) { + return buildNField(value); } - static public String getCombo(String value) { - return getRadioGroup(value); + static public String buildCombo(String value) { + return buildRadioGroup(value); } - static public List parseHeaders(String value) { - List nvPairs = new LinkedList(); - Table headerTable = Table.buildTable(value, new LinkedList() { - private static final long serialVersionUID = 3498984411571605459L; - { - add("header"); - add("value"); - } - }); - for (List entry : headerTable.getRealContent()) { - if (entry.size() != headerTable.getColumnCount()) { - continue; - } - nvPairs.add(new NameValuePair(entry.get(0).trim(), entry.get(1) - .trim())); - } - return nvPairs; + static public Table buildTable(String value, List columnLables) { + return Table.buildTable(value, columnLables); } /** @@ -72,7 +54,7 @@ public abstract class ParameterParser { * The string to be analyzed * @return 0 if no escape character was found, else the number */ - public static int getNumberOfEscapeCharacter(String value) { + private static int getNumberOfEscapeCharacter(String value) { int result = 0; if (value.length() > 0) { int last = value.lastIndexOf(ParameterConstant.escape); @@ -84,29 +66,6 @@ public abstract class ParameterParser { return result; } - /** - * Add escape separator before each separator - * - * @param separator - * The separator character - * @param value - * The value of the string to add the escape characters - * @return The string modified - */ - static public String addEscapeCharacter(String separator, String value) { - String result = ""; - StringTokenizer st = new StringTokenizer(value, separator, true); - while (st.hasMoreTokens()) { - String token = st.nextToken(); - if (token.equals(separator)) { - result = result.concat(ParameterConstant.escape + token); - } else { - result = result.concat(token); - } - } - return result; - } - /** * Split the string value with the separator, and check if there is no * escape character before the separator @@ -117,7 +76,7 @@ public abstract class ParameterParser { * The string value to be split * @return The vector containing each token */ - static public List getRealTokens(String separator, String value, + static List getRealTokens(String separator, String value, boolean toUnescapeSeparator) { List result = new ArrayList(); for (String entry : value.split(separator)) { @@ -141,7 +100,7 @@ public abstract class ParameterParser { * the string where some characters are escaped by '\' character * @return the unescaped string */ - static public String unescape(String value) { + static String unescape(String value) { StringBuilder result = new StringBuilder(); char c; boolean escape = false; // escape sequence diff --git a/src/main/java/org/bench4q/agent/scenario/util/Table.java b/src/main/java/org/bench4q/agent/scenario/util/Table.java index 0cbe3628..866287b3 100644 --- a/src/main/java/org/bench4q/agent/scenario/util/Table.java +++ b/src/main/java/org/bench4q/agent/scenario/util/Table.java @@ -38,8 +38,7 @@ public class Table { this.setColumnLables(new LinkedList()); } - public static Table buildTable(String value, - List columnLablesInSequence) { + static Table buildTable(String value, List columnLablesInSequence) { Table result = new Table(); result.setRealContent(buildTableContent(value)); result.setColumnLables(columnLablesInSequence); diff --git a/src/test/java/org/bench4q/agent/test/scenario/utils/Test_ParameterParser.java b/src/test/java/org/bench4q/agent/test/scenario/utils/Test_ParameterParser.java index c3e5153d..7554daf6 100644 --- a/src/test/java/org/bench4q/agent/test/scenario/utils/Test_ParameterParser.java +++ b/src/test/java/org/bench4q/agent/test/scenario/utils/Test_ParameterParser.java @@ -7,6 +7,7 @@ import java.util.LinkedList; import java.util.List; import org.apache.commons.httpclient.NameValuePair; +import org.bench4q.agent.plugin.basic.http.HttpPlugin; import org.bench4q.agent.scenario.util.ParameterParser; import org.bench4q.agent.scenario.util.Table; import org.bench4q.share.helper.TestHelper; @@ -37,14 +38,16 @@ public class Test_ParameterParser { }; @Test - public void testGetNumberOfEscapeCharacter() { + public void testGetNumberOfEscapeCharacter() throws Exception { assertEquals(3, "\\\\\\".length()); - assertEquals(2, ParameterParser.getNumberOfEscapeCharacter("\\\\")); + assertEquals(2, TestHelper.invokePrivate(ParameterParser.class, null, + "getNumberOfEscapeCharacter", new Class[] { String.class }, + new Object[] { "\\\\" })); } @Test - public void testGetRealTokenForContainSeparator() { - List entryList = ParameterParser.getRealTokens( + public void testGetRealTokenForContainSeparator() throws Exception { + List entryList = invokeGetRealTokens( Table.ESCAPE_ROW_SEPARATOR, TESTCASE1_CONTAIN_SEPARATOR, true); assertEquals(1, entryList.size()); assertEquals("header=accept|value=asdfasdf|;", entryList.get(0)); @@ -52,13 +55,14 @@ public class Test_ParameterParser { @Test public void testGetRealTokenForContainManyEscapse() throws Exception { - List rowList = ParameterParser.getRealTokens( - Table.ESCAPE_ROW_SEPARATOR, testcaseWithEscapes, false); + List rowList = invokeGetRealTokens(Table.ESCAPE_ROW_SEPARATOR, + testcaseWithEscapes, false); assertEquals(1, rowList.size()); assertEquals("varName=ticket|varExpression=\"ticket\":\\s*?\"\\w+\",", rowList.get(0)); - final List columnList = ParameterParser.getRealTokens( - Table.ESCAPE_COLUMN_SEPARATOR, rowList.get(0), true); + + final List columnList = invokeGetRealTokens( + Table.ESCAPE_COLUMN_SEPARATOR, rowList.get(0), false); assertEquals(2, columnList.size()); assertEquals("varName=ticket", columnList.get(0)); assertEquals("varExpression=\"ticket\":\\s*?\"\\w+\",", @@ -87,9 +91,18 @@ public class Test_ParameterParser { assertEquals("\"ticket\":\\s*?\"\\w+\",", result.get(0).get(1)); } + @SuppressWarnings("unchecked") + private List invokeGetRealTokens(String separator, String value, + boolean toUnescapeSeparator) throws Exception { + return (List) TestHelper.invokePrivate(ParameterParser.class, + null, "getRealTokens", new Class[] { String.class, + String.class, boolean.class }, new Object[] { + separator, value, true }); + } + @Test - public void testGetRealTokensForMultiSeparator() { - List entryList = ParameterParser.getRealTokens( + public void testGetRealTokensForMultiSeparator() throws Exception { + List entryList = invokeGetRealTokens( Table.ESCAPE_ROW_SEPARATOR, testcase2, false); assertEquals(2, entryList.size()); assertEquals("header=accept|value=fafsd", entryList.get(0)); @@ -118,7 +131,7 @@ public class Test_ParameterParser { } private Table buildHeaderTable(String value) { - return Table.buildTable(value, new LinkedList() { + return ParameterParser.buildTable(value, new LinkedList() { private static final long serialVersionUID = -6734367739974282326L; { add("header"); @@ -139,7 +152,7 @@ public class Test_ParameterParser { @Test public void testParseParam() { - List result = ParameterParser.getNField(testcase); + List result = ParameterParser.buildNField(testcase); assertEquals(10, result.size()); for (int i = 0; i < result.size(); i++) { assertEquals(result.get(i), expectedNFField.get(i)); @@ -148,8 +161,13 @@ public class Test_ParameterParser { } @Test - public void testGetHeadersWithRightCase() { - List nvPairs = ParameterParser.parseHeaders(testHeaders); + public void testGetHeadersWithRightCase() throws Exception { + @SuppressWarnings("unchecked") + List nvPairs = (List) TestHelper + .invokePrivate(HttpPlugin.class, new HttpPlugin(), + "parseHeaders", new Class[] { String.class }, + new Object[] { testHeaders }); + assertEquals(3, nvPairs.size()); assertEquals("Content-Type", nvPairs.get(0).getName()); assertEquals("application/x-www-form-urlencoded", nvPairs.get(0) @@ -162,9 +180,12 @@ public class Test_ParameterParser { } @Test - public void testGetHeadersWithUpperCase() { - List nvPairs = ParameterParser - .parseHeaders(testheaderWithUpperCase); + public void testGetHeadersWithUpperCase() throws Exception { + @SuppressWarnings("unchecked") + List nvPairs = (List) TestHelper + .invokePrivate(HttpPlugin.class, new HttpPlugin(), + "parseHeaders", new Class[] { String.class }, + new Object[] { testheaderWithUpperCase }); assertEquals(3, nvPairs.size()); assertEquals("Content-Type", nvPairs.get(0).getName()); assertEquals("application/x-www-form-urlencoded", nvPairs.get(0) From eddeb65f0b613debc95654c79eb4cf26fef53833 Mon Sep 17 00:00:00 2001 From: coderfengyun Date: Thu, 13 Mar 2014 09:11:39 +0800 Subject: [PATCH 175/196] remove the warnings --- .../parameterization/impl/Para_File.java | 4 +- .../impl/Para_UserNameAndPassword.java | 129 ++++++++---------- .../impl/ParameterParser.java | 27 ++-- .../impl/ParameterThreadOption.java | 19 ++- .../impl/TEST_HelloThread.java | 92 ++++++------- 5 files changed, 122 insertions(+), 149 deletions(-) diff --git a/src/main/java/org/bench4q/agent/parameterization/impl/Para_File.java b/src/main/java/org/bench4q/agent/parameterization/impl/Para_File.java index 36c3c754..aaca0b6d 100644 --- a/src/main/java/org/bench4q/agent/parameterization/impl/Para_File.java +++ b/src/main/java/org/bench4q/agent/parameterization/impl/Para_File.java @@ -1,14 +1,12 @@ package org.bench4q.agent.parameterization.impl; import java.io.BufferedReader; -import java.util.ArrayList; import java.util.HashMap; -import java.util.List; import java.util.Map; import java.util.UUID; public class Para_File { - + @SuppressWarnings("unused") private Map readBuffer = new HashMap(); diff --git a/src/main/java/org/bench4q/agent/parameterization/impl/Para_UserNameAndPassword.java b/src/main/java/org/bench4q/agent/parameterization/impl/Para_UserNameAndPassword.java index b6dd4049..736c83ec 100644 --- a/src/main/java/org/bench4q/agent/parameterization/impl/Para_UserNameAndPassword.java +++ b/src/main/java/org/bench4q/agent/parameterization/impl/Para_UserNameAndPassword.java @@ -6,52 +6,46 @@ import java.util.UUID; import java.util.concurrent.locks.ReentrantReadWriteLock; public class Para_UserNameAndPassword { - String [] Password = new String[]{"a","b","c","d","e"}; - String [] userName= new String[] {"http://www.baidu.com/","http://www.163.com/","http://baike.baidu.com/","http://zhidao.baidu.com/","http://www.sina.com.cn/"}; - UUID [] useUUID = new UUID[5]; - - Map posMap = new HashMap(); + String[] Password = new String[] { "a", "b", "c", "d", "e" }; + String[] userName = new String[] { "http://www.baidu.com/", + "http://www.163.com/", "http://baike.baidu.com/", + "http://zhidao.baidu.com/", "http://www.sina.com.cn/" }; + UUID[] useUUID = new UUID[5]; + + Map posMap = new HashMap(); ReentrantReadWriteLock mapRWLock = new ReentrantReadWriteLock(); ReentrantReadWriteLock idposLock = new ReentrantReadWriteLock(); - public String getUserName(UUID id) - { + + public String getUserName(UUID id) { mapRWLock.readLock().lock(); - if(posMap.containsKey(id)) - { + if (posMap.containsKey(id)) { mapRWLock.readLock().unlock(); return userName[posMap.get(id)]; } mapRWLock.readLock().unlock(); - + int vaildPos = -1; - int tryNum =0; - while(vaildPos < 0 && tryNum < 100) - { + int tryNum = 0; + while (vaildPos < 0 && tryNum < 100) { tryNum++; idposLock.readLock().lock(); - for(int i =0 ; i < 5;i++) - { - - if(useUUID[i] == null) - { + for (int i = 0; i < 5; i++) { + + if (useUUID[i] == null) { vaildPos = i; break; } } idposLock.readLock().unlock(); - if(vaildPos < 0) - { - try - { - Thread.currentThread().sleep(1000); - } - catch(Exception ex) - { - + if (vaildPos < 0) { + try { + Thread.sleep(1000); + } catch (Exception ex) { + } } } - + idposLock.writeLock().lock(); useUUID[vaildPos] = id; idposLock.writeLock().unlock(); @@ -60,46 +54,37 @@ public class Para_UserNameAndPassword { mapRWLock.writeLock().unlock(); return userName[vaildPos]; } - - public String getPassword(UUID id) - { + + public String getPassword(UUID id) { mapRWLock.readLock().lock(); - if(posMap.containsKey(id)) - { + if (posMap.containsKey(id)) { mapRWLock.readLock().unlock(); return Password[posMap.get(id)]; } mapRWLock.readLock().unlock(); - + int vaildPos = -1; - int tryNum =0; - while(vaildPos < 0 && tryNum < 100) - { + int tryNum = 0; + while (vaildPos < 0 && tryNum < 100) { tryNum++; idposLock.readLock().lock(); - for(int i =0 ; i < 5;i++) - { - - if(useUUID[i] == null) - { + for (int i = 0; i < 5; i++) { + + if (useUUID[i] == null) { vaildPos = i; break; } } idposLock.readLock().unlock(); - if(vaildPos < 0) - { - try - { - Thread.currentThread().sleep(1000); - } - catch(Exception ex) - { - + if (vaildPos < 0) { + try { + Thread.sleep(1000); + } catch (Exception ex) { + } } } - + idposLock.writeLock().lock(); useUUID[vaildPos] = id; idposLock.writeLock().unlock(); @@ -108,27 +93,23 @@ public class Para_UserNameAndPassword { mapRWLock.writeLock().unlock(); return Password[vaildPos]; } - - public void unreg(UUID id) - { - try - { - //System.out.println("1"); - mapRWLock.writeLock().lock(); - //System.out.println("2"); - int pos = posMap.get(id); - //System.out.println("3"); - posMap.remove(id); - //System.out.println("4"); - mapRWLock.writeLock().unlock(); - //System.out.println("5"); - idposLock.writeLock().lock(); - //System.out.println("6"); - useUUID[pos] = null; - idposLock.writeLock().unlock(); - } - catch(Exception ex) - { + + public void unreg(UUID id) { + try { + // System.out.println("1"); + mapRWLock.writeLock().lock(); + // System.out.println("2"); + int pos = posMap.get(id); + // System.out.println("3"); + posMap.remove(id); + // System.out.println("4"); + mapRWLock.writeLock().unlock(); + // System.out.println("5"); + idposLock.writeLock().lock(); + // System.out.println("6"); + useUUID[pos] = null; + idposLock.writeLock().unlock(); + } catch (Exception ex) { System.out.println(ex.getClass().getName()); System.out.println(ex.getMessage()); System.out.println(ex.getStackTrace()); @@ -136,5 +117,5 @@ public class Para_UserNameAndPassword { idposLock.writeLock().unlock(); } } - + } diff --git a/src/main/java/org/bench4q/agent/parameterization/impl/ParameterParser.java b/src/main/java/org/bench4q/agent/parameterization/impl/ParameterParser.java index ceb05cbc..382f28e1 100644 --- a/src/main/java/org/bench4q/agent/parameterization/impl/ParameterParser.java +++ b/src/main/java/org/bench4q/agent/parameterization/impl/ParameterParser.java @@ -1,10 +1,6 @@ package org.bench4q.agent.parameterization.impl; import java.io.StringReader; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; @@ -16,7 +12,7 @@ public class ParameterParser { public String parse(String text, InstanceControler insCon) { // Pattern pattern = Pattern.compile(""); - + String result = ""; try { @@ -32,21 +28,20 @@ public class ParameterParser { String[] args = argString.split(","); if (argString.trim().equals("")) args = new String[0]; - + String name = root.getAttribute("name"); result = insCon.getParameterByContext(name); - if(result != null) + if (result != null) return result; - if(type == "crossThread") - { - result = insCon.getParameter(name,"org.bench4q.agent.parameters." - + className, methodName, args); + if (type == "crossThread") { + result = insCon.getParameter(name, + "org.bench4q.agent.parameters." + className, + methodName, args); + } else if (type == "inThread") { + result = insCon.instanceLevelGetParameter(name, className, + methodName, args); } - else if(type == "inThread") - { - result = insCon.instanceLevelGetParameter(name,className, methodName, args); - } - + } catch (Exception ex) { return text; } diff --git a/src/main/java/org/bench4q/agent/parameterization/impl/ParameterThreadOption.java b/src/main/java/org/bench4q/agent/parameterization/impl/ParameterThreadOption.java index d22ea8b5..e4b79149 100644 --- a/src/main/java/org/bench4q/agent/parameterization/impl/ParameterThreadOption.java +++ b/src/main/java/org/bench4q/agent/parameterization/impl/ParameterThreadOption.java @@ -1,6 +1,5 @@ package org.bench4q.agent.parameterization.impl; -import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; @@ -8,22 +7,22 @@ import java.util.Map; public class ParameterThreadOption { public final ParameterThreadOption instance = new ParameterThreadOption(); - Map> optionMap = new HashMap>(); + Map> optionMap = new HashMap>(); private List all = Arrays.asList("crossThread", "inThread"); - private List justIn = Arrays.asList( "inThread"); + // private List justIn = Arrays.asList("inThread"); private List justCross = Arrays.asList("crossThread"); - private ParameterThreadOption() - { - + + private ParameterThreadOption() { + optionMap.put("Para_File", all); - optionMap.put("Para_IteratorNumber",justCross); + optionMap.put("Para_IteratorNumber", justCross); optionMap.put("Para_RandomNumber", all); optionMap.put("Para_UniqueNumber", all); optionMap.put("Para_UserNameAndPassword", justCross); } - public List getThreadOption(String classname) - { - if(this.optionMap.containsKey(classname)== false) + + public List getThreadOption(String classname) { + if (this.optionMap.containsKey(classname) == false) return all; return optionMap.get(classname); } diff --git a/src/main/java/org/bench4q/agent/parameterization/impl/TEST_HelloThread.java b/src/main/java/org/bench4q/agent/parameterization/impl/TEST_HelloThread.java index 2108f37c..477f6683 100644 --- a/src/main/java/org/bench4q/agent/parameterization/impl/TEST_HelloThread.java +++ b/src/main/java/org/bench4q/agent/parameterization/impl/TEST_HelloThread.java @@ -2,55 +2,55 @@ package org.bench4q.agent.parameterization.impl; public class TEST_HelloThread extends Thread { InstanceControler ic; - public TEST_HelloThread() { - ic = new InstanceControler(); - } - - - - public void run() { - java.util.Random r=new java.util.Random(); - int t = r.nextInt(10000); - System.out.print(Thread.currentThread().getId()); - System.out.println(":"+t); - try { - Thread.currentThread().sleep(t); - } catch (InterruptedException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - System.out.print(Thread.currentThread().getId()); - System.out.print("\t"); - - String userName = ic.getParam(""); - String passwordName = ic.getParam(""); - System.out.print(userName); - System.out.print("\t"); - System.out.println(passwordName); - try { - Thread.currentThread().sleep(r.nextInt(10000)); - } catch (InterruptedException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - ic.releaseAll(); - - } - public static void main(String[] args) { - while(true) - { - TEST_HelloThread h1=new TEST_HelloThread(); - - h1.start(); - try { - Thread.currentThread().sleep(1000); + public TEST_HelloThread() { + ic = new InstanceControler(); + } + + public void run() { + java.util.Random r = new java.util.Random(); + int t = r.nextInt(10000); + System.out.print(Thread.currentThread().getId()); + System.out.println(":" + t); + try { + Thread.sleep(t); + } catch (InterruptedException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + System.out.print(Thread.currentThread().getId()); + System.out.print("\t"); + + String userName = ic + .getParam(""); + String passwordName = ic + .getParam(""); + System.out.print(userName); + System.out.print("\t"); + System.out.println(passwordName); + try { + Thread.sleep(r.nextInt(10000)); + } catch (InterruptedException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + ic.releaseAll(); + + } + + public static void main(String[] args) { + while (true) { + TEST_HelloThread h1 = new TEST_HelloThread(); + + h1.start(); + try { + Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } - } - } - - private String name; + } + } + + // private String name; } From ff2f3146e0f35468d6736ba876164cf5da7c072b Mon Sep 17 00:00:00 2001 From: coderfengyun Date: Fri, 14 Mar 2014 10:09:04 +0800 Subject: [PATCH 176/196] add configuration of userDefinedParamFolder --- configure/agent-config.properties | 3 +- src/main/java/org/bench4q/agent/Main.java | 153 ++++---- .../{interfaces => }/DataCollector.java | 40 +- .../impl/AbstractDataCollector.java | 2 +- .../impl/InstanceControler.java | 33 +- .../java/org/bench4q/agent/scenario/Page.java | 44 +-- .../agent/scenario/ScenarioContext.java | 154 ++++---- .../org/bench4q/agent/scenario/Worker.java | 2 +- .../agent/scenario/behavior/Behavior.java | 2 +- .../scenario/behavior/TimerBehavior.java | 42 +-- .../agent/scenario/behavior/UserBehavior.java | 40 +- .../datastatistics/DetailStatisticsTest.java | 278 +++++++------- .../PageResultStatisticsTest.java | 266 +++++++------- .../ScenarioStatisticsTest.java | 346 +++++++++--------- 14 files changed, 712 insertions(+), 693 deletions(-) rename src/main/java/org/bench4q/agent/datacollector/{interfaces => }/DataCollector.java (87%) diff --git a/configure/agent-config.properties b/configure/agent-config.properties index 9ab434f8..3c09e025 100644 --- a/configure/agent-config.properties +++ b/configure/agent-config.properties @@ -1,2 +1,3 @@ isToSaveDetailResult=false -servePort=6565 \ No newline at end of file +servePort=6565 +userDefinedParamFolder=userDefinedParams \ No newline at end of file diff --git a/src/main/java/org/bench4q/agent/Main.java b/src/main/java/org/bench4q/agent/Main.java index 159213f7..45c45d7b 100644 --- a/src/main/java/org/bench4q/agent/Main.java +++ b/src/main/java/org/bench4q/agent/Main.java @@ -1,67 +1,86 @@ -package org.bench4q.agent; - -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.util.Properties; - -import org.apache.log4j.Logger; - -public class Main { - private static final String CONFIG_FILE_NAME = "agent-config.properties"; - private static String DIR_PATH = "configure" - + System.getProperty("file.separator"); - private static Logger logger = Logger.getLogger(Main.class); - private static int PORT_TO_SERVE; - public static boolean IS_TO_SAVE_DETAIL; - - public static void main(String[] args) { - init(); - AgentServer agentServer = new AgentServer(PORT_TO_SERVE); - agentServer.start(); - } - - public static void init() { - // TODO: when the configuration exists, should validate it - File dirFile = new File(DIR_PATH); - if (!dirFile.exists()) { - dirFile.mkdirs(); - } - File configFile = new File(DIR_PATH + CONFIG_FILE_NAME); - if (!configFile.exists()) { - createDefaultConfig(configFile); - } - initProperties(); - } - - private static void createDefaultConfig(File configFile) { - try { - if (configFile.createNewFile()) { - FileOutputStream outputStream = new FileOutputStream(configFile); - String content = "isToSaveDetailResult=false" + "\n" - + "servePort=6565"; - outputStream.write(content.getBytes()); - outputStream.flush(); - outputStream.close(); - } - } catch (Exception e) { - } - } - - private static void initProperties() { - try { - FileInputStream inputStream = new FileInputStream(new File(DIR_PATH - + CONFIG_FILE_NAME)); - Properties properties = new Properties(); - properties.load(inputStream); - PORT_TO_SERVE = Integer.parseInt((String) properties - .get("servePort")); - IS_TO_SAVE_DETAIL = Boolean.parseBoolean((String) properties - .get("isToSaveDetailResult")); - } catch (IOException e) { - logger.error("There is an error when getPortToServe!"); - } - } - -} +package org.bench4q.agent; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.util.Properties; + +import org.apache.log4j.Logger; + +public class Main { + private static final String CONFIG_FILE_NAME = "agent-config.properties"; + private static String DIR_PATH = "configure" + + System.getProperty("file.separator"); + private static Logger logger = Logger.getLogger(Main.class); + private static int PORT_TO_SERVE; + public static boolean IS_TO_SAVE_DETAIL; + public static String USER_DEFINED_PARAMS_FOLDER; + + static { + init(); + } + + public static void main(String[] args) { + AgentServer agentServer = new AgentServer(PORT_TO_SERVE); + agentServer.start(); + } + + public static void init() { + guardConfigureExists(); + initProperties(); + } + + private static void guardConfigureExists() { + File dirFile = new File(DIR_PATH); + if (!dirFile.exists()) { + dirFile.mkdirs(); + } + File configFile = new File(DIR_PATH + CONFIG_FILE_NAME); + if (!configFile.exists()) { + createDefaultConfig(configFile); + } + } + + private static void createDefaultConfig(File configFile) { + try { + if (configFile.createNewFile()) { + FileOutputStream outputStream = new FileOutputStream(configFile); + String content = "isToSaveDetailResult=false" + "\n" + + "servePort=6565" + "\n" + + "userDefinedParamFolder=userDefinedParams"; + outputStream.write(content.getBytes()); + outputStream.flush(); + outputStream.close(); + } + } catch (Exception e) { + } + } + + private static void initProperties() { + try { + FileInputStream inputStream = new FileInputStream(new File(DIR_PATH + + CONFIG_FILE_NAME)); + Properties properties = new Properties(); + properties.load(inputStream); + PORT_TO_SERVE = Integer.parseInt((String) properties + .get("servePort")); + IS_TO_SAVE_DETAIL = Boolean.parseBoolean((String) properties + .get("isToSaveDetailResult")); + USER_DEFINED_PARAMS_FOLDER = properties + .getProperty("userDefinedParamFolder"); + guardUserDefinedFolderExists(); + } catch (IOException e) { + logger.error("There is an error when getPortToServe!"); + } + } + + private static void guardUserDefinedFolderExists() { + File dirFile = new File(USER_DEFINED_PARAMS_FOLDER + + System.getProperty("file.separator")); + if (!dirFile.exists()) { + dirFile.mkdirs(); + } + } + +} diff --git a/src/main/java/org/bench4q/agent/datacollector/interfaces/DataCollector.java b/src/main/java/org/bench4q/agent/datacollector/DataCollector.java similarity index 87% rename from src/main/java/org/bench4q/agent/datacollector/interfaces/DataCollector.java rename to src/main/java/org/bench4q/agent/datacollector/DataCollector.java index 95a6f3fa..94c13c9f 100644 --- a/src/main/java/org/bench4q/agent/datacollector/interfaces/DataCollector.java +++ b/src/main/java/org/bench4q/agent/datacollector/DataCollector.java @@ -1,20 +1,20 @@ -package org.bench4q.agent.datacollector.interfaces; - -import java.util.Map; - -import org.bench4q.agent.datacollector.impl.BehaviorStatusCodeResult; -import org.bench4q.agent.scenario.BehaviorResult; -import org.bench4q.agent.scenario.PageResult; - -public interface DataCollector { - public void add(BehaviorResult behaviorResult); - - public void add(PageResult pageResult); - - public Object getScenarioBriefStatistics(); - - public Map getBehaviorBriefStatistics( - int behaviorId); - - public Object getPageBriefStatistics(int pageId); -} +package org.bench4q.agent.datacollector; + +import java.util.Map; + +import org.bench4q.agent.datacollector.impl.BehaviorStatusCodeResult; +import org.bench4q.agent.scenario.BehaviorResult; +import org.bench4q.agent.scenario.PageResult; + +public interface DataCollector { + public void add(BehaviorResult behaviorResult); + + public void add(PageResult pageResult); + + public Object getScenarioBriefStatistics(); + + public Map getBehaviorBriefStatistics( + int behaviorId); + + public Object getPageBriefStatistics(int pageId); +} diff --git a/src/main/java/org/bench4q/agent/datacollector/impl/AbstractDataCollector.java b/src/main/java/org/bench4q/agent/datacollector/impl/AbstractDataCollector.java index 24228108..e14a0b75 100644 --- a/src/main/java/org/bench4q/agent/datacollector/impl/AbstractDataCollector.java +++ b/src/main/java/org/bench4q/agent/datacollector/impl/AbstractDataCollector.java @@ -5,7 +5,7 @@ import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import org.bench4q.agent.Main; -import org.bench4q.agent.datacollector.interfaces.DataCollector; +import org.bench4q.agent.datacollector.DataCollector; import org.bench4q.agent.helper.ApplicationContextHelper; import org.bench4q.agent.scenario.BehaviorResult; import org.bench4q.agent.storage.StorageHelper; diff --git a/src/main/java/org/bench4q/agent/parameterization/impl/InstanceControler.java b/src/main/java/org/bench4q/agent/parameterization/impl/InstanceControler.java index 9df9f78d..00bf5313 100644 --- a/src/main/java/org/bench4q/agent/parameterization/impl/InstanceControler.java +++ b/src/main/java/org/bench4q/agent/parameterization/impl/InstanceControler.java @@ -12,14 +12,15 @@ import java.util.concurrent.locks.ReentrantReadWriteLock; import org.bench4q.agent.parameterization.SessionObject; public class InstanceControler implements SessionObject { + private String userDefineParameterFolderPath = "/home/yxsh/git/Bench4Q-Agent/parameterClass/"; private UUID instandid = java.util.UUID.randomUUID(); private Set usedClassName = new HashSet(); private Map objMap = new HashMap(); private Map runtimeParaMap = new HashMap(); - public Map cacheObjMap = new HashMap(); + public Map cacheObjMap = new HashMap(); ReentrantReadWriteLock mapRWLock = new ReentrantReadWriteLock(); - public String instanceLevelGetParameter(String name,String className, + public String instanceLevelGetParameter(String name, String className, String functionName, Object[] args) { boolean hasThisClass = false; @@ -38,8 +39,8 @@ public class InstanceControler implements SessionObject { Object[] totalArgs = new Object[args.length + 2]; totalArgs[0] = instandid; totalArgs[1] = this.cacheObjMap; - for (int i = 2; i < args.length+2; i++) { - argTypeArr[i] = args[i-2].getClass(); + for (int i = 2; i < args.length + 2; i++) { + argTypeArr[i] = args[i - 2].getClass(); totalArgs[i] = args[i - 2]; } @@ -58,8 +59,6 @@ public class InstanceControler implements SessionObject { } - private String rootFilePath = "/home/yxsh/git/Bench4Q-Agent/parameterClass/"; - public String getParameterByContext(String name) { if (false == this.runtimeParaMap.containsKey(name)) { return null; @@ -70,7 +69,7 @@ public class InstanceControler implements SessionObject { public boolean createObj(String className) { try { MyFileClassLoader cl = new MyFileClassLoader(); - cl.setClassPath(rootFilePath); + cl.setClassPath(userDefineParameterFolderPath); Class cls = cl.loadClass(className); Object instance = cls.newInstance(); mapRWLock.writeLock().lock(); @@ -91,8 +90,8 @@ public class InstanceControler implements SessionObject { return result; } - public String getParameter(String name , String className, String functionName, - Object[] args) { + public String getParameter(String name, String className, + String functionName, Object[] args) { ParametersFactory pf = ParametersFactory.getInstance(); boolean hasThisClass = pf.containObj(className); @@ -109,9 +108,9 @@ public class InstanceControler implements SessionObject { Object[] totalArgs = new Object[args.length + 1]; totalArgs[0] = instandid; totalArgs[1] = this.cacheObjMap; - for (int i = 2; i < args.length+2; i++) { - argTypeArr[i] = args[i-2].getClass(); - totalArgs[i] = args[i-2]; + for (int i = 2; i < args.length + 2; i++) { + argTypeArr[i] = args[i - 2].getClass(); + totalArgs[i] = args[i - 2]; } Method m = instance.getClass().getMethod(functionName, argTypeArr); @@ -131,8 +130,9 @@ public class InstanceControler implements SessionObject { } /** - * Implement SessionObject start + * Implement SessionObject begin */ + public String getParam(String name) { if (!(name.startsWith(""))) return name; @@ -144,6 +144,9 @@ public class InstanceControler implements SessionObject { runtimeParaMap.put(name, value); } + public void saveRuntimeParams(Map runTimeParams) { + runtimeParaMap.putAll(runTimeParams); + } public void doCleanUp() { this.releaseAll(); @@ -188,8 +191,4 @@ public class InstanceControler implements SessionObject { } - public void saveRuntimeParams(Map runTimeParams) { - // TODO Auto-generated method stub - runtimeParaMap.putAll(runTimeParams); - } } diff --git a/src/main/java/org/bench4q/agent/scenario/Page.java b/src/main/java/org/bench4q/agent/scenario/Page.java index 2814652b..f03f9e77 100644 --- a/src/main/java/org/bench4q/agent/scenario/Page.java +++ b/src/main/java/org/bench4q/agent/scenario/Page.java @@ -1,22 +1,22 @@ -package org.bench4q.agent.scenario; - -import org.bench4q.agent.datacollector.impl.PageResultCollector; -import org.bench4q.agent.datacollector.interfaces.DataCollector; - -public class Page { - private Batch[] batches; - final private DataCollector dataCollector = new PageResultCollector(); - - public Batch[] getBatches() { - return batches; - } - - public void setBatches(Batch[] batches) { - this.batches = batches; - } - - public DataCollector getDataCollector() { - return dataCollector; - } - -} +package org.bench4q.agent.scenario; + +import org.bench4q.agent.datacollector.DataCollector; +import org.bench4q.agent.datacollector.impl.PageResultCollector; + +public class Page { + private Batch[] batches; + final private DataCollector dataCollector = new PageResultCollector(); + + public Batch[] getBatches() { + return batches; + } + + public void setBatches(Batch[] batches) { + this.batches = batches; + } + + public DataCollector getDataCollector() { + return dataCollector; + } + +} diff --git a/src/main/java/org/bench4q/agent/scenario/ScenarioContext.java b/src/main/java/org/bench4q/agent/scenario/ScenarioContext.java index 24087583..2d110114 100644 --- a/src/main/java/org/bench4q/agent/scenario/ScenarioContext.java +++ b/src/main/java/org/bench4q/agent/scenario/ScenarioContext.java @@ -1,77 +1,77 @@ -package org.bench4q.agent.scenario; - -import java.util.Date; -import java.util.UUID; -import java.util.concurrent.ThreadPoolExecutor; - -import org.bench4q.agent.datacollector.impl.ScenarioResultCollector; -import org.bench4q.agent.datacollector.interfaces.DataCollector; - -public class ScenarioContext { - private Date startDate; - private Date endDate; - private ThreadPoolExecutor executor; - private Scenario scenario; - private boolean finished; - private DataCollector dataStatistics; - - public Date getStartDate() { - return startDate; - } - - public void setStartDate(Date saveStartDate) { - this.startDate = saveStartDate; - } - - public Date getEndDate() { - return endDate; - } - - public void setEndDate(Date endDate) { - this.endDate = endDate; - } - - public ThreadPoolExecutor getExecutor() { - return executor; - } - - public void setExecutorService(ThreadPoolExecutor executor) { - this.executor = 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 dataStatistics; - } - - private void setDataStatistics(DataCollector dataStatistics) { - this.dataStatistics = dataStatistics; - } - - public static ScenarioContext buildScenarioContext(UUID testId, - final Scenario scenario, int poolSize, ThreadPoolExecutor executor) { - ScenarioContext scenarioContext = new ScenarioContext(); - scenarioContext.setScenario(scenario); - scenarioContext.setStartDate(new Date(System.currentTimeMillis())); - scenarioContext.setExecutorService(executor); - // TODO:remove this direct dependency - scenarioContext.setDataStatistics(new ScenarioResultCollector(testId)); - return scenarioContext; - } - -} +package org.bench4q.agent.scenario; + +import java.util.Date; +import java.util.UUID; +import java.util.concurrent.ThreadPoolExecutor; + +import org.bench4q.agent.datacollector.DataCollector; +import org.bench4q.agent.datacollector.impl.ScenarioResultCollector; + +public class ScenarioContext { + private Date startDate; + private Date endDate; + private ThreadPoolExecutor executor; + private Scenario scenario; + private boolean finished; + private DataCollector dataStatistics; + + public Date getStartDate() { + return startDate; + } + + public void setStartDate(Date saveStartDate) { + this.startDate = saveStartDate; + } + + public Date getEndDate() { + return endDate; + } + + public void setEndDate(Date endDate) { + this.endDate = endDate; + } + + public ThreadPoolExecutor getExecutor() { + return executor; + } + + public void setExecutorService(ThreadPoolExecutor executor) { + this.executor = 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 dataStatistics; + } + + private void setDataStatistics(DataCollector dataStatistics) { + this.dataStatistics = dataStatistics; + } + + public static ScenarioContext buildScenarioContext(UUID testId, + final Scenario scenario, int poolSize, ThreadPoolExecutor executor) { + ScenarioContext scenarioContext = new ScenarioContext(); + scenarioContext.setScenario(scenario); + scenarioContext.setStartDate(new Date(System.currentTimeMillis())); + scenarioContext.setExecutorService(executor); + // TODO:remove this direct dependency + scenarioContext.setDataStatistics(new ScenarioResultCollector(testId)); + return scenarioContext; + } + +} diff --git a/src/main/java/org/bench4q/agent/scenario/Worker.java b/src/main/java/org/bench4q/agent/scenario/Worker.java index b782036b..587bcc04 100644 --- a/src/main/java/org/bench4q/agent/scenario/Worker.java +++ b/src/main/java/org/bench4q/agent/scenario/Worker.java @@ -6,7 +6,7 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -import org.bench4q.agent.datacollector.interfaces.DataCollector; +import org.bench4q.agent.datacollector.DataCollector; import org.bench4q.agent.helper.ApplicationContextHelper; import org.bench4q.agent.parameterization.SessionObject; import org.bench4q.agent.plugin.Plugin; diff --git a/src/main/java/org/bench4q/agent/scenario/behavior/Behavior.java b/src/main/java/org/bench4q/agent/scenario/behavior/Behavior.java index 705233ef..80142d7a 100644 --- a/src/main/java/org/bench4q/agent/scenario/behavior/Behavior.java +++ b/src/main/java/org/bench4q/agent/scenario/behavior/Behavior.java @@ -2,8 +2,8 @@ package org.bench4q.agent.scenario.behavior; import java.util.Map; +import org.bench4q.agent.datacollector.DataCollector; import org.bench4q.agent.datacollector.impl.BehaviorStatusCodeResult; -import org.bench4q.agent.datacollector.interfaces.DataCollector; import org.bench4q.agent.parameterization.SessionObject; import org.bench4q.agent.scenario.Parameter; diff --git a/src/main/java/org/bench4q/agent/scenario/behavior/TimerBehavior.java b/src/main/java/org/bench4q/agent/scenario/behavior/TimerBehavior.java index 25414e28..c99d80aa 100644 --- a/src/main/java/org/bench4q/agent/scenario/behavior/TimerBehavior.java +++ b/src/main/java/org/bench4q/agent/scenario/behavior/TimerBehavior.java @@ -1,21 +1,21 @@ -package org.bench4q.agent.scenario.behavior; - -import java.util.Map; - -import org.bench4q.agent.datacollector.impl.BehaviorStatusCodeResult; -import org.bench4q.agent.datacollector.interfaces.DataCollector; - -public class TimerBehavior extends Behavior { - - @Override - public boolean shouldBeCountResponseTime() { - return false; - } - - @Override - public Map getBehaviorBriefResult( - DataCollector dataStatistics) { - return null; - } - -} +package org.bench4q.agent.scenario.behavior; + +import java.util.Map; + +import org.bench4q.agent.datacollector.DataCollector; +import org.bench4q.agent.datacollector.impl.BehaviorStatusCodeResult; + +public class TimerBehavior extends Behavior { + + @Override + public boolean shouldBeCountResponseTime() { + return false; + } + + @Override + public Map getBehaviorBriefResult( + DataCollector dataStatistics) { + return null; + } + +} diff --git a/src/main/java/org/bench4q/agent/scenario/behavior/UserBehavior.java b/src/main/java/org/bench4q/agent/scenario/behavior/UserBehavior.java index 5b6490c9..6fe473d5 100644 --- a/src/main/java/org/bench4q/agent/scenario/behavior/UserBehavior.java +++ b/src/main/java/org/bench4q/agent/scenario/behavior/UserBehavior.java @@ -1,20 +1,20 @@ -package org.bench4q.agent.scenario.behavior; - -import java.util.Map; - -import org.bench4q.agent.datacollector.impl.BehaviorStatusCodeResult; -import org.bench4q.agent.datacollector.interfaces.DataCollector; - -public class UserBehavior extends Behavior { - @Override - public boolean shouldBeCountResponseTime() { - return true; - } - - @Override - public Map getBehaviorBriefResult( - DataCollector dataStatistics) { - return dataStatistics.getBehaviorBriefStatistics(this.getId()); - } - -} +package org.bench4q.agent.scenario.behavior; + +import java.util.Map; + +import org.bench4q.agent.datacollector.DataCollector; +import org.bench4q.agent.datacollector.impl.BehaviorStatusCodeResult; + +public class UserBehavior extends Behavior { + @Override + public boolean shouldBeCountResponseTime() { + return true; + } + + @Override + public Map getBehaviorBriefResult( + DataCollector dataStatistics) { + return dataStatistics.getBehaviorBriefStatistics(this.getId()); + } + +} diff --git a/src/test/java/org/bench4q/agent/test/datastatistics/DetailStatisticsTest.java b/src/test/java/org/bench4q/agent/test/datastatistics/DetailStatisticsTest.java index bfe51b2b..1df3257a 100644 --- a/src/test/java/org/bench4q/agent/test/datastatistics/DetailStatisticsTest.java +++ b/src/test/java/org/bench4q/agent/test/datastatistics/DetailStatisticsTest.java @@ -1,139 +1,139 @@ -package org.bench4q.agent.test.datastatistics; - -import static org.junit.Assert.*; - -import java.util.HashMap; -import java.util.Map; -import java.util.UUID; - -import org.bench4q.agent.datacollector.impl.ScenarioResultCollector; -import org.bench4q.agent.datacollector.impl.BehaviorStatusCodeResult; -import org.bench4q.agent.datacollector.interfaces.DataCollector; -import org.bench4q.agent.scenario.BehaviorResult; -import org.bench4q.agent.storage.StorageHelper; -import org.junit.Test; -import org.springframework.context.ApplicationContext; -import org.springframework.context.support.ClassPathXmlApplicationContext; - -public class DetailStatisticsTest { - private DataCollector detailStatistics; - - private DataCollector getDetailStatistics() { - return detailStatistics; - } - - private void setDetailStatistics(DataCollector detailStatistics) { - this.detailStatistics = detailStatistics; - } - - public DetailStatisticsTest() { - init(); - } - - private void init() { - @SuppressWarnings("resource") - ApplicationContext context = new ClassPathXmlApplicationContext( - "classpath*:/org/bench4q/agent/config/application-context.xml"); - ScenarioResultCollector agentResultDataCollector = new ScenarioResultCollector( - UUID.randomUUID()); - agentResultDataCollector.setStorageHelper((StorageHelper) context - .getBean(StorageHelper.class)); - this.setDetailStatistics(agentResultDataCollector); - } - - @Test - public void addZeroTest() { - for (BehaviorResult behaviorResult : ScenarioStatisticsTest - .makeBehaviorList(0)) { - this.getDetailStatistics().add(behaviorResult); - } - - Object object = this.detailStatistics.getBehaviorBriefStatistics(0); - assertEquals(null, object); - } - - @Test - public void addOneDetailTest() { - for (BehaviorResult behaviorResult : ScenarioStatisticsTest - .makeBehaviorList(1)) { - this.getDetailStatistics().add(behaviorResult); - } - Map map = this.detailStatistics - .getBehaviorBriefStatistics(1); - - BehaviorStatusCodeResult actualResult = map.get(200); - assertTrue(actualResult.equals(makeExpectedResultForOne())); - } - - private BehaviorStatusCodeResult makeExpectedResultForOne() { - BehaviorStatusCodeResult ret = new BehaviorStatusCodeResult(""); - ret.contentLength = 20; - ret.count = 1; - ret.maxResponseTime = 200; - ret.minResponseTime = 200; - ret.totalResponseTimeThisTime = 200; - return ret; - } - - @Test - public void addTwoDetailTest() { - for (BehaviorResult behaviorResult : ScenarioStatisticsTest - .makeBehaviorList(2)) { - this.getDetailStatistics().add(behaviorResult); - } - Map map = this.detailStatistics - .getBehaviorBriefStatistics(1); - assertTrue(mapEquals(map, makeExpectedMapForTwo())); - } - - private Map makeExpectedMapForTwo() { - Map ret = new HashMap(); - ret.put(new Integer(200), buildCodeResult(20, 1, 200, 200, 200)); - ret.put(new Integer(400), buildCodeResult(0, 1, 0, 0, 0)); - return ret; - } - - private BehaviorStatusCodeResult buildCodeResult(long contentLength, - long count, long maxResponseTime, long minResponseTime, - long totalResponseTimeThisTime) { - BehaviorStatusCodeResult ret = new BehaviorStatusCodeResult(""); - ret.contentLength = contentLength; - ret.count = count; - ret.maxResponseTime = maxResponseTime; - ret.minResponseTime = minResponseTime; - ret.totalResponseTimeThisTime = totalResponseTimeThisTime; - return ret; - } - - private boolean mapEquals(Map mapActual, - Map mapExpected) { - boolean equal = true; - if (mapActual.size() != mapExpected.size()) { - return false; - } - for (int i : mapActual.keySet()) { - if (!mapActual.get(i).equals(mapExpected.get(i))) { - equal = false; - } - } - return equal; - } - - @Test - public void addThreeTest() { - for (BehaviorResult behaviorResult : ScenarioStatisticsTest - .makeBehaviorList(3)) { - this.getDetailStatistics().add(behaviorResult); - } - Map mapActual = this - .getDetailStatistics().getBehaviorBriefStatistics(1); - assertTrue(mapEquals(mapActual, makeExpectedMapForThree())); - } - - private Map makeExpectedMapForThree() { - Map retMap = new HashMap(); - retMap.put(200, buildCodeResult(40, 2, 220, 200, 420)); - retMap.put(400, buildCodeResult(0, 1, 0, 0, 0)); - return retMap; - } -} +package org.bench4q.agent.test.datastatistics; + +import static org.junit.Assert.*; + +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; + +import org.bench4q.agent.datacollector.DataCollector; +import org.bench4q.agent.datacollector.impl.ScenarioResultCollector; +import org.bench4q.agent.datacollector.impl.BehaviorStatusCodeResult; +import org.bench4q.agent.scenario.BehaviorResult; +import org.bench4q.agent.storage.StorageHelper; +import org.junit.Test; +import org.springframework.context.ApplicationContext; +import org.springframework.context.support.ClassPathXmlApplicationContext; + +public class DetailStatisticsTest { + private DataCollector detailStatistics; + + private DataCollector getDetailStatistics() { + return detailStatistics; + } + + private void setDetailStatistics(DataCollector detailStatistics) { + this.detailStatistics = detailStatistics; + } + + public DetailStatisticsTest() { + init(); + } + + private void init() { + @SuppressWarnings("resource") + ApplicationContext context = new ClassPathXmlApplicationContext( + "classpath*:/org/bench4q/agent/config/application-context.xml"); + ScenarioResultCollector agentResultDataCollector = new ScenarioResultCollector( + UUID.randomUUID()); + agentResultDataCollector.setStorageHelper((StorageHelper) context + .getBean(StorageHelper.class)); + this.setDetailStatistics(agentResultDataCollector); + } + + @Test + public void addZeroTest() { + for (BehaviorResult behaviorResult : ScenarioStatisticsTest + .makeBehaviorList(0)) { + this.getDetailStatistics().add(behaviorResult); + } + + Object object = this.detailStatistics.getBehaviorBriefStatistics(0); + assertEquals(null, object); + } + + @Test + public void addOneDetailTest() { + for (BehaviorResult behaviorResult : ScenarioStatisticsTest + .makeBehaviorList(1)) { + this.getDetailStatistics().add(behaviorResult); + } + Map map = this.detailStatistics + .getBehaviorBriefStatistics(1); + + BehaviorStatusCodeResult actualResult = map.get(200); + assertTrue(actualResult.equals(makeExpectedResultForOne())); + } + + private BehaviorStatusCodeResult makeExpectedResultForOne() { + BehaviorStatusCodeResult ret = new BehaviorStatusCodeResult(""); + ret.contentLength = 20; + ret.count = 1; + ret.maxResponseTime = 200; + ret.minResponseTime = 200; + ret.totalResponseTimeThisTime = 200; + return ret; + } + + @Test + public void addTwoDetailTest() { + for (BehaviorResult behaviorResult : ScenarioStatisticsTest + .makeBehaviorList(2)) { + this.getDetailStatistics().add(behaviorResult); + } + Map map = this.detailStatistics + .getBehaviorBriefStatistics(1); + assertTrue(mapEquals(map, makeExpectedMapForTwo())); + } + + private Map makeExpectedMapForTwo() { + Map ret = new HashMap(); + ret.put(new Integer(200), buildCodeResult(20, 1, 200, 200, 200)); + ret.put(new Integer(400), buildCodeResult(0, 1, 0, 0, 0)); + return ret; + } + + private BehaviorStatusCodeResult buildCodeResult(long contentLength, + long count, long maxResponseTime, long minResponseTime, + long totalResponseTimeThisTime) { + BehaviorStatusCodeResult ret = new BehaviorStatusCodeResult(""); + ret.contentLength = contentLength; + ret.count = count; + ret.maxResponseTime = maxResponseTime; + ret.minResponseTime = minResponseTime; + ret.totalResponseTimeThisTime = totalResponseTimeThisTime; + return ret; + } + + private boolean mapEquals(Map mapActual, + Map mapExpected) { + boolean equal = true; + if (mapActual.size() != mapExpected.size()) { + return false; + } + for (int i : mapActual.keySet()) { + if (!mapActual.get(i).equals(mapExpected.get(i))) { + equal = false; + } + } + return equal; + } + + @Test + public void addThreeTest() { + for (BehaviorResult behaviorResult : ScenarioStatisticsTest + .makeBehaviorList(3)) { + this.getDetailStatistics().add(behaviorResult); + } + Map mapActual = this + .getDetailStatistics().getBehaviorBriefStatistics(1); + assertTrue(mapEquals(mapActual, makeExpectedMapForThree())); + } + + private Map makeExpectedMapForThree() { + Map retMap = new HashMap(); + retMap.put(200, buildCodeResult(40, 2, 220, 200, 420)); + retMap.put(400, buildCodeResult(0, 1, 0, 0, 0)); + return retMap; + } +} diff --git a/src/test/java/org/bench4q/agent/test/datastatistics/PageResultStatisticsTest.java b/src/test/java/org/bench4q/agent/test/datastatistics/PageResultStatisticsTest.java index c8e0bb9c..a6b4dad8 100644 --- a/src/test/java/org/bench4q/agent/test/datastatistics/PageResultStatisticsTest.java +++ b/src/test/java/org/bench4q/agent/test/datastatistics/PageResultStatisticsTest.java @@ -1,133 +1,133 @@ -package org.bench4q.agent.test.datastatistics; - -import org.bench4q.agent.datacollector.impl.PageResultCollector; -import org.bench4q.agent.datacollector.interfaces.DataCollector; -import org.bench4q.agent.scenario.PageResult; -import org.bench4q.share.models.agent.statistics.AgentPageBriefModel; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.springframework.context.support.ClassPathXmlApplicationContext; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; - -import static org.junit.Assert.*; - -@RunWith(SpringJUnit4ClassRunner.class) -@ContextConfiguration(locations = { "classpath:test-storage-context.xml", - "classpath*:/org/bench4q/agent/config/application-context.xml" }) -public class PageResultStatisticsTest { - private DataCollector dataCollector; - - private DataCollector getDataCollector() { - return dataCollector; - } - - private void setDataCollector(DataCollector dataCollector) { - this.dataCollector = dataCollector; - } - - @SuppressWarnings("resource") - public PageResultStatisticsTest() { - new ClassPathXmlApplicationContext( - "classpath*:/org/bench4q/agent/config/application-context.xml"); - this.setDataCollector(new PageResultCollector()); - } - - @Test - public void pageResultTest() { - PageResult pageResult = PageResult.buildPageResult(2, - ScenarioStatisticsTest.makeBehaviorList(1)); - assertEquals(2, pageResult.getPageId()); - assertEquals(200, pageResult.getExecuteRange()); - assertTrue(pageResult.getPageStartTime() > 0); - } - - @Test - public void pageResultWithTwoBehaviorTest() { - PageResult pageResult = PageResult.buildPageResult(2, - ScenarioStatisticsTest.makeBehaviorList(2)); - assertEquals(2, pageResult.getPageId()); - assertEquals(220, pageResult.getExecuteRange()); - assertEquals(200, pageResult.getPageStartTime()); - assertEquals(420, pageResult.getPageEndTime()); - } - - @Test - public void testNull() { - this.getDataCollector().add((PageResult) null); - assertNotNull(dataCollector.getPageBriefStatistics(0)); - } - - @Test - public void testOnePaegWithOneBehaviorResult() { - this.getDataCollector().add( - PageResult.buildPageResult(2, - ScenarioStatisticsTest.makeBehaviorList(1))); - AgentPageBriefModel pageBriefModel = (AgentPageBriefModel) this - .getDataCollector().getPageBriefStatistics(2); - assertEquals(2, pageBriefModel.getPageId()); - assertEquals(1, pageBriefModel.getCountFromBegin()); - assertEquals(1, pageBriefModel.getCountThisTime()); - assertEquals(200, pageBriefModel.getMaxResponseTimeFromBegin()); - assertEquals(200, pageBriefModel.getMinResponseTimeFromBegin()); - assertTrue(pageBriefModel.getTimeFrame() >= 0); - assertEquals(200, pageBriefModel.getTotalResponseTimeThisTime()); - assertEquals(200, pageBriefModel.getLatestResponseTime()); - } - - @Test - public void testOnePageWithTwoBehaviorResult() { - this.getDataCollector().add( - PageResult.buildPageResult(2, - ScenarioStatisticsTest.makeBehaviorList(2))); - AgentPageBriefModel pageBriefModel = (AgentPageBriefModel) this - .getDataCollector().getPageBriefStatistics(2); - System.out.println(pageBriefModel.getCountFromBegin()); - assertEquals(2, pageBriefModel.getPageId()); - assertEquals(1, pageBriefModel.getCountFromBegin()); - assertEquals(1, pageBriefModel.getCountThisTime()); - assertEquals(220, pageBriefModel.getMaxResponseTimeFromBegin()); - assertEquals(220, pageBriefModel.getMinResponseTimeFromBegin()); - assertTrue(pageBriefModel.getTimeFrame() >= 0); - assertEquals(220, pageBriefModel.getTotalResponseTimeThisTime()); - assertEquals(220, pageBriefModel.getLatestResponseTime()); - } - - @Test - public void testTwoPageWithStatisticsAtLast() { - this.getDataCollector().add( - PageResult.buildPageResult(2, - ScenarioStatisticsTest.makeBehaviorList(1))); - this.getDataCollector().add( - PageResult.buildPageResult(2, - ScenarioStatisticsTest.makeBehaviorList(2))); - AgentPageBriefModel pageBriefModel = (AgentPageBriefModel) this - .getDataCollector().getPageBriefStatistics(2); - assertEquals(2, pageBriefModel.getPageId()); - assertEquals(2, pageBriefModel.getCountFromBegin()); - assertEquals(2, pageBriefModel.getCountThisTime()); - assertEquals(220, pageBriefModel.getMaxResponseTimeFromBegin()); - assertEquals(200, pageBriefModel.getMinResponseTimeFromBegin()); - assertEquals(420, pageBriefModel.getTotalResponseTimeThisTime()); - assertTrue(pageBriefModel.getTimeFrame() >= 0); - assertEquals(220, pageBriefModel.getLatestResponseTime()); - } - - @Test - public void testTwoPageWithStatisticsIndividually() { - testOnePaegWithOneBehaviorResult(); - this.getDataCollector().add( - PageResult.buildPageResult(2, - ScenarioStatisticsTest.makeBehaviorList(2))); - AgentPageBriefModel model = (AgentPageBriefModel) this.getDataCollector() - .getPageBriefStatistics(2); - assertEquals(2, model.getPageId()); - assertEquals(2, model.getCountFromBegin()); - assertEquals(1, model.getCountThisTime()); - assertEquals(220, model.getMaxResponseTimeFromBegin()); - assertEquals(200, model.getMinResponseTimeFromBegin()); - assertEquals(220, model.getTotalResponseTimeThisTime()); - assertTrue(model.getTimeFrame() >= -0); - assertEquals(220, model.getLatestResponseTime()); - } -} +package org.bench4q.agent.test.datastatistics; + +import org.bench4q.agent.datacollector.DataCollector; +import org.bench4q.agent.datacollector.impl.PageResultCollector; +import org.bench4q.agent.scenario.PageResult; +import org.bench4q.share.models.agent.statistics.AgentPageBriefModel; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.context.support.ClassPathXmlApplicationContext; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +import static org.junit.Assert.*; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(locations = { "classpath:test-storage-context.xml", + "classpath*:/org/bench4q/agent/config/application-context.xml" }) +public class PageResultStatisticsTest { + private DataCollector dataCollector; + + private DataCollector getDataCollector() { + return dataCollector; + } + + private void setDataCollector(DataCollector dataCollector) { + this.dataCollector = dataCollector; + } + + @SuppressWarnings("resource") + public PageResultStatisticsTest() { + new ClassPathXmlApplicationContext( + "classpath*:/org/bench4q/agent/config/application-context.xml"); + this.setDataCollector(new PageResultCollector()); + } + + @Test + public void pageResultTest() { + PageResult pageResult = PageResult.buildPageResult(2, + ScenarioStatisticsTest.makeBehaviorList(1)); + assertEquals(2, pageResult.getPageId()); + assertEquals(200, pageResult.getExecuteRange()); + assertTrue(pageResult.getPageStartTime() > 0); + } + + @Test + public void pageResultWithTwoBehaviorTest() { + PageResult pageResult = PageResult.buildPageResult(2, + ScenarioStatisticsTest.makeBehaviorList(2)); + assertEquals(2, pageResult.getPageId()); + assertEquals(220, pageResult.getExecuteRange()); + assertEquals(200, pageResult.getPageStartTime()); + assertEquals(420, pageResult.getPageEndTime()); + } + + @Test + public void testNull() { + this.getDataCollector().add((PageResult) null); + assertNotNull(dataCollector.getPageBriefStatistics(0)); + } + + @Test + public void testOnePaegWithOneBehaviorResult() { + this.getDataCollector().add( + PageResult.buildPageResult(2, + ScenarioStatisticsTest.makeBehaviorList(1))); + AgentPageBriefModel pageBriefModel = (AgentPageBriefModel) this + .getDataCollector().getPageBriefStatistics(2); + assertEquals(2, pageBriefModel.getPageId()); + assertEquals(1, pageBriefModel.getCountFromBegin()); + assertEquals(1, pageBriefModel.getCountThisTime()); + assertEquals(200, pageBriefModel.getMaxResponseTimeFromBegin()); + assertEquals(200, pageBriefModel.getMinResponseTimeFromBegin()); + assertTrue(pageBriefModel.getTimeFrame() >= 0); + assertEquals(200, pageBriefModel.getTotalResponseTimeThisTime()); + assertEquals(200, pageBriefModel.getLatestResponseTime()); + } + + @Test + public void testOnePageWithTwoBehaviorResult() { + this.getDataCollector().add( + PageResult.buildPageResult(2, + ScenarioStatisticsTest.makeBehaviorList(2))); + AgentPageBriefModel pageBriefModel = (AgentPageBriefModel) this + .getDataCollector().getPageBriefStatistics(2); + System.out.println(pageBriefModel.getCountFromBegin()); + assertEquals(2, pageBriefModel.getPageId()); + assertEquals(1, pageBriefModel.getCountFromBegin()); + assertEquals(1, pageBriefModel.getCountThisTime()); + assertEquals(220, pageBriefModel.getMaxResponseTimeFromBegin()); + assertEquals(220, pageBriefModel.getMinResponseTimeFromBegin()); + assertTrue(pageBriefModel.getTimeFrame() >= 0); + assertEquals(220, pageBriefModel.getTotalResponseTimeThisTime()); + assertEquals(220, pageBriefModel.getLatestResponseTime()); + } + + @Test + public void testTwoPageWithStatisticsAtLast() { + this.getDataCollector().add( + PageResult.buildPageResult(2, + ScenarioStatisticsTest.makeBehaviorList(1))); + this.getDataCollector().add( + PageResult.buildPageResult(2, + ScenarioStatisticsTest.makeBehaviorList(2))); + AgentPageBriefModel pageBriefModel = (AgentPageBriefModel) this + .getDataCollector().getPageBriefStatistics(2); + assertEquals(2, pageBriefModel.getPageId()); + assertEquals(2, pageBriefModel.getCountFromBegin()); + assertEquals(2, pageBriefModel.getCountThisTime()); + assertEquals(220, pageBriefModel.getMaxResponseTimeFromBegin()); + assertEquals(200, pageBriefModel.getMinResponseTimeFromBegin()); + assertEquals(420, pageBriefModel.getTotalResponseTimeThisTime()); + assertTrue(pageBriefModel.getTimeFrame() >= 0); + assertEquals(220, pageBriefModel.getLatestResponseTime()); + } + + @Test + public void testTwoPageWithStatisticsIndividually() { + testOnePaegWithOneBehaviorResult(); + this.getDataCollector().add( + PageResult.buildPageResult(2, + ScenarioStatisticsTest.makeBehaviorList(2))); + AgentPageBriefModel model = (AgentPageBriefModel) this.getDataCollector() + .getPageBriefStatistics(2); + assertEquals(2, model.getPageId()); + assertEquals(2, model.getCountFromBegin()); + assertEquals(1, model.getCountThisTime()); + assertEquals(220, model.getMaxResponseTimeFromBegin()); + assertEquals(200, model.getMinResponseTimeFromBegin()); + assertEquals(220, model.getTotalResponseTimeThisTime()); + assertTrue(model.getTimeFrame() >= -0); + assertEquals(220, model.getLatestResponseTime()); + } +} diff --git a/src/test/java/org/bench4q/agent/test/datastatistics/ScenarioStatisticsTest.java b/src/test/java/org/bench4q/agent/test/datastatistics/ScenarioStatisticsTest.java index 6b0fbd75..e8680020 100644 --- a/src/test/java/org/bench4q/agent/test/datastatistics/ScenarioStatisticsTest.java +++ b/src/test/java/org/bench4q/agent/test/datastatistics/ScenarioStatisticsTest.java @@ -1,173 +1,173 @@ -package org.bench4q.agent.test.datastatistics; - -import static org.junit.Assert.*; - -import java.util.ArrayList; -import java.util.Date; -import java.util.List; -import java.util.UUID; - -import org.bench4q.agent.datacollector.impl.ScenarioResultCollector; -import org.bench4q.agent.datacollector.interfaces.DataCollector; -import org.bench4q.agent.scenario.BehaviorResult; -import org.bench4q.agent.scenario.PageResult; -import org.bench4q.agent.storage.StorageHelper; -import org.bench4q.share.models.agent.statistics.AgentBriefStatusModel; -import org.junit.Test; -import org.springframework.context.ApplicationContext; -import org.springframework.context.support.ClassPathXmlApplicationContext; - -public class ScenarioStatisticsTest { - private DataCollector dataStatistics; - - protected DataCollector getDataStatistics() { - return dataStatistics; - } - - private void setDataStatistics(DataCollector dataStatistics) { - this.dataStatistics = dataStatistics; - } - - public ScenarioStatisticsTest() { - init(); - } - - public void init() { - @SuppressWarnings("resource") - ApplicationContext context = new ClassPathXmlApplicationContext( - "classpath*:/org/bench4q/agent/config/application-context.xml"); - ScenarioResultCollector agentResultDataCollector = new ScenarioResultCollector( - UUID.randomUUID()); - agentResultDataCollector.setStorageHelper((StorageHelper) context - .getBean(StorageHelper.class)); - this.setDataStatistics(agentResultDataCollector); - } - - @Test - public void addZeroBriefTest() { - for (BehaviorResult behaviorResult : makeBehaviorList(0)) { - this.getDataStatistics().add(behaviorResult); - } - AgentBriefStatusModel model = (AgentBriefStatusModel) this - .getDataStatistics().getScenarioBriefStatistics(); - AgentBriefStatusModel modelExpect = makeAllZeroModel(); - modelExpect.setTimeFrame(model.getTimeFrame()); - assertTrue(model.equals(modelExpect)); - } - - @Test - public void addOneBriefTest() throws InterruptedException { - for (BehaviorResult behaviorResult : makeBehaviorList(1)) { - this.getDataStatistics().add(behaviorResult); - } - - Thread.sleep(100); - AgentBriefStatusModel model = (AgentBriefStatusModel) this - .getDataStatistics().getScenarioBriefStatistics(); - AgentBriefStatusModel modelExpect = new AgentBriefStatusModel(); - modelExpect.setTimeFrame(model.getTimeFrame()); - makeUpStatusModelForOneBehavior(modelExpect); - assertTrue(model.equals(modelExpect)); - } - - @Test - public void addTwoBriefTest() throws InterruptedException { - for (BehaviorResult behaviorResult : makeBehaviorList(2)) { - this.getDataStatistics().add(behaviorResult); - } - Thread.sleep(100); - AgentBriefStatusModel model = (AgentBriefStatusModel) this - .getDataStatistics().getScenarioBriefStatistics(); - AgentBriefStatusModel modelExpect = makeUpStatusModelForTwoBehavior(model - .getTimeFrame()); - assertTrue(model.equals(modelExpect)); - } - - public static AgentBriefStatusModel makeUpStatusModelForTwoBehavior( - long timeFrame) { - AgentBriefStatusModel model = new AgentBriefStatusModel(); - model.setTimeFrame(timeFrame); - model.setSuccessThroughputThisTime(1 * 1000 / timeFrame); - model.setFailCountFromBegin(1); - model.setFailThroughputThisTime(1 * 1000 / timeFrame); - model.setMaxResponseTime(200); - model.setMinResponseTime(200); - model.setSuccessCountFromBegin(1); - model.setSuccessCountThisTime(1); - model.setFailCountThisTime(1); - model.setTotalResponseTimeThisTime(200); - model.setTotalSqureResponseTimeThisTime(40000); - return model; - } - - public static void makeUpStatusModelForOneBehavior( - AgentBriefStatusModel model) { - model.setSuccessThroughputThisTime(1 * 1000 / model.getTimeFrame()); - model.setFailCountFromBegin(0); - model.setFailThroughputThisTime(0); - model.setMaxResponseTime(200); - model.setMinResponseTime(200); - model.setSuccessCountFromBegin(1); - model.setSuccessCountThisTime(1); - model.setFailCountThisTime(0); - model.setTotalResponseTimeThisTime(200); - model.setTotalSqureResponseTimeThisTime(40000); - } - - public static AgentBriefStatusModel makeAllZeroModel() { - AgentBriefStatusModel model = new AgentBriefStatusModel(); - model.setSuccessThroughputThisTime(0); - model.setFailCountFromBegin(0); - model.setFailThroughputThisTime(0); - model.setMaxResponseTime(0); - model.setMinResponseTime(0); - model.setTimeFrame(0); - model.setSuccessCountFromBegin(0); - model.setTotalResponseTimeThisTime(0); - model.setSuccessCountThisTime(0); - model.setFailCountThisTime(0); - model.setTotalSqureResponseTimeThisTime(0); - return model; - } - - public static PageResult makePageResultWithBehaviorResult(int count) { - List behaviorResults = makeBehaviorList(count); - return PageResult.buildPageResult(2, behaviorResults); - } - - public static List makeBehaviorList(int count) { - List behaviorResults = new ArrayList(); - for (int i = 0; i < count; i++) { - int statusCode = i % 2 == 0 ? 200 : 400; - behaviorResults.add(buildBehaviorResult(200 + 10 * i, i % 2 == 0, - statusCode, 1, 200 + 10 * i)); - } - return behaviorResults; - } - - public static BehaviorResult buildBehaviorResult(long responseTime, - boolean success, int statusCode, int behaviorId, long startDateTime) { - Date date = new Date(startDateTime); - BehaviorResult result = new BehaviorResult(); - result.setBehaviorName(""); - result.setEndDate(new Date(date.getTime() + responseTime)); - result.setPluginId("Get"); - result.setPluginName("get"); - result.setResponseTime(responseTime); - result.setStartDate(date); - result.setSuccess(success); - result.setShouldBeCountResponseTime(true); - - result.setBehaviorId(behaviorId); - if (result.isSuccess()) { - result.setContentLength(20); - result.setContentType("image"); - } else { - result.setContentLength(0); - result.setContentType(""); - } - result.setStatusCode(statusCode); - return result; - } - -} +package org.bench4q.agent.test.datastatistics; + +import static org.junit.Assert.*; + +import java.util.ArrayList; +import java.util.Date; +import java.util.List; +import java.util.UUID; + +import org.bench4q.agent.datacollector.DataCollector; +import org.bench4q.agent.datacollector.impl.ScenarioResultCollector; +import org.bench4q.agent.scenario.BehaviorResult; +import org.bench4q.agent.scenario.PageResult; +import org.bench4q.agent.storage.StorageHelper; +import org.bench4q.share.models.agent.statistics.AgentBriefStatusModel; +import org.junit.Test; +import org.springframework.context.ApplicationContext; +import org.springframework.context.support.ClassPathXmlApplicationContext; + +public class ScenarioStatisticsTest { + private DataCollector dataStatistics; + + protected DataCollector getDataStatistics() { + return dataStatistics; + } + + private void setDataStatistics(DataCollector dataStatistics) { + this.dataStatistics = dataStatistics; + } + + public ScenarioStatisticsTest() { + init(); + } + + public void init() { + @SuppressWarnings("resource") + ApplicationContext context = new ClassPathXmlApplicationContext( + "classpath*:/org/bench4q/agent/config/application-context.xml"); + ScenarioResultCollector agentResultDataCollector = new ScenarioResultCollector( + UUID.randomUUID()); + agentResultDataCollector.setStorageHelper((StorageHelper) context + .getBean(StorageHelper.class)); + this.setDataStatistics(agentResultDataCollector); + } + + @Test + public void addZeroBriefTest() { + for (BehaviorResult behaviorResult : makeBehaviorList(0)) { + this.getDataStatistics().add(behaviorResult); + } + AgentBriefStatusModel model = (AgentBriefStatusModel) this + .getDataStatistics().getScenarioBriefStatistics(); + AgentBriefStatusModel modelExpect = makeAllZeroModel(); + modelExpect.setTimeFrame(model.getTimeFrame()); + assertTrue(model.equals(modelExpect)); + } + + @Test + public void addOneBriefTest() throws InterruptedException { + for (BehaviorResult behaviorResult : makeBehaviorList(1)) { + this.getDataStatistics().add(behaviorResult); + } + + Thread.sleep(100); + AgentBriefStatusModel model = (AgentBriefStatusModel) this + .getDataStatistics().getScenarioBriefStatistics(); + AgentBriefStatusModel modelExpect = new AgentBriefStatusModel(); + modelExpect.setTimeFrame(model.getTimeFrame()); + makeUpStatusModelForOneBehavior(modelExpect); + assertTrue(model.equals(modelExpect)); + } + + @Test + public void addTwoBriefTest() throws InterruptedException { + for (BehaviorResult behaviorResult : makeBehaviorList(2)) { + this.getDataStatistics().add(behaviorResult); + } + Thread.sleep(100); + AgentBriefStatusModel model = (AgentBriefStatusModel) this + .getDataStatistics().getScenarioBriefStatistics(); + AgentBriefStatusModel modelExpect = makeUpStatusModelForTwoBehavior(model + .getTimeFrame()); + assertTrue(model.equals(modelExpect)); + } + + public static AgentBriefStatusModel makeUpStatusModelForTwoBehavior( + long timeFrame) { + AgentBriefStatusModel model = new AgentBriefStatusModel(); + model.setTimeFrame(timeFrame); + model.setSuccessThroughputThisTime(1 * 1000 / timeFrame); + model.setFailCountFromBegin(1); + model.setFailThroughputThisTime(1 * 1000 / timeFrame); + model.setMaxResponseTime(200); + model.setMinResponseTime(200); + model.setSuccessCountFromBegin(1); + model.setSuccessCountThisTime(1); + model.setFailCountThisTime(1); + model.setTotalResponseTimeThisTime(200); + model.setTotalSqureResponseTimeThisTime(40000); + return model; + } + + public static void makeUpStatusModelForOneBehavior( + AgentBriefStatusModel model) { + model.setSuccessThroughputThisTime(1 * 1000 / model.getTimeFrame()); + model.setFailCountFromBegin(0); + model.setFailThroughputThisTime(0); + model.setMaxResponseTime(200); + model.setMinResponseTime(200); + model.setSuccessCountFromBegin(1); + model.setSuccessCountThisTime(1); + model.setFailCountThisTime(0); + model.setTotalResponseTimeThisTime(200); + model.setTotalSqureResponseTimeThisTime(40000); + } + + public static AgentBriefStatusModel makeAllZeroModel() { + AgentBriefStatusModel model = new AgentBriefStatusModel(); + model.setSuccessThroughputThisTime(0); + model.setFailCountFromBegin(0); + model.setFailThroughputThisTime(0); + model.setMaxResponseTime(0); + model.setMinResponseTime(0); + model.setTimeFrame(0); + model.setSuccessCountFromBegin(0); + model.setTotalResponseTimeThisTime(0); + model.setSuccessCountThisTime(0); + model.setFailCountThisTime(0); + model.setTotalSqureResponseTimeThisTime(0); + return model; + } + + public static PageResult makePageResultWithBehaviorResult(int count) { + List behaviorResults = makeBehaviorList(count); + return PageResult.buildPageResult(2, behaviorResults); + } + + public static List makeBehaviorList(int count) { + List behaviorResults = new ArrayList(); + for (int i = 0; i < count; i++) { + int statusCode = i % 2 == 0 ? 200 : 400; + behaviorResults.add(buildBehaviorResult(200 + 10 * i, i % 2 == 0, + statusCode, 1, 200 + 10 * i)); + } + return behaviorResults; + } + + public static BehaviorResult buildBehaviorResult(long responseTime, + boolean success, int statusCode, int behaviorId, long startDateTime) { + Date date = new Date(startDateTime); + BehaviorResult result = new BehaviorResult(); + result.setBehaviorName(""); + result.setEndDate(new Date(date.getTime() + responseTime)); + result.setPluginId("Get"); + result.setPluginName("get"); + result.setResponseTime(responseTime); + result.setStartDate(date); + result.setSuccess(success); + result.setShouldBeCountResponseTime(true); + + result.setBehaviorId(behaviorId); + if (result.isSuccess()) { + result.setContentLength(20); + result.setContentType("image"); + } else { + result.setContentLength(0); + result.setContentType(""); + } + result.setStatusCode(statusCode); + return result; + } + +} From 2951dfaf6c9546ad6bee5461014d3e74fc14cc6d Mon Sep 17 00:00:00 2001 From: coderfengyun Date: Fri, 14 Mar 2014 11:14:30 +0800 Subject: [PATCH 177/196] add tests and refactor --- .../impl/InstanceControler.java | 7 +- ...arser.java => ParameterizationParser.java} | 15 ++-- .../java/org/bench4q/agent/test/MainTest.java | 74 +++++++++---------- .../parameterization}/TEST_HelloThread.java | 4 +- .../test/parameterization}/TEST_UserName.java | 4 +- .../Test_ParameterizationParser.java | 30 ++++++++ 6 files changed, 84 insertions(+), 50 deletions(-) rename src/main/java/org/bench4q/agent/parameterization/impl/{ParameterParser.java => ParameterizationParser.java} (81%) rename src/{main/java/org/bench4q/agent/parameterization/impl => test/java/org/bench4q/agent/test/parameterization}/TEST_HelloThread.java (92%) rename src/{main/java/org/bench4q/agent/parameterization/impl => test/java/org/bench4q/agent/test/parameterization}/TEST_UserName.java (85%) create mode 100644 src/test/java/org/bench4q/agent/test/parameterization/Test_ParameterizationParser.java diff --git a/src/main/java/org/bench4q/agent/parameterization/impl/InstanceControler.java b/src/main/java/org/bench4q/agent/parameterization/impl/InstanceControler.java index 00bf5313..53df2055 100644 --- a/src/main/java/org/bench4q/agent/parameterization/impl/InstanceControler.java +++ b/src/main/java/org/bench4q/agent/parameterization/impl/InstanceControler.java @@ -43,11 +43,8 @@ public class InstanceControler implements SessionObject { argTypeArr[i] = args[i - 2].getClass(); totalArgs[i] = args[i - 2]; } - Method m = instance.getClass().getMethod(functionName, argTypeArr); - result = m.invoke(instance, totalArgs); - } catch (Exception ex) { System.out.println(ex.getMessage() + ex.getStackTrace()); System.out.println(((InvocationTargetException) ex) @@ -66,7 +63,7 @@ public class InstanceControler implements SessionObject { return runtimeParaMap.get(name); } - public boolean createObj(String className) { + private boolean createObj(String className) { try { MyFileClassLoader cl = new MyFileClassLoader(); cl.setClassPath(userDefineParameterFolderPath); @@ -136,7 +133,7 @@ public class InstanceControler implements SessionObject { public String getParam(String name) { if (!(name.startsWith(""))) return name; - ParameterParser p = new ParameterParser(); + ParameterizationParser p = new ParameterizationParser(); return p.parse(name, this); } diff --git a/src/main/java/org/bench4q/agent/parameterization/impl/ParameterParser.java b/src/main/java/org/bench4q/agent/parameterization/impl/ParameterizationParser.java similarity index 81% rename from src/main/java/org/bench4q/agent/parameterization/impl/ParameterParser.java rename to src/main/java/org/bench4q/agent/parameterization/impl/ParameterizationParser.java index 382f28e1..66a1837b 100644 --- a/src/main/java/org/bench4q/agent/parameterization/impl/ParameterParser.java +++ b/src/main/java/org/bench4q/agent/parameterization/impl/ParameterizationParser.java @@ -1,6 +1,7 @@ package org.bench4q.agent.parameterization.impl; import java.io.StringReader; + import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; @@ -8,13 +9,11 @@ import org.w3c.dom.Document; import org.w3c.dom.Element; import org.xml.sax.InputSource; -public class ParameterParser { +public class ParameterizationParser { public String parse(String text, InstanceControler insCon) { // Pattern pattern = Pattern.compile(""); - String result = ""; - try { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); @@ -34,9 +33,8 @@ public class ParameterParser { if (result != null) return result; if (type == "crossThread") { - result = insCon.getParameter(name, - "org.bench4q.agent.parameters." + className, - methodName, args); + result = insCon.getParameter(name, getCurrentPackageFullName() + + "." + className, methodName, args); } else if (type == "inThread") { result = insCon.instanceLevelGetParameter(name, className, methodName, args); @@ -47,4 +45,9 @@ public class ParameterParser { } return result; } + + private String getCurrentPackageFullName() { + return this.getClass().getName() + .substring(0, this.getClass().getName().lastIndexOf('.')); + } } diff --git a/src/test/java/org/bench4q/agent/test/MainTest.java b/src/test/java/org/bench4q/agent/test/MainTest.java index c79fa7d1..70602654 100644 --- a/src/test/java/org/bench4q/agent/test/MainTest.java +++ b/src/test/java/org/bench4q/agent/test/MainTest.java @@ -1,37 +1,37 @@ -package org.bench4q.agent.test; - -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.util.Properties; - -import org.bench4q.agent.Main; -import org.junit.Test; - -import static org.junit.Assert.*; - -public class MainTest { - public MainTest() { - Main.init(); - } - - @Test - public void initTest() { - Main.init(); - assertTrue(new File("configure").exists()); - } - - @Test - public void getPropertiesTest() throws IOException { - FileInputStream inputStream = new FileInputStream(new File("configure" - + System.getProperty("file.separator") - + "agent-config.properties")); - Properties properties = new Properties(); - properties.load(inputStream); - assertEquals(6565, - Integer.parseInt((String) properties.get("servePort"))); - assertEquals(false, Boolean.parseBoolean((String) properties - .get("isToSaveDetailResult"))); - } - -} +package org.bench4q.agent.test; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.util.Properties; + +import org.bench4q.agent.Main; +import org.junit.Test; + +import static org.junit.Assert.*; + +public class MainTest { + public MainTest() { + Main.init(); + } + + @Test + public void initTest() { + Main.init(); + assertTrue(new File("configure").exists()); + } + + @Test + public void getPropertiesTest() throws IOException { + FileInputStream inputStream = new FileInputStream(new File("configure" + + System.getProperty("file.separator") + + "agent-config.properties")); + Properties properties = new Properties(); + properties.load(inputStream); + assertEquals(6565, + Integer.parseInt((String) properties.get("servePort"))); + assertEquals(false, Boolean.parseBoolean((String) properties + .get("isToSaveDetailResult"))); + } + +} diff --git a/src/main/java/org/bench4q/agent/parameterization/impl/TEST_HelloThread.java b/src/test/java/org/bench4q/agent/test/parameterization/TEST_HelloThread.java similarity index 92% rename from src/main/java/org/bench4q/agent/parameterization/impl/TEST_HelloThread.java rename to src/test/java/org/bench4q/agent/test/parameterization/TEST_HelloThread.java index 477f6683..162ec160 100644 --- a/src/main/java/org/bench4q/agent/parameterization/impl/TEST_HelloThread.java +++ b/src/test/java/org/bench4q/agent/test/parameterization/TEST_HelloThread.java @@ -1,4 +1,6 @@ -package org.bench4q.agent.parameterization.impl; +package org.bench4q.agent.test.parameterization; + +import org.bench4q.agent.parameterization.impl.InstanceControler; public class TEST_HelloThread extends Thread { InstanceControler ic; diff --git a/src/main/java/org/bench4q/agent/parameterization/impl/TEST_UserName.java b/src/test/java/org/bench4q/agent/test/parameterization/TEST_UserName.java similarity index 85% rename from src/main/java/org/bench4q/agent/parameterization/impl/TEST_UserName.java rename to src/test/java/org/bench4q/agent/test/parameterization/TEST_UserName.java index 65b92b50..40568dfd 100644 --- a/src/main/java/org/bench4q/agent/parameterization/impl/TEST_UserName.java +++ b/src/test/java/org/bench4q/agent/test/parameterization/TEST_UserName.java @@ -1,4 +1,6 @@ -package org.bench4q.agent.parameterization.impl; +package org.bench4q.agent.test.parameterization; + +import org.bench4q.agent.parameterization.impl.InstanceControler; public class TEST_UserName { diff --git a/src/test/java/org/bench4q/agent/test/parameterization/Test_ParameterizationParser.java b/src/test/java/org/bench4q/agent/test/parameterization/Test_ParameterizationParser.java new file mode 100644 index 00000000..7e8d1531 --- /dev/null +++ b/src/test/java/org/bench4q/agent/test/parameterization/Test_ParameterizationParser.java @@ -0,0 +1,30 @@ +package org.bench4q.agent.test.parameterization; + +import static org.junit.Assert.assertEquals; + +import java.util.UUID; + +import org.bench4q.agent.parameterization.impl.InstanceControler; +import org.bench4q.agent.parameterization.impl.ParameterizationParser; +import org.bench4q.share.helper.TestHelper; +import org.junit.Test; + +public class Test_ParameterizationParser { + @Test + public void testGetClassName() throws Exception { + String result = (String) TestHelper.invokePrivate( + ParameterizationParser.class, new ParameterizationParser(), + "getCurrentPackageFullName", null, null); + assertEquals("org.bench4q.agent.parameterization.impl", result); + } + + @Test + public void testParse() { + ParameterizationParser parameterParser = new ParameterizationParser(); + String result = parameterParser.parse( + "", + new InstanceControler()); + System.out.println(result); + } +} From ad688287e33b08b898da8b4507203338efa3c407 Mon Sep 17 00:00:00 2001 From: coderfengyun Date: Fri, 14 Mar 2014 14:03:20 +0800 Subject: [PATCH 178/196] little refa --- .../impl/Para_IteratorNumber.java | 23 +++++++++++-------- .../impl/ParameterizationParser.java | 4 ++-- .../Test_ParameterizationParser.java | 7 ++---- 3 files changed, 18 insertions(+), 16 deletions(-) diff --git a/src/main/java/org/bench4q/agent/parameterization/impl/Para_IteratorNumber.java b/src/main/java/org/bench4q/agent/parameterization/impl/Para_IteratorNumber.java index a696f7d9..e4d42743 100644 --- a/src/main/java/org/bench4q/agent/parameterization/impl/Para_IteratorNumber.java +++ b/src/main/java/org/bench4q/agent/parameterization/impl/Para_IteratorNumber.java @@ -1,24 +1,29 @@ package org.bench4q.agent.parameterization.impl; +import java.util.Map; import java.util.UUID; public class Para_IteratorNumber { public Long iteratorNum = new Long(0); - - public String getIteratorNumber(UUID id) - { + + /** + * For all methods, they will has these two params + * + * @param id + * @param a + * @return + */ + public String getIteratorNumber(UUID id, Map a) { long result = 0; - synchronized(iteratorNum) - { + synchronized (iteratorNum) { iteratorNum++; result = iteratorNum; } String ret = String.valueOf(result); return ret; } - - public void unreg(UUID id) - { - + + public void unreg(UUID id) { + } } diff --git a/src/main/java/org/bench4q/agent/parameterization/impl/ParameterizationParser.java b/src/main/java/org/bench4q/agent/parameterization/impl/ParameterizationParser.java index 66a1837b..32e4d513 100644 --- a/src/main/java/org/bench4q/agent/parameterization/impl/ParameterizationParser.java +++ b/src/main/java/org/bench4q/agent/parameterization/impl/ParameterizationParser.java @@ -32,10 +32,10 @@ public class ParameterizationParser { result = insCon.getParameterByContext(name); if (result != null) return result; - if (type == "crossThread") { + if (type.equals("crossThread")) { result = insCon.getParameter(name, getCurrentPackageFullName() + "." + className, methodName, args); - } else if (type == "inThread") { + } else if (type.equals("inThread")) { result = insCon.instanceLevelGetParameter(name, className, methodName, args); } diff --git a/src/test/java/org/bench4q/agent/test/parameterization/Test_ParameterizationParser.java b/src/test/java/org/bench4q/agent/test/parameterization/Test_ParameterizationParser.java index 7e8d1531..f4140855 100644 --- a/src/test/java/org/bench4q/agent/test/parameterization/Test_ParameterizationParser.java +++ b/src/test/java/org/bench4q/agent/test/parameterization/Test_ParameterizationParser.java @@ -2,8 +2,6 @@ package org.bench4q.agent.test.parameterization; import static org.junit.Assert.assertEquals; -import java.util.UUID; - import org.bench4q.agent.parameterization.impl.InstanceControler; import org.bench4q.agent.parameterization.impl.ParameterizationParser; import org.bench4q.share.helper.TestHelper; @@ -22,9 +20,8 @@ public class Test_ParameterizationParser { public void testParse() { ParameterizationParser parameterParser = new ParameterizationParser(); String result = parameterParser.parse( - "", - new InstanceControler()); + "", new InstanceControler()); System.out.println(result); } } From 864debb4874f073f198486679fba21c5427e312f Mon Sep 17 00:00:00 2001 From: yxsh Date: Fri, 14 Mar 2014 15:40:05 +0800 Subject: [PATCH 179/196] save for re-install machine --- .../parameterization/impl/Para_Table.java | 57 +++++++++++++++++++ .../parameterization/impl/Para_Table.xml | 19 +++++++ 2 files changed, 76 insertions(+) create mode 100644 src/main/java/org/bench4q/agent/parameterization/impl/Para_Table.java create mode 100644 src/main/java/org/bench4q/agent/parameterization/impl/Para_Table.xml diff --git a/src/main/java/org/bench4q/agent/parameterization/impl/Para_Table.java b/src/main/java/org/bench4q/agent/parameterization/impl/Para_Table.java new file mode 100644 index 00000000..78e1c14a --- /dev/null +++ b/src/main/java/org/bench4q/agent/parameterization/impl/Para_Table.java @@ -0,0 +1,57 @@ +package org.bench4q.agent.parameterization.impl; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileReader; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +public class Para_Table { + + public int state = 0;// 1 sequence 2 random + public class Table + { + private final String source; + + public Table() + { + source = + } + public List rows = new ArrayList(); + + public int getTime= 0; + public boolean add(TableRow r) + { + return rows.add(r); + } + public TableRow pop() + { + + } + } + + public class TableRow + { + List cells = new ArrayList(); + } + public String getTableColumnValue(UUID id, Map objCache, + String source, String sourceValue, String firstRow, String nextRow, + String splitChar, String lineChar) { + if(source == "file") + { + try { + File file = new File(sourceValue); + BufferedReader reader = new BufferedReader(new FileReader(file)); + //reader. + } catch (FileNotFoundException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + } + } + +} diff --git a/src/main/java/org/bench4q/agent/parameterization/impl/Para_Table.xml b/src/main/java/org/bench4q/agent/parameterization/impl/Para_Table.xml new file mode 100644 index 00000000..b1ba35f4 --- /dev/null +++ b/src/main/java/org/bench4q/agent/parameterization/impl/Para_Table.xml @@ -0,0 +1,19 @@ + + + + file + input + + + + + + + sequence + random + + + + + + From a656b8b081be3500fb226596a8deb4b756309a93 Mon Sep 17 00:00:00 2001 From: yxsh Date: Mon, 17 Mar 2014 15:19:46 +0800 Subject: [PATCH 180/196] group function --- .../parameterization/impl/Para_Table.java | 290 ++++++++++++++++-- 1 file changed, 256 insertions(+), 34 deletions(-) diff --git a/src/main/java/org/bench4q/agent/parameterization/impl/Para_Table.java b/src/main/java/org/bench4q/agent/parameterization/impl/Para_Table.java index 78e1c14a..a065b831 100644 --- a/src/main/java/org/bench4q/agent/parameterization/impl/Para_Table.java +++ b/src/main/java/org/bench4q/agent/parameterization/impl/Para_Table.java @@ -2,56 +2,278 @@ package org.bench4q.agent.parameterization.impl; import java.io.BufferedReader; import java.io.File; +import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.nio.CharBuffer; import java.util.ArrayList; import java.util.List; import java.util.Map; +import java.util.Random; import java.util.UUID; +import java.util.concurrent.ArrayBlockingQueue; public class Para_Table { - - public int state = 0;// 1 sequence 2 random - public class Table - { - private final String source; - - public Table() - { - source = + public final int cacheCap = 5000;// 1 sequence 2 random + public final int cacheSize = 1000;// 1 sequence 2 random + public final int readCharSize = 10000; + + public abstract class Reader { + public final Table t; + + public Reader(Table table) { + this.t = table; } + + public abstract TableRow nextRow(); + + } + + public class RandomReader extends Reader { + public ArrayBlockingQueue queue; + + public RandomReader(ArrayBlockingQueue queue, Table t) { + super(t); + this.queue = queue; + } + + @Override + public TableRow nextRow() { + // TODO Auto-generated method stub + TableRow result = null; + do { + if (queue.size() == 0) { + synchronized (queue) { + if (queue.size() == 0) { + List rows = t.readRows(); + int n = rows.size(); + Random r = new Random(); + for (int i = 0; i < n; i++) { + int next = r.nextInt(n); + TableRow tempRow = rows.get(i); + rows.set(i, rows.get(next)); + rows.set(next, tempRow); + } + queue.addAll(rows); + } + } + } + result = queue.poll(); + } while (result != null); + return result; + } + + } + + public class SequenceReader extends Reader { + public ArrayBlockingQueue queue; + + public SequenceReader(ArrayBlockingQueue queue, Table t) { + super(t); + this.queue = queue; + } + + @Override + public TableRow nextRow() { + // TODO Auto-generated method stub + TableRow result = null; + do { + if (queue.size() == 0) { + synchronized (queue) { + if (queue.size() == 0) { + List rows = t.readRows(); + queue.addAll(rows); + } + } + } + result = queue.poll(); + } while (result != null); + return result; + } + + } + + public abstract class Table { + String sourceValue; + int firstRow; + + public Table(String sourceValue, int firstRow) { + this.sourceValue = sourceValue; + } + + public abstract List readRows(); + public List rows = new ArrayList(); - - public int getTime= 0; - public boolean add(TableRow r) - { + + public int getTime = 0; + + public boolean add(TableRow r) { return rows.add(r); } - public TableRow pop() - { - + } + + public class FileTable extends Table { + private BufferedReader bfr; + char splitChar; + char lineChar; + + public FileTable(String sourceValue, int firstRow, char splitChar, + char lineChar) { + super(sourceValue, firstRow); + // TODO Auto-generated constructor stub + this.splitChar = splitChar; + this.lineChar = lineChar; + } - } - - public class TableRow - { - List cells = new ArrayList(); - } - public String getTableColumnValue(UUID id, Map objCache, - String source, String sourceValue, String firstRow, String nextRow, - String splitChar, String lineChar) { - if(source == "file") - { - try { - File file = new File(sourceValue); - BufferedReader reader = new BufferedReader(new FileReader(file)); - //reader. - } catch (FileNotFoundException e) { - // TODO Auto-generated catch block - e.printStackTrace(); + + private void createBFR() throws IOException { + FileInputStream fis = new FileInputStream(sourceValue); + InputStreamReader ir = new InputStreamReader(fis); + bfr = new BufferedReader(ir); + for (int i = 0; i < firstRow;) { + char readChar = (char) bfr.read(); + if (readChar == lineChar) + i++; } } + + @Override + public List readRows() { + // TODO Auto-generated method stub + CharBuffer target = CharBuffer.allocate(readCharSize); + List result = new ArrayList(); + TableRow tempTableRow = new TableRow(); + try { + for (int i = 0; i < cacheSize;) { + char readBuff = (char) bfr.read(); + if (readBuff == -1) { + createBFR(); + break; + } else if (readBuff == this.splitChar) { + tempTableRow.AddCell(target.toString()); + target.clear(); + } else if (readBuff == this.lineChar) { + tempTableRow.AddCell(target.toString()); + result.add(tempTableRow); + target.clear(); + i++; + } + target.append(readBuff); + } + } catch (IOException ioex) { + return result; + } + if (target.length() > 0) { + tempTableRow.AddCell(target.toString()); + result.add(tempTableRow); + target.clear(); + } + return result; + // try { + // bfr.read(target); + // } catch (IOException ioex) { + // return null; + // } + // createBFR(); + // String readStr = target.toString(); + // String[] tokens = readStr.split(String.valueOf(lineChar)); + // + // for(String line : tokens) + // { + // TableRow tempRow = new TableRow(); + // String [] columns = line.split(String.valueOf(splitChar)); + // for(String column : columns) + // { + // tempRow.AddCell(column); + // } + // result.add(tempRow); + // } + // return result; + } + + } + + public class StringTable extends Table { + + char splitChar; + char lineChar; + + public StringTable(String sourceValue, int firstRow, char splitChar, + char lineChar) { + super(sourceValue, firstRow); + // TODO Auto-generated constructor stub + this.splitChar = splitChar; + this.lineChar = lineChar; + } + + @Override + public List readRows() { + // TODO Auto-generated method stub + String readStr = this.sourceValue; + String[] tokens = readStr.split(String.valueOf(lineChar)); + List result = new ArrayList(); + for (String line : tokens) { + TableRow tempRow = new TableRow(); + String[] columns = line.split(String.valueOf(splitChar)); + for (String column : columns) { + tempRow.AddCell(column); + } + result.add(tempRow); + } + return result; + } + + } + + public class TableRow { + public List cells = new ArrayList(); + + public void AddCell(String s) { + cells.add(s); + } + } + + public String getTableColumnValue(UUID id, Map objCache, + String source, String sourceValue, String firstRow, String nextRow, + String splitChar, String lineChar,String column) { + int fRow = Integer.parseInt(firstRow); + char sChar = splitChar.charAt(0); + char lChar = lineChar.charAt(0); + int col = Integer.parseInt(column); + TableRow resultRow = null; + Table table = null; + Reader reader = null; + if(objCache.containsKey(sourceValue) == true) + { + resultRow = (TableRow)objCache.get(sourceValue); + return resultRow.cells.get(col); + } + if (source.equals("file")) { + table = new FileTable(sourceValue,fRow,sChar,lChar); + } + else if(source.equals("input")) + { + table = new StringTable(sourceValue,fRow,sChar,lChar); + } + + if(nextRow.equals("random")) + { + ArrayBlockingQueue queue = new ArrayBlockingQueue(cacheCap); + reader = new RandomReader(queue,table); + } + else if(nextRow.equals("sequence")) + { + + ArrayBlockingQueue queue = new ArrayBlockingQueue(cacheCap); + reader = new SequenceReader(queue,table); + } + + resultRow = reader.nextRow(); + objCache.put(sourceValue, resultRow); + return resultRow.cells.get(col); } } From 22c76452bef03acdda88b7869de3c4d528496f84 Mon Sep 17 00:00:00 2001 From: coderfengyun Date: Mon, 17 Mar 2014 22:42:48 +0800 Subject: [PATCH 181/196] add ways to upload config file --- Upload/ready | 2076 +++++++++++++++++ Upload/test | 11 + pom.xml | 12 +- .../org/bench4q/agent/api/TestController.java | 22 +- .../parameterization/impl/Para_Table.java | 93 +- .../parameterization/impl/Para_Table.xml | 32 +- .../agent/config/application-context.xml | 27 +- .../java/Communication/HttpRequester.java | 276 --- .../agent/test/TestControllerTest.java | 5 - .../agent/test/TestWithScriptFile.java | 17 +- 10 files changed, 2208 insertions(+), 363 deletions(-) create mode 100644 Upload/ready create mode 100644 Upload/test delete mode 100644 src/test/java/Communication/HttpRequester.java delete mode 100644 src/test/java/org/bench4q/agent/test/TestControllerTest.java diff --git a/Upload/ready b/Upload/ready new file mode 100644 index 00000000..aeb6083b --- /dev/null +++ b/Upload/ready @@ -0,0 +1,2076 @@ + + + + + + + + + 0 + Get + + + url + http://133.133.12.2:8080/bench4q-web/homepage.jsp + + + + queryParams + + + + headers + header=Accept|value= + text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8|; + + + + USERBEHAVIOR + http + + + -1 + 0 + -1 + + + + + 0 + Sleep + + + time + 15 + + + TIMERBEHAVIOR + timer + + + -1 + 1 + -1 + + + + + 1 + Get + + + url + http://133.133.12.2:8080/bench4q-web/index.jsp + + + queryParams + + + + headers + header=Accept|value= + text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8|; + + + + USERBEHAVIOR + http + + + 4 + 2 + -1 + + + + + 0 + Sleep + + + time + 133 + + + TIMERBEHAVIOR + timer + + + -1 + 3 + -1 + + + + + 2 + Get + + + url + http://133.133.12.2:8080/bench4q-web/css/bootstrap-cerulean.css + + + + queryParams + + + + headers + header=Accept|value= + text/css,*/*;q=0.1|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/index.jsp|; + + + + USERBEHAVIOR + http + + + 3 + Get + + + url + http://133.133.12.2:8080/bench4q-web/script/login.js + + + + queryParams + + + + headers + header=Accept|value= + */*|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/index.jsp|; + + + + USERBEHAVIOR + http + + + 4 + Get + + + url + http://133.133.12.2:8080/bench4q-web/js/jquery-1.7.2.min.js + + + + queryParams + + + + headers + header=Accept|value= + */*|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/index.jsp|; + + + + USERBEHAVIOR + http + + + 5 + Get + + + url + http://133.133.12.2:8080/bench4q-web/js/jquery.i18n.properties-1.0.9.js + + + + queryParams + + + + headers + header=Accept|value= + */*|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/index.jsp|; + + + + USERBEHAVIOR + http + + + 6 + Get + + + url + http://133.133.12.2:8080/bench4q-web/css/charisma-app.css + + + + queryParams + + + + headers + header=Accept|value= + text/css,*/*;q=0.1|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/index.jsp|; + + + + USERBEHAVIOR + http + + + -1 + 4 + 2 + + + + + 0 + Sleep + + + time + 1 + + + TIMERBEHAVIOR + timer + + + -1 + 5 + -1 + + + + + 0 + Sleep + + + time + 72 + + + TIMERBEHAVIOR + timer + + + -1 + 6 + -1 + + + + + 0 + Sleep + + + time + 24 + + + TIMERBEHAVIOR + timer + + + -1 + 7 + -1 + + + + + 0 + Sleep + + + time + 1 + + + TIMERBEHAVIOR + timer + + + -1 + 8 + -1 + + + + + 0 + Sleep + + + time + 211 + + + TIMERBEHAVIOR + timer + + + -1 + 9 + -1 + + + + + 7 + Get + + + url + http://fonts.googleapis.com/css + + + queryParams + family=Karla|Ubuntu + + + headers + header=Accept|value= + text/css,*/*;q=0.1|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/index.jsp|; + + + + USERBEHAVIOR + http + + + -1 + 10 + -1 + + + + + 0 + Sleep + + + time + 3 + + + TIMERBEHAVIOR + timer + + + -1 + 11 + -1 + + + + + 8 + Get + + + url + http://fonts.googleapis.com/css + + + queryParams + family=Shojumaru + + + headers + header=Accept|value= + text/css,*/*;q=0.1|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/index.jsp|; + + + + USERBEHAVIOR + http + + + -1 + 12 + -1 + + + + + 0 + Sleep + + + time + 82 + + + TIMERBEHAVIOR + timer + + + -1 + 13 + -1 + + + + + 9 + Get + + + url + http://133.133.12.2:8080/bench4q-web/img/glyphicons-halflings.png + + + + queryParams + + + + headers + header=Accept|value= + image/webp,*/*;q=0.8|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/index.jsp|; + + + + USERBEHAVIOR + http + + + -1 + 14 + -1 + + + + + 0 + Sleep + + + time + 2 + + + TIMERBEHAVIOR + timer + + + -1 + 15 + -1 + + + + + 10 + Get + + + url + http://133.133.12.2:8080/bench4q-web/i18n/i18n.properties + + + + queryParams + _=1389777175541 + + + headers + header=Content-Type|value=text/plain;charset=UTF-8|;header=Accept|value= + text/plain, */*; + q=0.01|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/index.jsp|; + + + + USERBEHAVIOR + http + + + -1 + 16 + -1 + + + + + 0 + Sleep + + + time + 10 + + + TIMERBEHAVIOR + timer + + + -1 + 17 + -1 + + + + + 11 + Get + + + url + http://133.133.12.2:8080/bench4q-web/i18n/i18n_zh.properties + + + + queryParams + _=1389777175572 + + + headers + header=Content-Type|value=text/plain;charset=UTF-8|;header=Accept|value= + text/plain, */*; + q=0.01|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/index.jsp|; + + + + USERBEHAVIOR + http + + + -1 + 18 + -1 + + + + + 0 + Sleep + + + time + 8 + + + TIMERBEHAVIOR + timer + + + -1 + 19 + -1 + + + + + 12 + Get + + + url + http://133.133.12.2:8080/bench4q-web/i18n/i18n_zh-CN.properties + + + + queryParams + _=1389777175587 + + + headers + header=Content-Type|value=text/plain;charset=UTF-8|;header=Accept|value= + text/plain, */*; + q=0.01|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/index.jsp|; + + + + USERBEHAVIOR + http + + + -1 + 20 + -1 + + + + + 0 + Sleep + + + time + 52 + + + TIMERBEHAVIOR + timer + + + -1 + 21 + -1 + + + + + 13 + Get + + + url + http://themes.googleusercontent.com/static/fonts/karla/v3/azR40LUJrT4HaWK28zHmVA.woff + + + + queryParams + + + + headers + header=Accept|value= + */*|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/index.jsp|; + + + + USERBEHAVIOR + http + + + -1 + 22 + -1 + + + + + 0 + Sleep + + + time + 16442 + + + TIMERBEHAVIOR + timer + + + -1 + 23 + -1 + + + + + 14 + Get + + + url + http://themes.googleusercontent.com/static/fonts/ubuntu/v5/_xyN3apAT_yRRDeqB3sPRg.woff + + + + queryParams + + + + headers + header=Accept|value= + */*|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/index.jsp|; + + + + USERBEHAVIOR + http + + + -1 + 24 + -1 + + + + + + + + + 0 + Sleep + + + time + 9 + + + TIMERBEHAVIOR + timer + + + 3 + 25 + -1 + + + + + 15 + Get + + + url + http://133.133.12.2:8080/bench4q-web/homepage.jsp + + + + queryParams + + + + headers + header=Accept|value= + text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/index.jsp|; + + + + USERBEHAVIOR + http + + + -1 + 26 + -1 + + + + + 0 + Sleep + + + time + 25 + + + TIMERBEHAVIOR + timer + + + -1 + 27 + -1 + + + + + 16 + Get + + + url + http://133.133.12.2:8080/bench4q-web/css/bootstrap-responsive.css + + + + queryParams + + + + headers + header=Accept|value= + text/css,*/*;q=0.1|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/homepage.jsp|; + + + + USERBEHAVIOR + http + + + 17 + Get + + + url + http://133.133.12.2:8080/bench4q-web/css/noty_theme_default.css + + + + queryParams + + + + headers + header=Accept|value= + text/css,*/*;q=0.1|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/homepage.jsp|; + + + + USERBEHAVIOR + http + + + 18 + Get + + + url + http://133.133.12.2:8080/bench4q-web/js/jquery-1.8.2.min.js + + + + queryParams + + + + headers + header=Accept|value= + */*|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/homepage.jsp|; + + + + USERBEHAVIOR + http + + + 19 + Get + + + url + http://133.133.12.2:8080/bench4q-web/bench4q-css/bench4q.css + + + + queryParams + + + + headers + header=Accept|value= + text/css,*/*;q=0.1|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/homepage.jsp|; + + + + USERBEHAVIOR + http + + + 20 + Get + + + url + http://133.133.12.2:8080/bench4q-web/css/jquery-ui-1.8.21.custom.css + + + + queryParams + + + + headers + header=Accept|value= + text/css,*/*;q=0.1|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/homepage.jsp|; + + + + USERBEHAVIOR + http + + + 21 + Get + + + url + http://133.133.12.2:8080/bench4q-web/css/opa-icons.css + + + + queryParams + + + + headers + header=Accept|value= + text/css,*/*;q=0.1|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/homepage.jsp|; + + + + USERBEHAVIOR + http + + + 22 + Get + + + url + http://133.133.12.2:8080/bench4q-web/css/colorbox.css + + + + queryParams + + + + headers + header=Accept|value= + text/css,*/*;q=0.1|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/homepage.jsp|; + + + + USERBEHAVIOR + http + + + 23 + Get + + + url + http://133.133.12.2:8080/bench4q-web/js/jquery.cookie.js + + + + queryParams + + + + headers + header=Accept|value= + */*|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/homepage.jsp|; + + + + USERBEHAVIOR + http + + + 24 + Get + + + url + http://133.133.12.2:8080/bench4q-web/js/jquery.dataTables.min.js + + + + queryParams + + + + headers + header=Accept|value= + */*|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/homepage.jsp|; + + + + USERBEHAVIOR + http + + + 25 + Get + + + url + http://133.133.12.2:8080/bench4q-web/js/theme.js + + + queryParams + + + + headers + header=Accept|value= + */*|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/homepage.jsp|; + + + + USERBEHAVIOR + http + + + 26 + Get + + + url + http://133.133.12.2:8080/bench4q-web/script/base.js + + + + queryParams + + + + headers + header=Accept|value= + */*|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/homepage.jsp|; + + + + USERBEHAVIOR + http + + + 27 + Get + + + url + http://133.133.12.2:8080/bench4q-web/script/bench4q.table.js + + + + queryParams + + + + headers + header=Accept|value= + */*|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/homepage.jsp|; + + + + USERBEHAVIOR + http + + + 28 + Get + + + url + http://133.133.12.2:8080/bench4q-web/script/loadTestPlans.js + + + + queryParams + + + + headers + header=Accept|value= + */*|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/homepage.jsp|; + + + + USERBEHAVIOR + http + + + 29 + Get + + + url + http://133.133.12.2:8080/bench4q-web/script/scriptTable.js + + + + queryParams + + + + headers + header=Accept|value= + */*|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/homepage.jsp|; + + + + USERBEHAVIOR + http + + + 30 + Get + + + url + http://133.133.12.2:8080/bench4q-web/js/jquery-ui-1.8.21.custom.min.js + + + + queryParams + + + + headers + header=Accept|value= + */*|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/homepage.jsp|; + + + + USERBEHAVIOR + http + + + 31 + Get + + + url + http://133.133.12.2:8080/bench4q-web/img/bench4q.png + + + + queryParams + + + + headers + header=Accept|value= + image/webp,*/*;q=0.8|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/homepage.jsp|; + + + + USERBEHAVIOR + http + + + 32 + Get + + + url + http://133.133.12.2:8080/bench4q-web/js/bootstrap-dropdown.js + + + + queryParams + + + + headers + header=Accept|value= + */*|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/homepage.jsp|; + + + + USERBEHAVIOR + http + + + 36 + Get + + + url + http://133.133.12.2:8080/bench4q-web/script/home.js + + + + queryParams + + + + headers + header=Accept|value= + */*|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/homepage.jsp|; + + + + USERBEHAVIOR + http + + + -1 + 28 + 0 + + + + + 0 + Sleep + + + time + 10 + + + TIMERBEHAVIOR + timer + + + -1 + 29 + -1 + + + + + 0 + Sleep + + + time + 25 + + + TIMERBEHAVIOR + timer + + + -1 + 30 + -1 + + + + + 0 + Sleep + + + time + 1 + + + TIMERBEHAVIOR + timer + + + -1 + 31 + -1 + + + + + 0 + Sleep + + + time + 4 + + + TIMERBEHAVIOR + timer + + + -1 + 32 + -1 + + + + + 0 + Sleep + + + time + 4 + + + TIMERBEHAVIOR + timer + + + -1 + 33 + -1 + + + + + 0 + Sleep + + + time + 0 + + + TIMERBEHAVIOR + timer + + + -1 + 34 + -1 + + + + + 0 + Sleep + + + time + 1 + + + TIMERBEHAVIOR + timer + + + -1 + 35 + -1 + + + + + 0 + Sleep + + + time + 6 + + + TIMERBEHAVIOR + timer + + + -1 + 36 + -1 + + + + + 0 + Sleep + + + time + 27 + + + TIMERBEHAVIOR + timer + + + -1 + 37 + -1 + + + + + 0 + Sleep + + + time + 9 + + + TIMERBEHAVIOR + timer + + + -1 + 38 + -1 + + + + + 0 + Sleep + + + time + 1 + + + TIMERBEHAVIOR + timer + + + -1 + 39 + -1 + + + + + 0 + Sleep + + + time + 0 + + + TIMERBEHAVIOR + timer + + + -1 + 40 + -1 + + + + + 0 + Sleep + + + time + 1 + + + TIMERBEHAVIOR + timer + + + -1 + 41 + -1 + + + + + 0 + Sleep + + + time + 36 + + + TIMERBEHAVIOR + timer + + + -1 + 42 + -1 + + + + + 0 + Sleep + + + time + 5 + + + TIMERBEHAVIOR + timer + + + -1 + 43 + -1 + + + + + 0 + Sleep + + + time + 1 + + + TIMERBEHAVIOR + timer + + + -1 + 44 + -1 + + + + + 0 + Sleep + + + time + 75 + + + TIMERBEHAVIOR + timer + + + -1 + 45 + -1 + + + + + 33 + Get + + + url + http://133.133.12.2:8080/bench4q-web/img/opa-icons-blue32.png + + + + queryParams + + + + headers + header=Accept|value= + image/webp,*/*;q=0.8|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/homepage.jsp|; + + + + USERBEHAVIOR + http + + + -1 + 46 + -1 + + + + + 0 + Sleep + + + time + 30 + + + TIMERBEHAVIOR + timer + + + -1 + 47 + -1 + + + + + 34 + Get + + + url + http://133.133.12.2:8080/bench4q-web/img/opa-icons-color32.png + + + + queryParams + + + + headers + header=Accept|value= + image/webp,*/*;q=0.8|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/homepage.jsp|; + + + + USERBEHAVIOR + http + + + -1 + 48 + -1 + + + + + 0 + Sleep + + + time + 27 + + + TIMERBEHAVIOR + timer + + + -1 + 49 + -1 + + + + + 35 + Get + + + url + http://133.133.12.2:8080/bench4q-web/img/opa-icons-red32.png + + + + queryParams + + + + headers + header=Accept|value= + image/webp,*/*;q=0.8|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/homepage.jsp|; + + + + USERBEHAVIOR + http + + + -1 + 50 + -1 + + + + + 0 + Sleep + + + time + 1 + + + TIMERBEHAVIOR + timer + + + -1 + 51 + -1 + + + + + 0 + Sleep + + + time + 24 + + + TIMERBEHAVIOR + timer + + + -1 + 52 + -1 + + + + + 37 + Get + + + url + http://themes.googleusercontent.com/static/fonts/shojumaru/v2/pYVcIM206l3F7GUKEvtB3T8E0i7KZn-EPnyo3HZu7kw.woff + + + + queryParams + + + + headers + header=Accept|value= + */*|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/index.jsp|; + + + + USERBEHAVIOR + http + + + -1 + 53 + -1 + + + + + 0 + Sleep + + + time + 145 + + + TIMERBEHAVIOR + timer + + + -1 + 54 + -1 + + + + + 38 + Get + + + url + http://133.133.12.2:8080/bench4q-web/img/opa-icons-green32.png + + + + queryParams + + + + headers + header=Accept|value= + image/webp,*/*;q=0.8|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/homepage.jsp|; + + + + USERBEHAVIOR + http + + + -1 + 55 + -1 + + + + + 0 + Sleep + + + time + 1 + + + TIMERBEHAVIOR + timer + + + -1 + 56 + -1 + + + + + 39 + Get + + + url + http://133.133.12.2:8080/bench4q-web/i18n/i18n.properties + + + + queryParams + _=1389777196041 + + + headers + header=Content-Type|value=text/plain;charset=UTF-8|;header=Accept|value= + text/plain, */*; + q=0.01|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/homepage.jsp|; + + + + USERBEHAVIOR + http + + + -1 + 57 + -1 + + + + + 0 + Sleep + + + time + 8 + + + TIMERBEHAVIOR + timer + + + -1 + 58 + -1 + + + + + 40 + Get + + + url + http://133.133.12.2:8080/bench4q-web/i18n/i18n_zh.properties + + + + queryParams + _=1389777196134 + + + headers + header=Content-Type|value=text/plain;charset=UTF-8|;header=Accept|value= + text/plain, */*; + q=0.01|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/homepage.jsp|; + + + + USERBEHAVIOR + http + + + -1 + 59 + -1 + + + + + 0 + Sleep + + + time + 7 + + + TIMERBEHAVIOR + timer + + + -1 + 60 + -1 + + + + + 41 + Get + + + url + http://133.133.12.2:8080/bench4q-web/i18n/i18n_zh-CN.properties + + + + queryParams + _=1389777196150 + + + headers + header=Content-Type|value=text/plain;charset=UTF-8|;header=Accept|value= + text/plain, */*; + q=0.01|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/homepage.jsp|; + + + + USERBEHAVIOR + http + + + -1 + 61 + -1 + + + + + 0 + Sleep + + + time + 163 + + + TIMERBEHAVIOR + timer + + + -1 + 62 + -1 + + + + + 42 + Post + + + url + http://133.133.12.2:8080/bench4q-web/loadTestPlans + + + + queryParams + + + + headers + header=Accept|value= application/json, text/javascript, + */*; + q=0.01|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/homepage.jsp|; + + + + bodyparameters + + + + USERBEHAVIOR + http + + + -1 + 63 + -1 + + + + + 0 + Sleep + + + time + 1 + + + TIMERBEHAVIOR + timer + + + -1 + 64 + -1 + + + + + 43 + Post + + + url + http://133.133.12.2:8080/bench4q-web/loadScript + + + queryParams + + + + headers + header=Accept|value= application/json, text/javascript, + */*; + q=0.01|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/homepage.jsp|; + + + + bodyparameters + + + + USERBEHAVIOR + http + + + -1 + 65 + -1 + + + + + 0 + Sleep + + + time + 27 + + + TIMERBEHAVIOR + timer + + + -1 + 66 + -1 + + + + + 44 + Get + + + url + http://133.133.12.2:8080/bench4q-web/img/glyphicons-halflings-white.png + + + + queryParams + + + + headers + header=Accept|value= + image/webp,*/*;q=0.8|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/homepage.jsp|; + + + + USERBEHAVIOR + http + + + -1 + 67 + -1 + + + + + 0 + + + http + Http + + + + timer + ConstantTimer + + + + \ No newline at end of file diff --git a/Upload/test b/Upload/test new file mode 100644 index 00000000..3b1ab089 --- /dev/null +++ b/Upload/test @@ -0,0 +1,11 @@ +-- Adminer 3.7.1 MySQL dump + +SET NAMES utf8; +SET foreign_key_checks = 0; +SET time_zone = '+08:00'; +SET sql_mode = 'NO_AUTO_VALUE_ON_ZERO'; + +CREATE DATABASE `bench4q-master-yvAxaJI0` /*!40100 DEFAULT CHARACTER SET utf8 */; +USE `bench4q-master-yvAxaJI0`; + +-- 2014-01-20 15:37:24 diff --git a/pom.xml b/pom.xml index c2a500b5..20380fbe 100644 --- a/pom.xml +++ b/pom.xml @@ -32,10 +32,15 @@ spring-webmvc 3.2.4.RELEASE + + org.codehaus.jackson + jackson-core-lgpl + 1.9.13 + org.codehaus.jackson jackson-mapper-asl - 1.9.12 + 1.9.13 org.apache.hadoop @@ -62,6 +67,11 @@ spring-test 3.2.5.RELEASE + + commons-fileupload + commons-fileupload + 1.2 + diff --git a/src/main/java/org/bench4q/agent/api/TestController.java b/src/main/java/org/bench4q/agent/api/TestController.java index d8c96a75..7a859126 100644 --- a/src/main/java/org/bench4q/agent/api/TestController.java +++ b/src/main/java/org/bench4q/agent/api/TestController.java @@ -1,6 +1,8 @@ package org.bench4q.agent.api; import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.IOException; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.Date; @@ -35,7 +37,9 @@ import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.multipart.MultipartFile; @Controller @RequestMapping("/test") @@ -56,12 +60,28 @@ public class TestController { this.scenarioEngine = scenarioEngine; } + @RequestMapping(value = "/prepare/{fileName}", method = RequestMethod.POST) + @ResponseBody + public String prepare(@RequestParam MultipartFile file, + @PathVariable String fileName) { + RunScenarioResultModel result = new RunScenarioResultModel(); + try { + File receiveFile = new File("Upload" + + System.getProperty("file.separator") + fileName); + file.transferTo(receiveFile); + result.setRunId(UUID.randomUUID()); + return "It's ok!"; + } catch (IOException e) { + logger.error("/prepare/fileName", e); + return null; + } + } + @RequestMapping(value = "/run", method = RequestMethod.POST) @ResponseBody public RunScenarioResultModel run( @RequestBody RunScenarioModel runScenarioModel) throws UnknownHostException { - // Scenario scenario = extractScenario(runScenarioModel); Scenario scenario = Scenario.scenarioBuilder(runScenarioModel); UUID runId = UUID.randomUUID(); System.out.println(runScenarioModel.getPoolSize()); diff --git a/src/main/java/org/bench4q/agent/parameterization/impl/Para_Table.java b/src/main/java/org/bench4q/agent/parameterization/impl/Para_Table.java index 78e1c14a..5b8a20e0 100644 --- a/src/main/java/org/bench4q/agent/parameterization/impl/Para_Table.java +++ b/src/main/java/org/bench4q/agent/parameterization/impl/Para_Table.java @@ -1,57 +1,48 @@ package org.bench4q.agent.parameterization.impl; -import java.io.BufferedReader; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.FileReader; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.UUID; - public class Para_Table { - - public int state = 0;// 1 sequence 2 random - public class Table - { - private final String source; - - public Table() - { - source = - } - public List rows = new ArrayList(); - - public int getTime= 0; - public boolean add(TableRow r) - { - return rows.add(r); - } - public TableRow pop() - { - - } - } - - public class TableRow - { - List cells = new ArrayList(); - } - public String getTableColumnValue(UUID id, Map objCache, - String source, String sourceValue, String firstRow, String nextRow, - String splitChar, String lineChar) { - if(source == "file") - { - try { - File file = new File(sourceValue); - BufferedReader reader = new BufferedReader(new FileReader(file)); - //reader. - } catch (FileNotFoundException e) { - // TODO Auto-generated catch block - e.printStackTrace(); - } - } - } + // public int state = 0;// 1 sequence 2 random + // public class Table + // { + // private final String source; + // + // public Table() + // { + // source = + // } + // public List rows = new ArrayList(); + // + // public int getTime= 0; + // public boolean add(TableRow r) + // { + // return rows.add(r); + // } + // public TableRow pop() + // { + // + // } + // } + // + // public class TableRow + // { + // List cells = new ArrayList(); + // } + // public String getTableColumnValue(UUID id, Map objCache, + // String source, String sourceValue, String firstRow, String nextRow, + // String splitChar, String lineChar) { + // if(source == "file") + // { + // try { + // File file = new File(sourceValue); + // BufferedReader reader = new BufferedReader(new FileReader(file)); + // //reader. + // } catch (FileNotFoundException e) { + // // TODO Auto-generated catch block + // e.printStackTrace(); + // } + // + // } + // } } diff --git a/src/main/java/org/bench4q/agent/parameterization/impl/Para_Table.xml b/src/main/java/org/bench4q/agent/parameterization/impl/Para_Table.xml index b1ba35f4..15f7c4a6 100644 --- a/src/main/java/org/bench4q/agent/parameterization/impl/Para_Table.xml +++ b/src/main/java/org/bench4q/agent/parameterization/impl/Para_Table.xml @@ -1,19 +1,19 @@ - - file - input - - - - - - - sequence - random - - - - - + + file + input + + + + + + + sequence + random + + + + + diff --git a/src/main/resources/org/bench4q/agent/config/application-context.xml b/src/main/resources/org/bench4q/agent/config/application-context.xml index 909a7298..fb1938d9 100644 --- a/src/main/resources/org/bench4q/agent/config/application-context.xml +++ b/src/main/resources/org/bench4q/agent/config/application-context.xml @@ -1,10 +1,17 @@ - - - - - + + + + + + + + + + + diff --git a/src/test/java/Communication/HttpRequester.java b/src/test/java/Communication/HttpRequester.java deleted file mode 100644 index 1c72da9d..00000000 --- a/src/test/java/Communication/HttpRequester.java +++ /dev/null @@ -1,276 +0,0 @@ -package Communication; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -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 params, - Map properties) throws IOException { - return this.send(urlString, "POST", params, "", properties); - } - - public HttpResponse sendPostXml(String urlString, String contentString, - Map properties) throws IOException { - if (properties == null) { - properties = new HashMap(); - } - properties.put("Content-Type", "application/xml"); - return this.send(urlString, "POST", null, contentString, properties); - } - - public HttpResponse sendGet(String urlString, Map params, - Map properties) throws IOException { - return this.send(urlString, "GET", params, "", properties); - } - - private HttpResponse send(String urlString, String method, - Map parameters, String Content, - Map 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; - } - 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(); - } - return this.makeContent(urlString, urlConnection); - } - - private HttpResponse makeContent(String urlString, - HttpURLConnection urlConnection) { - HttpResponse httpResponser = new HttpResponse(); - try { - InputStream in = urlConnection.getInputStream(); - BufferedReader bufferedReader = new BufferedReader( - new InputStreamReader(in)); - httpResponser.contentCollection = new Vector(); - 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 (Exception 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 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 getContentCollection() { - return contentCollection; - } - - public void setContentCollection(Vector contentCollection) { - this.contentCollection = contentCollection; - } - - } -} diff --git a/src/test/java/org/bench4q/agent/test/TestControllerTest.java b/src/test/java/org/bench4q/agent/test/TestControllerTest.java deleted file mode 100644 index c22b4e26..00000000 --- a/src/test/java/org/bench4q/agent/test/TestControllerTest.java +++ /dev/null @@ -1,5 +0,0 @@ -package org.bench4q.agent.test; - -public class TestControllerTest { - -} diff --git a/src/test/java/org/bench4q/agent/test/TestWithScriptFile.java b/src/test/java/org/bench4q/agent/test/TestWithScriptFile.java index 9b97ea80..b570f85e 100644 --- a/src/test/java/org/bench4q/agent/test/TestWithScriptFile.java +++ b/src/test/java/org/bench4q/agent/test/TestWithScriptFile.java @@ -13,6 +13,8 @@ import javax.xml.bind.JAXBException; import javax.xml.bind.Unmarshaller; import org.apache.commons.io.FileUtils; +import org.bench4q.share.communication.HttpRequester; +import org.bench4q.share.communication.HttpRequester.HttpResponse; import org.bench4q.share.helper.MarshalHelper; import org.bench4q.share.models.agent.BehaviorBriefModel; import org.bench4q.share.models.agent.RunScenarioModel; @@ -22,9 +24,6 @@ import org.bench4q.share.models.agent.statistics.AgentBehaviorsBriefModel; import org.bench4q.share.models.agent.statistics.AgentPageBriefModel; import org.junit.Test; -import Communication.HttpRequester; -import Communication.HttpRequester.HttpResponse; - public class TestWithScriptFile { private HttpRequester httpRequester; private String url = "http://localhost:6565/test"; @@ -176,6 +175,18 @@ public class TestWithScriptFile { } + @Test + public void testPrepare() throws IOException { + HttpResponse httpResponse = this.getHttpRequester().postMultiFile( + url + "/prepare/" + "ready.txt", + "Scripts" + System.getProperty("file.separator") + + "forGoodRecord.xml"); + assertNotNull(httpResponse); + assertNotNull(httpResponse.getContent()); + assertEquals(200, httpResponse.getCode()); + System.out.println(httpResponse.getContent()); + } + private void pageBrief(int i) throws IOException, JAXBException { try { HttpResponse httpResponse = this.getHttpRequester().sendGet( From 2d894965fdf2dc1a074782a608dd1db60498371f Mon Sep 17 00:00:00 2001 From: coderfengyun Date: Tue, 18 Mar 2014 10:20:03 +0800 Subject: [PATCH 182/196] refactor --- .../parameterization/impl/Para_Table.java | 284 +++++++++++++++--- 1 file changed, 241 insertions(+), 43 deletions(-) diff --git a/src/main/java/org/bench4q/agent/parameterization/impl/Para_Table.java b/src/main/java/org/bench4q/agent/parameterization/impl/Para_Table.java index 5b8a20e0..78115445 100644 --- a/src/main/java/org/bench4q/agent/parameterization/impl/Para_Table.java +++ b/src/main/java/org/bench4q/agent/parameterization/impl/Para_Table.java @@ -1,48 +1,246 @@ package org.bench4q.agent.parameterization.impl; -public class Para_Table { +import java.io.BufferedReader; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStreamReader; +import java.nio.CharBuffer; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Random; +import java.util.UUID; +import java.util.concurrent.ArrayBlockingQueue; - // public int state = 0;// 1 sequence 2 random - // public class Table - // { - // private final String source; - // - // public Table() - // { - // source = - // } - // public List rows = new ArrayList(); - // - // public int getTime= 0; - // public boolean add(TableRow r) - // { - // return rows.add(r); - // } - // public TableRow pop() - // { - // - // } - // } - // - // public class TableRow - // { - // List cells = new ArrayList(); - // } - // public String getTableColumnValue(UUID id, Map objCache, - // String source, String sourceValue, String firstRow, String nextRow, - // String splitChar, String lineChar) { - // if(source == "file") - // { - // try { - // File file = new File(sourceValue); - // BufferedReader reader = new BufferedReader(new FileReader(file)); - // //reader. - // } catch (FileNotFoundException e) { - // // TODO Auto-generated catch block - // e.printStackTrace(); - // } - // - // } - // } +public class Para_Table { + public final int cacheCap = 5000;// 1 sequence 2 random + public final int cacheSize = 1000;// 1 sequence 2 random + public final int readCharSize = 10000; + + public abstract class Reader { + public final Table t; + + public Reader(Table table) { + this.t = table; + } + + public abstract TableRow nextRow(); + + } + + public class RandomReader extends Reader { + public ArrayBlockingQueue queue; + + public RandomReader(ArrayBlockingQueue queue, Table t) { + super(t); + this.queue = queue; + } + + @Override + public TableRow nextRow() { + TableRow result = null; + do { + if (queue.size() == 0) { + synchronized (queue) { + if (queue.size() == 0) { + List rows = t.readRows(); + int n = rows.size(); + Random r = new Random(); + for (int i = 0; i < n; i++) { + int next = r.nextInt(n); + TableRow tempRow = rows.get(i); + rows.set(i, rows.get(next)); + rows.set(next, tempRow); + } + queue.addAll(rows); + } + } + } + result = queue.poll(); + } while (result != null); + return result; + } + + } + + public class SequenceReader extends Reader { + public ArrayBlockingQueue queue; + + public SequenceReader(ArrayBlockingQueue queue, Table t) { + super(t); + this.queue = queue; + } + + @Override + public TableRow nextRow() { + TableRow result = null; + do { + if (queue.size() == 0) { + synchronized (queue) { + if (queue.size() == 0) { + List rows = t.readRows(); + queue.addAll(rows); + } + } + } + result = queue.poll(); + } while (result != null); + return result; + } + + } + + public abstract class Table { + String sourceValue; + int firstRow; + + public Table(String sourceValue, int firstRow) { + this.sourceValue = sourceValue; + } + + public abstract List readRows(); + + public List rows = new ArrayList(); + + public int getTime = 0; + + public boolean add(TableRow r) { + return rows.add(r); + } + } + + public class FileTable extends Table { + private BufferedReader bfr; + char splitChar; + char lineChar; + + public FileTable(String sourceValue, int firstRow, char splitChar, + char lineChar) { + super(sourceValue, firstRow); + this.splitChar = splitChar; + this.lineChar = lineChar; + + } + + private void createBFR() throws IOException { + FileInputStream fis = new FileInputStream(sourceValue); + InputStreamReader ir = new InputStreamReader(fis); + bfr = new BufferedReader(ir); + for (int i = 0; i < firstRow;) { + char readChar = (char) bfr.read(); + if (readChar == lineChar) + i++; + } + + } + + @Override + public List readRows() { + CharBuffer target = CharBuffer.allocate(readCharSize); + List result = new ArrayList(); + TableRow tempTableRow = new TableRow(); + try { + for (int i = 0; i < cacheSize;) { + char readBuff = (char) bfr.read(); + if (readBuff == -1) { + createBFR(); + break; + } else if (readBuff == this.splitChar) { + tempTableRow.AddCell(target.toString()); + target.clear(); + } else if (readBuff == this.lineChar) { + tempTableRow.AddCell(target.toString()); + result.add(tempTableRow); + target.clear(); + i++; + } + target.append(readBuff); + } + } catch (IOException ioex) { + return result; + } + if (target.length() > 0) { + tempTableRow.AddCell(target.toString()); + result.add(tempTableRow); + target.clear(); + } + return result; + } + + } + + public class StringTable extends Table { + + char splitChar; + char lineChar; + + public StringTable(String sourceValue, int firstRow, char splitChar, + char lineChar) { + super(sourceValue, firstRow); + this.splitChar = splitChar; + this.lineChar = lineChar; + } + + @Override + public List readRows() { + String readStr = this.sourceValue; + String[] tokens = readStr.split(String.valueOf(lineChar)); + List result = new ArrayList(); + for (String line : tokens) { + TableRow tempRow = new TableRow(); + String[] columns = line.split(String.valueOf(splitChar)); + for (String column : columns) { + tempRow.AddCell(column); + } + result.add(tempRow); + } + return result; + } + + } + + public class TableRow { + public List cells = new ArrayList(); + + public void AddCell(String s) { + cells.add(s); + } + } + + public String getTableColumnValue(UUID id, Map objCache, + String source, String sourceValue, String firstRow, String nextRow, + String splitChar, String lineChar, String column) { + int fRow = Integer.parseInt(firstRow); + char sChar = splitChar.charAt(0); + char lChar = lineChar.charAt(0); + int col = Integer.parseInt(column); + TableRow resultRow = null; + Table table = null; + Reader reader = null; + if (objCache.containsKey(sourceValue) == true) { + resultRow = (TableRow) objCache.get(sourceValue); + return resultRow.cells.get(col); + } + if (source.equals("file")) { + table = new FileTable(sourceValue, fRow, sChar, lChar); + } else if (source.equals("input")) { + table = new StringTable(sourceValue, fRow, sChar, lChar); + } + + if (nextRow.equals("random")) { + ArrayBlockingQueue queue = new ArrayBlockingQueue( + cacheCap); + reader = new RandomReader(queue, table); + } else if (nextRow.equals("sequence")) { + + ArrayBlockingQueue queue = new ArrayBlockingQueue( + cacheCap); + reader = new SequenceReader(queue, table); + } + + resultRow = reader.nextRow(); + objCache.put(sourceValue, resultRow); + return resultRow.cells.get(col); + } } From 1576076d757673f5a6fc07a2f6af10da65962d8e Mon Sep 17 00:00:00 2001 From: coderfengyun Date: Tue, 18 Mar 2014 14:13:45 +0800 Subject: [PATCH 183/196] refactor and split the run into two mehtods named submit and runWith --- .../org/bench4q/agent/api/TestController.java | 4 ++- .../agent/scenario/ScenarioContext.java | 11 +++++-- .../agent/scenario/ScenarioEngine.java | 31 ++++++++++--------- .../agent/test/TestWithScriptFile.java | 2 +- .../test/scenario/Test_ScenarioContext.java | 27 ++++++++++++++++ 5 files changed, 56 insertions(+), 19 deletions(-) create mode 100644 src/test/java/org/bench4q/agent/test/scenario/Test_ScenarioContext.java diff --git a/src/main/java/org/bench4q/agent/api/TestController.java b/src/main/java/org/bench4q/agent/api/TestController.java index 3eaae374..6850905d 100644 --- a/src/main/java/org/bench4q/agent/api/TestController.java +++ b/src/main/java/org/bench4q/agent/api/TestController.java @@ -87,8 +87,10 @@ public class TestController { UUID runId = UUID.randomUUID(); System.out.println(runScenarioModel.getPoolSize()); this.getLogger().info(marshalRunScenarioModel(runScenarioModel)); - this.getScenarioEngine().runScenario(runId, scenario, + this.getScenarioEngine().submitScenario(runId, scenario, runScenarioModel.getPoolSize()); + + this.getScenarioEngine().runWith(runId); RunScenarioResultModel runScenarioResultModel = new RunScenarioResultModel(); runScenarioResultModel.setRunId(runId); return runScenarioResultModel; diff --git a/src/main/java/org/bench4q/agent/scenario/ScenarioContext.java b/src/main/java/org/bench4q/agent/scenario/ScenarioContext.java index 2d110114..f3454810 100644 --- a/src/main/java/org/bench4q/agent/scenario/ScenarioContext.java +++ b/src/main/java/org/bench4q/agent/scenario/ScenarioContext.java @@ -2,12 +2,16 @@ package org.bench4q.agent.scenario; import java.util.Date; import java.util.UUID; +import java.util.concurrent.SynchronousQueue; import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.ThreadPoolExecutor.DiscardPolicy; import org.bench4q.agent.datacollector.DataCollector; import org.bench4q.agent.datacollector.impl.ScenarioResultCollector; public class ScenarioContext { + private static final long keepAliveTime = 10; private Date startDate; private Date endDate; private ThreadPoolExecutor executor; @@ -64,12 +68,15 @@ public class ScenarioContext { } public static ScenarioContext buildScenarioContext(UUID testId, - final Scenario scenario, int poolSize, ThreadPoolExecutor executor) { + final Scenario scenario, int poolSize) { ScenarioContext scenarioContext = new ScenarioContext(); + final SynchronousQueue workQueue = new SynchronousQueue(); + ThreadPoolExecutor executor = new ThreadPoolExecutor(poolSize, + poolSize, keepAliveTime, TimeUnit.MINUTES, workQueue, + new DiscardPolicy()); scenarioContext.setScenario(scenario); scenarioContext.setStartDate(new Date(System.currentTimeMillis())); scenarioContext.setExecutorService(executor); - // TODO:remove this direct dependency scenarioContext.setDataStatistics(new ScenarioResultCollector(testId)); return scenarioContext; } diff --git a/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java b/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java index 4cba7820..ad3979e4 100644 --- a/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java +++ b/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java @@ -5,11 +5,6 @@ import java.util.Map; import java.util.UUID; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; -import java.util.concurrent.SynchronousQueue; -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.parameterization.impl.InstanceControler; import org.bench4q.agent.storage.StorageHelper; @@ -18,7 +13,6 @@ import org.springframework.stereotype.Component; @Component public class ScenarioEngine { - private static final long keepAliveTime = 10; private Map runningTests; private StorageHelper storageHelper; private Logger logger; @@ -54,24 +48,31 @@ public class ScenarioEngine { this.runningTests = runningTests; } - public void runScenario(UUID runId, final Scenario scenario, int poolSize) { + public void submitScenario(UUID runId, final Scenario scenario, int poolSize) { try { - final SynchronousQueue workQueue = new SynchronousQueue(); - ThreadPoolExecutor executor = new ThreadPoolExecutor(poolSize, - poolSize, keepAliveTime, TimeUnit.MINUTES, workQueue, - new DiscardPolicy()); final ScenarioContext scenarioContext = ScenarioContext - .buildScenarioContext(runId, scenario, poolSize, executor); - System.out.println("when run, classId:" + executor.toString()); + .buildScenarioContext(runId, scenario, poolSize); this.getRunningTests().put(runId, scenarioContext); + System.out.println(poolSize); - executeTasks(scenarioContext); + } catch (Exception e) { e.printStackTrace(); } } - private void executeTasks(final ScenarioContext scenarioContext) { + public void runWith(UUID runId) { + if (!this.getRunningTests().containsKey(runId)) { + return; + } + final ScenarioContext context = this.getRunningTests().get(runId); + runWith(context); + } + + private void runWith(final ScenarioContext scenarioContext) { + if (scenarioContext == null) { + return; + } ExecutorService taskMaker = Executors.newSingleThreadExecutor(); taskMaker.execute(new Runnable() { diff --git a/src/test/java/org/bench4q/agent/test/TestWithScriptFile.java b/src/test/java/org/bench4q/agent/test/TestWithScriptFile.java index e4043e9e..c61cb343 100644 --- a/src/test/java/org/bench4q/agent/test/TestWithScriptFile.java +++ b/src/test/java/org/bench4q/agent/test/TestWithScriptFile.java @@ -170,7 +170,7 @@ public class TestWithScriptFile { } catch (Exception e) { e.printStackTrace(); } finally { - // this.stopTest(); + this.stopTest(); } } diff --git a/src/test/java/org/bench4q/agent/test/scenario/Test_ScenarioContext.java b/src/test/java/org/bench4q/agent/test/scenario/Test_ScenarioContext.java new file mode 100644 index 00000000..c2f4f838 --- /dev/null +++ b/src/test/java/org/bench4q/agent/test/scenario/Test_ScenarioContext.java @@ -0,0 +1,27 @@ +package org.bench4q.agent.test.scenario; + +import static org.junit.Assert.*; + +import java.util.UUID; +import java.util.concurrent.TimeUnit; + +import org.bench4q.agent.scenario.Scenario; +import org.bench4q.agent.scenario.ScenarioContext; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.test.context.ContextConfiguration; +import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; + +@RunWith(SpringJUnit4ClassRunner.class) +@ContextConfiguration(locations = { "classpath*:/org/bench4q/agent/config/application-context.xml" }) +public class Test_ScenarioContext { + + @Test + public void test() { + ScenarioContext context = ScenarioContext.buildScenarioContext( + UUID.randomUUID(), new Scenario(), 20); + assertEquals(10, + context.getExecutor().getKeepAliveTime(TimeUnit.MINUTES)); + assertEquals(20, context.getExecutor().getMaximumPoolSize()); + } +} From 38b805153cc857332203d1d662d92ca73d0fbb1c Mon Sep 17 00:00:00 2001 From: coderfengyun Date: Tue, 18 Mar 2014 15:44:03 +0800 Subject: [PATCH 184/196] add ways to submit paramFiles to agent --- Upload/ready | 2076 ----------------- Upload/test | 11 - .../org/bench4q/agent/api/TestController.java | 28 +- .../agent/config/application-context.xml | 1 + .../agent/test/TestWithScriptFile.java | 15 +- 5 files changed, 32 insertions(+), 2099 deletions(-) delete mode 100644 Upload/ready delete mode 100644 Upload/test diff --git a/Upload/ready b/Upload/ready deleted file mode 100644 index aeb6083b..00000000 --- a/Upload/ready +++ /dev/null @@ -1,2076 +0,0 @@ - - - - - - - - - 0 - Get - - - url - http://133.133.12.2:8080/bench4q-web/homepage.jsp - - - - queryParams - - - - headers - header=Accept|value= - text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8|; - - - - USERBEHAVIOR - http - - - -1 - 0 - -1 - - - - - 0 - Sleep - - - time - 15 - - - TIMERBEHAVIOR - timer - - - -1 - 1 - -1 - - - - - 1 - Get - - - url - http://133.133.12.2:8080/bench4q-web/index.jsp - - - queryParams - - - - headers - header=Accept|value= - text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8|; - - - - USERBEHAVIOR - http - - - 4 - 2 - -1 - - - - - 0 - Sleep - - - time - 133 - - - TIMERBEHAVIOR - timer - - - -1 - 3 - -1 - - - - - 2 - Get - - - url - http://133.133.12.2:8080/bench4q-web/css/bootstrap-cerulean.css - - - - queryParams - - - - headers - header=Accept|value= - text/css,*/*;q=0.1|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/index.jsp|; - - - - USERBEHAVIOR - http - - - 3 - Get - - - url - http://133.133.12.2:8080/bench4q-web/script/login.js - - - - queryParams - - - - headers - header=Accept|value= - */*|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/index.jsp|; - - - - USERBEHAVIOR - http - - - 4 - Get - - - url - http://133.133.12.2:8080/bench4q-web/js/jquery-1.7.2.min.js - - - - queryParams - - - - headers - header=Accept|value= - */*|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/index.jsp|; - - - - USERBEHAVIOR - http - - - 5 - Get - - - url - http://133.133.12.2:8080/bench4q-web/js/jquery.i18n.properties-1.0.9.js - - - - queryParams - - - - headers - header=Accept|value= - */*|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/index.jsp|; - - - - USERBEHAVIOR - http - - - 6 - Get - - - url - http://133.133.12.2:8080/bench4q-web/css/charisma-app.css - - - - queryParams - - - - headers - header=Accept|value= - text/css,*/*;q=0.1|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/index.jsp|; - - - - USERBEHAVIOR - http - - - -1 - 4 - 2 - - - - - 0 - Sleep - - - time - 1 - - - TIMERBEHAVIOR - timer - - - -1 - 5 - -1 - - - - - 0 - Sleep - - - time - 72 - - - TIMERBEHAVIOR - timer - - - -1 - 6 - -1 - - - - - 0 - Sleep - - - time - 24 - - - TIMERBEHAVIOR - timer - - - -1 - 7 - -1 - - - - - 0 - Sleep - - - time - 1 - - - TIMERBEHAVIOR - timer - - - -1 - 8 - -1 - - - - - 0 - Sleep - - - time - 211 - - - TIMERBEHAVIOR - timer - - - -1 - 9 - -1 - - - - - 7 - Get - - - url - http://fonts.googleapis.com/css - - - queryParams - family=Karla|Ubuntu - - - headers - header=Accept|value= - text/css,*/*;q=0.1|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/index.jsp|; - - - - USERBEHAVIOR - http - - - -1 - 10 - -1 - - - - - 0 - Sleep - - - time - 3 - - - TIMERBEHAVIOR - timer - - - -1 - 11 - -1 - - - - - 8 - Get - - - url - http://fonts.googleapis.com/css - - - queryParams - family=Shojumaru - - - headers - header=Accept|value= - text/css,*/*;q=0.1|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/index.jsp|; - - - - USERBEHAVIOR - http - - - -1 - 12 - -1 - - - - - 0 - Sleep - - - time - 82 - - - TIMERBEHAVIOR - timer - - - -1 - 13 - -1 - - - - - 9 - Get - - - url - http://133.133.12.2:8080/bench4q-web/img/glyphicons-halflings.png - - - - queryParams - - - - headers - header=Accept|value= - image/webp,*/*;q=0.8|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/index.jsp|; - - - - USERBEHAVIOR - http - - - -1 - 14 - -1 - - - - - 0 - Sleep - - - time - 2 - - - TIMERBEHAVIOR - timer - - - -1 - 15 - -1 - - - - - 10 - Get - - - url - http://133.133.12.2:8080/bench4q-web/i18n/i18n.properties - - - - queryParams - _=1389777175541 - - - headers - header=Content-Type|value=text/plain;charset=UTF-8|;header=Accept|value= - text/plain, */*; - q=0.01|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/index.jsp|; - - - - USERBEHAVIOR - http - - - -1 - 16 - -1 - - - - - 0 - Sleep - - - time - 10 - - - TIMERBEHAVIOR - timer - - - -1 - 17 - -1 - - - - - 11 - Get - - - url - http://133.133.12.2:8080/bench4q-web/i18n/i18n_zh.properties - - - - queryParams - _=1389777175572 - - - headers - header=Content-Type|value=text/plain;charset=UTF-8|;header=Accept|value= - text/plain, */*; - q=0.01|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/index.jsp|; - - - - USERBEHAVIOR - http - - - -1 - 18 - -1 - - - - - 0 - Sleep - - - time - 8 - - - TIMERBEHAVIOR - timer - - - -1 - 19 - -1 - - - - - 12 - Get - - - url - http://133.133.12.2:8080/bench4q-web/i18n/i18n_zh-CN.properties - - - - queryParams - _=1389777175587 - - - headers - header=Content-Type|value=text/plain;charset=UTF-8|;header=Accept|value= - text/plain, */*; - q=0.01|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/index.jsp|; - - - - USERBEHAVIOR - http - - - -1 - 20 - -1 - - - - - 0 - Sleep - - - time - 52 - - - TIMERBEHAVIOR - timer - - - -1 - 21 - -1 - - - - - 13 - Get - - - url - http://themes.googleusercontent.com/static/fonts/karla/v3/azR40LUJrT4HaWK28zHmVA.woff - - - - queryParams - - - - headers - header=Accept|value= - */*|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/index.jsp|; - - - - USERBEHAVIOR - http - - - -1 - 22 - -1 - - - - - 0 - Sleep - - - time - 16442 - - - TIMERBEHAVIOR - timer - - - -1 - 23 - -1 - - - - - 14 - Get - - - url - http://themes.googleusercontent.com/static/fonts/ubuntu/v5/_xyN3apAT_yRRDeqB3sPRg.woff - - - - queryParams - - - - headers - header=Accept|value= - */*|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/index.jsp|; - - - - USERBEHAVIOR - http - - - -1 - 24 - -1 - - - - - - - - - 0 - Sleep - - - time - 9 - - - TIMERBEHAVIOR - timer - - - 3 - 25 - -1 - - - - - 15 - Get - - - url - http://133.133.12.2:8080/bench4q-web/homepage.jsp - - - - queryParams - - - - headers - header=Accept|value= - text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/index.jsp|; - - - - USERBEHAVIOR - http - - - -1 - 26 - -1 - - - - - 0 - Sleep - - - time - 25 - - - TIMERBEHAVIOR - timer - - - -1 - 27 - -1 - - - - - 16 - Get - - - url - http://133.133.12.2:8080/bench4q-web/css/bootstrap-responsive.css - - - - queryParams - - - - headers - header=Accept|value= - text/css,*/*;q=0.1|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/homepage.jsp|; - - - - USERBEHAVIOR - http - - - 17 - Get - - - url - http://133.133.12.2:8080/bench4q-web/css/noty_theme_default.css - - - - queryParams - - - - headers - header=Accept|value= - text/css,*/*;q=0.1|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/homepage.jsp|; - - - - USERBEHAVIOR - http - - - 18 - Get - - - url - http://133.133.12.2:8080/bench4q-web/js/jquery-1.8.2.min.js - - - - queryParams - - - - headers - header=Accept|value= - */*|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/homepage.jsp|; - - - - USERBEHAVIOR - http - - - 19 - Get - - - url - http://133.133.12.2:8080/bench4q-web/bench4q-css/bench4q.css - - - - queryParams - - - - headers - header=Accept|value= - text/css,*/*;q=0.1|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/homepage.jsp|; - - - - USERBEHAVIOR - http - - - 20 - Get - - - url - http://133.133.12.2:8080/bench4q-web/css/jquery-ui-1.8.21.custom.css - - - - queryParams - - - - headers - header=Accept|value= - text/css,*/*;q=0.1|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/homepage.jsp|; - - - - USERBEHAVIOR - http - - - 21 - Get - - - url - http://133.133.12.2:8080/bench4q-web/css/opa-icons.css - - - - queryParams - - - - headers - header=Accept|value= - text/css,*/*;q=0.1|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/homepage.jsp|; - - - - USERBEHAVIOR - http - - - 22 - Get - - - url - http://133.133.12.2:8080/bench4q-web/css/colorbox.css - - - - queryParams - - - - headers - header=Accept|value= - text/css,*/*;q=0.1|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/homepage.jsp|; - - - - USERBEHAVIOR - http - - - 23 - Get - - - url - http://133.133.12.2:8080/bench4q-web/js/jquery.cookie.js - - - - queryParams - - - - headers - header=Accept|value= - */*|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/homepage.jsp|; - - - - USERBEHAVIOR - http - - - 24 - Get - - - url - http://133.133.12.2:8080/bench4q-web/js/jquery.dataTables.min.js - - - - queryParams - - - - headers - header=Accept|value= - */*|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/homepage.jsp|; - - - - USERBEHAVIOR - http - - - 25 - Get - - - url - http://133.133.12.2:8080/bench4q-web/js/theme.js - - - queryParams - - - - headers - header=Accept|value= - */*|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/homepage.jsp|; - - - - USERBEHAVIOR - http - - - 26 - Get - - - url - http://133.133.12.2:8080/bench4q-web/script/base.js - - - - queryParams - - - - headers - header=Accept|value= - */*|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/homepage.jsp|; - - - - USERBEHAVIOR - http - - - 27 - Get - - - url - http://133.133.12.2:8080/bench4q-web/script/bench4q.table.js - - - - queryParams - - - - headers - header=Accept|value= - */*|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/homepage.jsp|; - - - - USERBEHAVIOR - http - - - 28 - Get - - - url - http://133.133.12.2:8080/bench4q-web/script/loadTestPlans.js - - - - queryParams - - - - headers - header=Accept|value= - */*|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/homepage.jsp|; - - - - USERBEHAVIOR - http - - - 29 - Get - - - url - http://133.133.12.2:8080/bench4q-web/script/scriptTable.js - - - - queryParams - - - - headers - header=Accept|value= - */*|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/homepage.jsp|; - - - - USERBEHAVIOR - http - - - 30 - Get - - - url - http://133.133.12.2:8080/bench4q-web/js/jquery-ui-1.8.21.custom.min.js - - - - queryParams - - - - headers - header=Accept|value= - */*|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/homepage.jsp|; - - - - USERBEHAVIOR - http - - - 31 - Get - - - url - http://133.133.12.2:8080/bench4q-web/img/bench4q.png - - - - queryParams - - - - headers - header=Accept|value= - image/webp,*/*;q=0.8|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/homepage.jsp|; - - - - USERBEHAVIOR - http - - - 32 - Get - - - url - http://133.133.12.2:8080/bench4q-web/js/bootstrap-dropdown.js - - - - queryParams - - - - headers - header=Accept|value= - */*|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/homepage.jsp|; - - - - USERBEHAVIOR - http - - - 36 - Get - - - url - http://133.133.12.2:8080/bench4q-web/script/home.js - - - - queryParams - - - - headers - header=Accept|value= - */*|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/homepage.jsp|; - - - - USERBEHAVIOR - http - - - -1 - 28 - 0 - - - - - 0 - Sleep - - - time - 10 - - - TIMERBEHAVIOR - timer - - - -1 - 29 - -1 - - - - - 0 - Sleep - - - time - 25 - - - TIMERBEHAVIOR - timer - - - -1 - 30 - -1 - - - - - 0 - Sleep - - - time - 1 - - - TIMERBEHAVIOR - timer - - - -1 - 31 - -1 - - - - - 0 - Sleep - - - time - 4 - - - TIMERBEHAVIOR - timer - - - -1 - 32 - -1 - - - - - 0 - Sleep - - - time - 4 - - - TIMERBEHAVIOR - timer - - - -1 - 33 - -1 - - - - - 0 - Sleep - - - time - 0 - - - TIMERBEHAVIOR - timer - - - -1 - 34 - -1 - - - - - 0 - Sleep - - - time - 1 - - - TIMERBEHAVIOR - timer - - - -1 - 35 - -1 - - - - - 0 - Sleep - - - time - 6 - - - TIMERBEHAVIOR - timer - - - -1 - 36 - -1 - - - - - 0 - Sleep - - - time - 27 - - - TIMERBEHAVIOR - timer - - - -1 - 37 - -1 - - - - - 0 - Sleep - - - time - 9 - - - TIMERBEHAVIOR - timer - - - -1 - 38 - -1 - - - - - 0 - Sleep - - - time - 1 - - - TIMERBEHAVIOR - timer - - - -1 - 39 - -1 - - - - - 0 - Sleep - - - time - 0 - - - TIMERBEHAVIOR - timer - - - -1 - 40 - -1 - - - - - 0 - Sleep - - - time - 1 - - - TIMERBEHAVIOR - timer - - - -1 - 41 - -1 - - - - - 0 - Sleep - - - time - 36 - - - TIMERBEHAVIOR - timer - - - -1 - 42 - -1 - - - - - 0 - Sleep - - - time - 5 - - - TIMERBEHAVIOR - timer - - - -1 - 43 - -1 - - - - - 0 - Sleep - - - time - 1 - - - TIMERBEHAVIOR - timer - - - -1 - 44 - -1 - - - - - 0 - Sleep - - - time - 75 - - - TIMERBEHAVIOR - timer - - - -1 - 45 - -1 - - - - - 33 - Get - - - url - http://133.133.12.2:8080/bench4q-web/img/opa-icons-blue32.png - - - - queryParams - - - - headers - header=Accept|value= - image/webp,*/*;q=0.8|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/homepage.jsp|; - - - - USERBEHAVIOR - http - - - -1 - 46 - -1 - - - - - 0 - Sleep - - - time - 30 - - - TIMERBEHAVIOR - timer - - - -1 - 47 - -1 - - - - - 34 - Get - - - url - http://133.133.12.2:8080/bench4q-web/img/opa-icons-color32.png - - - - queryParams - - - - headers - header=Accept|value= - image/webp,*/*;q=0.8|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/homepage.jsp|; - - - - USERBEHAVIOR - http - - - -1 - 48 - -1 - - - - - 0 - Sleep - - - time - 27 - - - TIMERBEHAVIOR - timer - - - -1 - 49 - -1 - - - - - 35 - Get - - - url - http://133.133.12.2:8080/bench4q-web/img/opa-icons-red32.png - - - - queryParams - - - - headers - header=Accept|value= - image/webp,*/*;q=0.8|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/homepage.jsp|; - - - - USERBEHAVIOR - http - - - -1 - 50 - -1 - - - - - 0 - Sleep - - - time - 1 - - - TIMERBEHAVIOR - timer - - - -1 - 51 - -1 - - - - - 0 - Sleep - - - time - 24 - - - TIMERBEHAVIOR - timer - - - -1 - 52 - -1 - - - - - 37 - Get - - - url - http://themes.googleusercontent.com/static/fonts/shojumaru/v2/pYVcIM206l3F7GUKEvtB3T8E0i7KZn-EPnyo3HZu7kw.woff - - - - queryParams - - - - headers - header=Accept|value= - */*|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/index.jsp|; - - - - USERBEHAVIOR - http - - - -1 - 53 - -1 - - - - - 0 - Sleep - - - time - 145 - - - TIMERBEHAVIOR - timer - - - -1 - 54 - -1 - - - - - 38 - Get - - - url - http://133.133.12.2:8080/bench4q-web/img/opa-icons-green32.png - - - - queryParams - - - - headers - header=Accept|value= - image/webp,*/*;q=0.8|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/homepage.jsp|; - - - - USERBEHAVIOR - http - - - -1 - 55 - -1 - - - - - 0 - Sleep - - - time - 1 - - - TIMERBEHAVIOR - timer - - - -1 - 56 - -1 - - - - - 39 - Get - - - url - http://133.133.12.2:8080/bench4q-web/i18n/i18n.properties - - - - queryParams - _=1389777196041 - - - headers - header=Content-Type|value=text/plain;charset=UTF-8|;header=Accept|value= - text/plain, */*; - q=0.01|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/homepage.jsp|; - - - - USERBEHAVIOR - http - - - -1 - 57 - -1 - - - - - 0 - Sleep - - - time - 8 - - - TIMERBEHAVIOR - timer - - - -1 - 58 - -1 - - - - - 40 - Get - - - url - http://133.133.12.2:8080/bench4q-web/i18n/i18n_zh.properties - - - - queryParams - _=1389777196134 - - - headers - header=Content-Type|value=text/plain;charset=UTF-8|;header=Accept|value= - text/plain, */*; - q=0.01|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/homepage.jsp|; - - - - USERBEHAVIOR - http - - - -1 - 59 - -1 - - - - - 0 - Sleep - - - time - 7 - - - TIMERBEHAVIOR - timer - - - -1 - 60 - -1 - - - - - 41 - Get - - - url - http://133.133.12.2:8080/bench4q-web/i18n/i18n_zh-CN.properties - - - - queryParams - _=1389777196150 - - - headers - header=Content-Type|value=text/plain;charset=UTF-8|;header=Accept|value= - text/plain, */*; - q=0.01|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/homepage.jsp|; - - - - USERBEHAVIOR - http - - - -1 - 61 - -1 - - - - - 0 - Sleep - - - time - 163 - - - TIMERBEHAVIOR - timer - - - -1 - 62 - -1 - - - - - 42 - Post - - - url - http://133.133.12.2:8080/bench4q-web/loadTestPlans - - - - queryParams - - - - headers - header=Accept|value= application/json, text/javascript, - */*; - q=0.01|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/homepage.jsp|; - - - - bodyparameters - - - - USERBEHAVIOR - http - - - -1 - 63 - -1 - - - - - 0 - Sleep - - - time - 1 - - - TIMERBEHAVIOR - timer - - - -1 - 64 - -1 - - - - - 43 - Post - - - url - http://133.133.12.2:8080/bench4q-web/loadScript - - - queryParams - - - - headers - header=Accept|value= application/json, text/javascript, - */*; - q=0.01|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/homepage.jsp|; - - - - bodyparameters - - - - USERBEHAVIOR - http - - - -1 - 65 - -1 - - - - - 0 - Sleep - - - time - 27 - - - TIMERBEHAVIOR - timer - - - -1 - 66 - -1 - - - - - 44 - Get - - - url - http://133.133.12.2:8080/bench4q-web/img/glyphicons-halflings-white.png - - - - queryParams - - - - headers - header=Accept|value= - image/webp,*/*;q=0.8|;header=Referer|value=http://133.133.12.2:8080/bench4q-web/homepage.jsp|; - - - - USERBEHAVIOR - http - - - -1 - 67 - -1 - - - - - 0 - - - http - Http - - - - timer - ConstantTimer - - - - \ No newline at end of file diff --git a/Upload/test b/Upload/test deleted file mode 100644 index 3b1ab089..00000000 --- a/Upload/test +++ /dev/null @@ -1,11 +0,0 @@ --- Adminer 3.7.1 MySQL dump - -SET NAMES utf8; -SET foreign_key_checks = 0; -SET time_zone = '+08:00'; -SET sql_mode = 'NO_AUTO_VALUE_ON_ZERO'; - -CREATE DATABASE `bench4q-master-yvAxaJI0` /*!40100 DEFAULT CHARACTER SET utf8 */; -USE `bench4q-master-yvAxaJI0`; - --- 2014-01-20 15:37:24 diff --git a/src/main/java/org/bench4q/agent/api/TestController.java b/src/main/java/org/bench4q/agent/api/TestController.java index 6850905d..701c4df4 100644 --- a/src/main/java/org/bench4q/agent/api/TestController.java +++ b/src/main/java/org/bench4q/agent/api/TestController.java @@ -45,6 +45,8 @@ import org.springframework.web.multipart.MultipartFile; @Controller @RequestMapping("/test") public class TestController { + private static final String FILE_SEPARATOR = System + .getProperty("file.separator"); private ScenarioEngine scenarioEngine; private Logger logger = Logger.getLogger(TestController.class); @@ -61,16 +63,18 @@ public class TestController { this.scenarioEngine = scenarioEngine; } - @RequestMapping(value = "/prepare/{fileName}", method = RequestMethod.POST) + @RequestMapping(value = "/submit", method = RequestMethod.POST) @ResponseBody - public String prepare(@RequestParam("file") MultipartFile file, - @PathVariable String fileName) { + public String submitParams( + @RequestParam("files[]") List files) { RunScenarioResultModel result = new RunScenarioResultModel(); try { - File receiveFile = new File("Upload" - + System.getProperty("file.separator") + fileName); - file.transferTo(receiveFile); - result.setRunId(UUID.randomUUID()); + UUID runId = UUID.randomUUID(); + for (MultipartFile file : files) { + file.transferTo(new File(guardDirExists(runId) + + file.getOriginalFilename())); + } + result.setRunId(runId); return MarshalHelper.tryMarshal(result); } catch (IOException e) { logger.error("/prepare/fileName", e); @@ -78,6 +82,16 @@ public class TestController { } } + private String guardDirExists(UUID runId) { + String dirPath = "ScenarioParameters" + FILE_SEPARATOR + + runId.toString() + FILE_SEPARATOR; + File dirFile = new File(dirPath); + if (!dirFile.exists()) { + dirFile.mkdirs(); + } + return dirPath; + } + @RequestMapping(value = "/run", method = RequestMethod.POST) @ResponseBody public RunScenarioResultModel run( diff --git a/src/main/resources/org/bench4q/agent/config/application-context.xml b/src/main/resources/org/bench4q/agent/config/application-context.xml index fb1938d9..48c14bb0 100644 --- a/src/main/resources/org/bench4q/agent/config/application-context.xml +++ b/src/main/resources/org/bench4q/agent/config/application-context.xml @@ -12,6 +12,7 @@ + diff --git a/src/test/java/org/bench4q/agent/test/TestWithScriptFile.java b/src/test/java/org/bench4q/agent/test/TestWithScriptFile.java index c61cb343..115e4f9e 100644 --- a/src/test/java/org/bench4q/agent/test/TestWithScriptFile.java +++ b/src/test/java/org/bench4q/agent/test/TestWithScriptFile.java @@ -4,6 +4,8 @@ import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; +import java.util.ArrayList; +import java.util.List; import java.util.UUID; import static org.junit.Assert.*; @@ -176,11 +178,14 @@ public class TestWithScriptFile { } @Test - public void testPrepare() throws IOException { - HttpResponse httpResponse = this.getHttpRequester().postMultiFile( - url + "/prepare/" + "ready.txt", - "Scripts" + System.getProperty("file.separator") - + "forGoodRecord.xml"); + public void testSubmitParams() throws IOException { + List files = new ArrayList(); + files.add(new File("Scripts" + System.getProperty("file.separator") + + "forGoodRecord.xml")); + files.add(new File("Scripts" + System.getProperty("file.separator") + + "testJD.xml")); + HttpResponse httpResponse = this.getHttpRequester().postFiles( + url + "/submit", "files[]", files); assertNotNull(httpResponse); assertNotNull(httpResponse.getContent()); assertEquals(200, httpResponse.getCode()); From dfcc838a966560d2d8294b44e6e81937daebc2cf Mon Sep 17 00:00:00 2001 From: coderfengyun Date: Tue, 18 Mar 2014 15:55:05 +0800 Subject: [PATCH 185/196] modify agent's api --- src/main/java/org/bench4q/agent/api/TestController.java | 2 +- src/test/java/org/bench4q/agent/test/TestWithScriptFile.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/main/java/org/bench4q/agent/api/TestController.java b/src/main/java/org/bench4q/agent/api/TestController.java index 701c4df4..1ab36ec1 100644 --- a/src/main/java/org/bench4q/agent/api/TestController.java +++ b/src/main/java/org/bench4q/agent/api/TestController.java @@ -92,7 +92,7 @@ public class TestController { return dirPath; } - @RequestMapping(value = "/run", method = RequestMethod.POST) + @RequestMapping(value = "/runWithoutParams", method = RequestMethod.POST) @ResponseBody public RunScenarioResultModel run( @RequestBody RunScenarioModel runScenarioModel) diff --git a/src/test/java/org/bench4q/agent/test/TestWithScriptFile.java b/src/test/java/org/bench4q/agent/test/TestWithScriptFile.java index 115e4f9e..0dd2ba0d 100644 --- a/src/test/java/org/bench4q/agent/test/TestWithScriptFile.java +++ b/src/test/java/org/bench4q/agent/test/TestWithScriptFile.java @@ -83,7 +83,7 @@ public class TestWithScriptFile { runScenarioModel.setPoolSize(load); HttpResponse httpResponse = this.getHttpRequester().sendPostXml( - this.url + "/run", + this.url + "/runWithoutParams", marshalRunScenarioModel(runScenarioModel), null); RunScenarioResultModel resultModel = (RunScenarioResultModel) MarshalHelper .unmarshal(RunScenarioResultModel.class, From 1dcfc626b0ff1c9c39b6af938499a910c675be9b Mon Sep 17 00:00:00 2001 From: coderfengyun Date: Tue, 18 Mar 2014 17:04:07 +0800 Subject: [PATCH 186/196] add apis for submit params and scenario and then run with the handle runId --- .../org/bench4q/agent/api/TestController.java | 82 ++--- .../ParameterFileCollector.java | 33 ++ .../org/bench4q/agent/scenario/Scenario.java | 343 +++++++++--------- .../agent/scenario/ScenarioEngine.java | 12 +- .../agent/test/TestWithScriptFile.java | 54 ++- 5 files changed, 298 insertions(+), 226 deletions(-) create mode 100644 src/main/java/org/bench4q/agent/parameterization/ParameterFileCollector.java diff --git a/src/main/java/org/bench4q/agent/api/TestController.java b/src/main/java/org/bench4q/agent/api/TestController.java index 1ab36ec1..2357f52e 100644 --- a/src/main/java/org/bench4q/agent/api/TestController.java +++ b/src/main/java/org/bench4q/agent/api/TestController.java @@ -1,8 +1,5 @@ package org.bench4q.agent.api; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.IOException; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.Date; @@ -10,12 +7,9 @@ import java.util.List; import java.util.Map; import java.util.UUID; -import javax.xml.bind.JAXBContext; -import javax.xml.bind.JAXBException; -import javax.xml.bind.Marshaller; - import org.apache.log4j.Logger; import org.bench4q.agent.datacollector.impl.BehaviorStatusCodeResult; +import org.bench4q.agent.parameterization.ParameterFileCollector; import org.bench4q.agent.scenario.Scenario; import org.bench4q.agent.scenario.ScenarioContext; import org.bench4q.agent.scenario.ScenarioEngine; @@ -45,9 +39,8 @@ import org.springframework.web.multipart.MultipartFile; @Controller @RequestMapping("/test") public class TestController { - private static final String FILE_SEPARATOR = System - .getProperty("file.separator"); private ScenarioEngine scenarioEngine; + private ParameterFileCollector paramFileCollector; private Logger logger = Logger.getLogger(TestController.class); private Logger getLogger() { @@ -63,33 +56,48 @@ public class TestController { this.scenarioEngine = scenarioEngine; } + private ParameterFileCollector getParamFileCollector() { + return paramFileCollector; + } + + @Autowired + private void setParamFileCollector(ParameterFileCollector paramFileCollector) { + this.paramFileCollector = paramFileCollector; + } + @RequestMapping(value = "/submit", method = RequestMethod.POST) @ResponseBody public String submitParams( - @RequestParam("files[]") List files) { - RunScenarioResultModel result = new RunScenarioResultModel(); + @RequestParam("files[]") List files, + @RequestParam("scenarioModel") String scenarioContent) { try { UUID runId = UUID.randomUUID(); - for (MultipartFile file : files) { - file.transferTo(new File(guardDirExists(runId) - + file.getOriginalFilename())); - } - result.setRunId(runId); - return MarshalHelper.tryMarshal(result); - } catch (IOException e) { - logger.error("/prepare/fileName", e); + this.getParamFileCollector().collectParamFiles(files, runId); + System.out.println(scenarioContent); + RunScenarioModel runScenarioModel = (RunScenarioModel) MarshalHelper + .unmarshal(RunScenarioModel.class, scenarioContent); + + this.getScenarioEngine().submitScenario(runId, + Scenario.scenarioBuilder(runScenarioModel), + runScenarioModel.getPoolSize()); + return MarshalHelper.tryMarshal(buildWith(runId)); + } catch (Exception e) { + logger.error("/submit", e); return null; } } - private String guardDirExists(UUID runId) { - String dirPath = "ScenarioParameters" + FILE_SEPARATOR - + runId.toString() + FILE_SEPARATOR; - File dirFile = new File(dirPath); - if (!dirFile.exists()) { - dirFile.mkdirs(); - } - return dirPath; + private RunScenarioResultModel buildWith(UUID runId) { + RunScenarioResultModel result = new RunScenarioResultModel(); + result.setRunId(runId); + return result; + } + + @RequestMapping(value = "/runWithParams/{runId}", method = RequestMethod.POST) + @ResponseBody + public RunScenarioResultModel runWithParams(@PathVariable UUID runId) { + return this.getScenarioEngine().runWith(runId) ? buildWith(runId) + : null; } @RequestMapping(value = "/runWithoutParams", method = RequestMethod.POST) @@ -100,7 +108,11 @@ public class TestController { Scenario scenario = Scenario.scenarioBuilder(runScenarioModel); UUID runId = UUID.randomUUID(); System.out.println(runScenarioModel.getPoolSize()); - this.getLogger().info(marshalRunScenarioModel(runScenarioModel)); + this.getLogger().info(MarshalHelper.tryMarshal(runScenarioModel)); + if (runScenarioModel.getPoolSize() <= 0) { + logger.info("This RunScenarioModel's pool size is L.E zero, so throw out"); + return null; + } this.getScenarioEngine().submitScenario(runId, scenario, runScenarioModel.getPoolSize()); @@ -110,20 +122,6 @@ public class TestController { return runScenarioResultModel; } - private String marshalRunScenarioModel(RunScenarioModel inModel) { - ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); - Marshaller marshaller; - try { - marshaller = JAXBContext.newInstance(RunScenarioModel.class) - .createMarshaller(); - marshaller.marshal(inModel, outputStream); - return outputStream.toString(); - } catch (JAXBException e) { - return "exception in marshal"; - } - - } - @RequestMapping(value = "/briefAll/{runId}", method = RequestMethod.GET) @ResponseBody public TestBriefStatusModel briefAll(@PathVariable UUID runId) { diff --git a/src/main/java/org/bench4q/agent/parameterization/ParameterFileCollector.java b/src/main/java/org/bench4q/agent/parameterization/ParameterFileCollector.java new file mode 100644 index 00000000..54bdb87a --- /dev/null +++ b/src/main/java/org/bench4q/agent/parameterization/ParameterFileCollector.java @@ -0,0 +1,33 @@ +package org.bench4q.agent.parameterization; + +import java.io.File; +import java.io.IOException; +import java.util.List; +import java.util.UUID; + +import org.springframework.stereotype.Component; +import org.springframework.web.multipart.MultipartFile; + +@Component +public class ParameterFileCollector { + private static final String FILE_SEPARATOR = System + .getProperty("file.separator"); + + public void collectParamFiles(List files, UUID runId) + throws IOException { + for (MultipartFile file : files) { + file.transferTo(new File(guardDirExists(runId) + + file.getOriginalFilename())); + } + } + + private String guardDirExists(UUID runId) { + String dirPath = "ScenarioParameters" + FILE_SEPARATOR + + runId.toString() + FILE_SEPARATOR; + File dirFile = new File(dirPath); + if (!dirFile.exists()) { + dirFile.mkdirs(); + } + return dirPath; + } +} diff --git a/src/main/java/org/bench4q/agent/scenario/Scenario.java b/src/main/java/org/bench4q/agent/scenario/Scenario.java index 01a1a272..04983540 100644 --- a/src/main/java/org/bench4q/agent/scenario/Scenario.java +++ b/src/main/java/org/bench4q/agent/scenario/Scenario.java @@ -1,167 +1,176 @@ -package org.bench4q.agent.scenario; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -import org.bench4q.agent.scenario.behavior.Behavior; -import org.bench4q.agent.scenario.behavior.BehaviorFactory; -import org.bench4q.share.models.agent.ParameterModel; -import org.bench4q.share.models.agent.RunScenarioModel; -import org.bench4q.share.models.agent.scriptrecord.BatchModel; -import org.bench4q.share.models.agent.scriptrecord.BehaviorModel; -import org.bench4q.share.models.agent.scriptrecord.PageModel; -import org.bench4q.share.models.agent.scriptrecord.UsePluginModel; - -public class Scenario { - private UsePlugin[] usePlugins; - private Page[] pages; - private List behaviors; - - public UsePlugin[] getUsePlugins() { - return usePlugins; - } - - public void setUsePlugins(UsePlugin[] usePlugins) { - this.usePlugins = usePlugins; - } - - public Page[] getPages() { - return pages; - } - - public void setPages(Page[] pages) { - this.pages = pages; - } - - private List getBehaviors() { - return behaviors; - } - - private void setBehaviors(List behaviors) { - this.behaviors = behaviors; - } - - public Scenario() { - this.setBehaviors(new ArrayList()); - } - - public List getAllBehaviorsInScenario() { - if (this.getBehaviors().size() > 0) { - return Collections.unmodifiableList(this.getBehaviors()); - } - List behaviors = new ArrayList(); - for (Page page : this.getPages()) { - for (Batch batch : page.getBatches()) { - for (Behavior behavior : batch.getBehaviors()) { - behaviors.add(behavior); - } - } - } - return Collections.unmodifiableList(behaviors); - } - - public static Scenario scenarioBuilder(RunScenarioModel scenarioModel) { - Scenario scenario = extractScenario(scenarioModel); - return scenario; - } - - private static Scenario extractScenario(RunScenarioModel runScenarioModel) { - Scenario scenario = new Scenario(); - scenario.setUsePlugins(new UsePlugin[runScenarioModel.getUsePlugins() - .size()]); - scenario.setPages(new Page[runScenarioModel.getPages().size()]); - extractUsePlugins(runScenarioModel, scenario); - extractPages(runScenarioModel, scenario); - return scenario; - } - - private static void extractPages(RunScenarioModel runScenarioModel, - Scenario scenario) { - List pageModels = runScenarioModel.getPages(); - for (int i = 0; i < pageModels.size(); i++) { - PageModel pageModel = pageModels.get(i); - scenario.getPages()[i] = extractPage(pageModel); - } - } - - private static Page extractPage(PageModel pageModel) { - Page page = new Page(); - page.setBatches(new Batch[pageModel.getBatches().size()]); - List batches = pageModel.getBatches(); - for (int i = 0; i < pageModel.getBatches().size(); i++) { - BatchModel batch = batches.get(i); - page.getBatches()[i] = extractBatch(batch); - } - return page; - } - - private static Batch extractBatch(BatchModel batchModel) { - Batch batch = new Batch(); - batch.setBehaviors(new Behavior[batchModel.getBehaviors().size()]); - batch.setId(batchModel.getId()); - batch.setParentId(batchModel.getParentId()); - batch.setChildId(batchModel.getChildId()); - if (batchModel.getBehaviors() == null) { - return batch; - } - batch.setBehaviors(new Behavior[batchModel.getBehaviors().size()]); - for (int i = 0; i < batchModel.getBehaviors().size(); ++i) { - batch.getBehaviors()[i] = extractBehavior(batchModel.getBehaviors() - .get(i)); - } - return batch; - } - - private static void extractUsePlugins(RunScenarioModel runScenarioModel, - Scenario scenario) { - int i; - List usePluginModels = runScenarioModel.getUsePlugins(); - for (i = 0; i < runScenarioModel.getUsePlugins().size(); i++) { - UsePluginModel usePluginModel = usePluginModels.get(i); - UsePlugin usePlugin = extractUsePlugin(usePluginModel); - scenario.getUsePlugins()[i] = usePlugin; - } - } - - private static Behavior extractBehavior(BehaviorModel behaviorModel) { - Behavior behavior = BehaviorFactory.getBuisinessObject(behaviorModel); - behavior.setName(behaviorModel.getName()); - behavior.setUse(behaviorModel.getUse()); - behavior.setId(behaviorModel.getId()); - behavior.setParameters(new Parameter[behaviorModel.getParameters() - .size()]); - - int k = 0; - for (k = 0; k < behaviorModel.getParameters().size(); k++) { - ParameterModel parameterModel = behaviorModel.getParameters() - .get(k); - Parameter parameter = extractParameter(parameterModel); - behavior.getParameters()[k] = parameter; - } - return behavior; - } - - private static UsePlugin extractUsePlugin(UsePluginModel usePluginModel) { - UsePlugin usePlugin = new UsePlugin(); - usePlugin.setId(usePluginModel.getId()); - usePlugin.setName(usePluginModel.getName()); - usePlugin.setParameters(new Parameter[usePluginModel.getParameters() - .size()]); - int k = 0; - for (k = 0; k < usePluginModel.getParameters().size(); k++) { - ParameterModel parameterModel = usePluginModel.getParameters().get( - k); - Parameter parameter = extractParameter(parameterModel); - usePlugin.getParameters()[k] = parameter; - } - return usePlugin; - } - - private static Parameter extractParameter(ParameterModel parameterModel) { - Parameter parameter = new Parameter(); - parameter.setKey(parameterModel.getKey()); - parameter.setValue(parameterModel.getValue()); - return parameter; - } -} +package org.bench4q.agent.scenario; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.bench4q.agent.scenario.behavior.Behavior; +import org.bench4q.agent.scenario.behavior.BehaviorFactory; +import org.bench4q.share.helper.MarshalHelper; +import org.bench4q.share.models.agent.ParameterModel; +import org.bench4q.share.models.agent.RunScenarioModel; +import org.bench4q.share.models.agent.scriptrecord.BatchModel; +import org.bench4q.share.models.agent.scriptrecord.BehaviorModel; +import org.bench4q.share.models.agent.scriptrecord.PageModel; +import org.bench4q.share.models.agent.scriptrecord.UsePluginModel; + +public class Scenario { + private UsePlugin[] usePlugins; + private Page[] pages; + private List behaviors; + + public UsePlugin[] getUsePlugins() { + return usePlugins; + } + + public void setUsePlugins(UsePlugin[] usePlugins) { + this.usePlugins = usePlugins; + } + + public Page[] getPages() { + return pages; + } + + public void setPages(Page[] pages) { + this.pages = pages; + } + + private List getBehaviors() { + return behaviors; + } + + private void setBehaviors(List behaviors) { + this.behaviors = behaviors; + } + + public Scenario() { + this.setBehaviors(new ArrayList()); + } + + public List getAllBehaviorsInScenario() { + if (this.getBehaviors().size() > 0) { + return Collections.unmodifiableList(this.getBehaviors()); + } + List behaviors = new ArrayList(); + for (Page page : this.getPages()) { + for (Batch batch : page.getBatches()) { + for (Behavior behavior : batch.getBehaviors()) { + behaviors.add(behavior); + } + } + } + return Collections.unmodifiableList(behaviors); + } + + public static Scenario scenarioBuilder(String scenarioContent) { + return extractScenario((RunScenarioModel) MarshalHelper.tryUnmarshal( + RunScenarioModel.class, scenarioContent)); + } + + public static Scenario scenarioBuilder(RunScenarioModel scenarioModel) { + if (scenarioModel == null) { + throw new NullPointerException(); + } + Scenario scenario = extractScenario(scenarioModel); + return scenario; + } + + private static Scenario extractScenario(RunScenarioModel runScenarioModel) { + Scenario scenario = new Scenario(); + scenario.setUsePlugins(new UsePlugin[runScenarioModel.getUsePlugins() + .size()]); + scenario.setPages(new Page[runScenarioModel.getPages().size()]); + extractUsePlugins(runScenarioModel, scenario); + extractPages(runScenarioModel, scenario); + return scenario; + } + + private static void extractPages(RunScenarioModel runScenarioModel, + Scenario scenario) { + List pageModels = runScenarioModel.getPages(); + for (int i = 0; i < pageModels.size(); i++) { + PageModel pageModel = pageModels.get(i); + scenario.getPages()[i] = extractPage(pageModel); + } + } + + private static Page extractPage(PageModel pageModel) { + Page page = new Page(); + page.setBatches(new Batch[pageModel.getBatches().size()]); + List batches = pageModel.getBatches(); + for (int i = 0; i < pageModel.getBatches().size(); i++) { + BatchModel batch = batches.get(i); + page.getBatches()[i] = extractBatch(batch); + } + return page; + } + + private static Batch extractBatch(BatchModel batchModel) { + Batch batch = new Batch(); + batch.setBehaviors(new Behavior[batchModel.getBehaviors().size()]); + batch.setId(batchModel.getId()); + batch.setParentId(batchModel.getParentId()); + batch.setChildId(batchModel.getChildId()); + if (batchModel.getBehaviors() == null) { + return batch; + } + batch.setBehaviors(new Behavior[batchModel.getBehaviors().size()]); + for (int i = 0; i < batchModel.getBehaviors().size(); ++i) { + batch.getBehaviors()[i] = extractBehavior(batchModel.getBehaviors() + .get(i)); + } + return batch; + } + + private static void extractUsePlugins(RunScenarioModel runScenarioModel, + Scenario scenario) { + int i; + List usePluginModels = runScenarioModel.getUsePlugins(); + for (i = 0; i < runScenarioModel.getUsePlugins().size(); i++) { + UsePluginModel usePluginModel = usePluginModels.get(i); + UsePlugin usePlugin = extractUsePlugin(usePluginModel); + scenario.getUsePlugins()[i] = usePlugin; + } + } + + private static Behavior extractBehavior(BehaviorModel behaviorModel) { + Behavior behavior = BehaviorFactory.getBuisinessObject(behaviorModel); + behavior.setName(behaviorModel.getName()); + behavior.setUse(behaviorModel.getUse()); + behavior.setId(behaviorModel.getId()); + behavior.setParameters(new Parameter[behaviorModel.getParameters() + .size()]); + + int k = 0; + for (k = 0; k < behaviorModel.getParameters().size(); k++) { + ParameterModel parameterModel = behaviorModel.getParameters() + .get(k); + Parameter parameter = extractParameter(parameterModel); + behavior.getParameters()[k] = parameter; + } + return behavior; + } + + private static UsePlugin extractUsePlugin(UsePluginModel usePluginModel) { + UsePlugin usePlugin = new UsePlugin(); + usePlugin.setId(usePluginModel.getId()); + usePlugin.setName(usePluginModel.getName()); + usePlugin.setParameters(new Parameter[usePluginModel.getParameters() + .size()]); + int k = 0; + for (k = 0; k < usePluginModel.getParameters().size(); k++) { + ParameterModel parameterModel = usePluginModel.getParameters().get( + k); + Parameter parameter = extractParameter(parameterModel); + usePlugin.getParameters()[k] = parameter; + } + return usePlugin; + } + + private static Parameter extractParameter(ParameterModel parameterModel) { + Parameter parameter = new Parameter(); + parameter.setKey(parameterModel.getKey()); + parameter.setValue(parameterModel.getValue()); + return parameter; + } +} diff --git a/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java b/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java index ad3979e4..141b1e23 100644 --- a/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java +++ b/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java @@ -61,17 +61,18 @@ public class ScenarioEngine { } } - public void runWith(UUID runId) { + public boolean runWith(UUID runId) { if (!this.getRunningTests().containsKey(runId)) { - return; + return false; } final ScenarioContext context = this.getRunningTests().get(runId); - runWith(context); + return runWith(context); } - private void runWith(final ScenarioContext scenarioContext) { + private boolean runWith(final ScenarioContext scenarioContext) { if (scenarioContext == null) { - return; + logger.error("The context required is null"); + return false; } ExecutorService taskMaker = Executors.newSingleThreadExecutor(); @@ -85,6 +86,7 @@ public class ScenarioEngine { } } }); + return true; } } diff --git a/src/test/java/org/bench4q/agent/test/TestWithScriptFile.java b/src/test/java/org/bench4q/agent/test/TestWithScriptFile.java index 0dd2ba0d..9fcbcf29 100644 --- a/src/test/java/org/bench4q/agent/test/TestWithScriptFile.java +++ b/src/test/java/org/bench4q/agent/test/TestWithScriptFile.java @@ -5,6 +5,7 @@ import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.util.ArrayList; +import java.util.LinkedList; import java.util.List; import java.util.UUID; @@ -15,9 +16,11 @@ import javax.xml.bind.JAXBException; import javax.xml.bind.Unmarshaller; import org.apache.commons.io.FileUtils; +import org.bench4q.agent.parameterization.ParameterFileCollector; import org.bench4q.share.communication.HttpRequester; import org.bench4q.share.communication.HttpRequester.HttpResponse; import org.bench4q.share.helper.MarshalHelper; +import org.bench4q.share.helper.TestHelper; import org.bench4q.share.models.agent.BehaviorBriefModel; import org.bench4q.share.models.agent.RunScenarioModel; import org.bench4q.share.models.agent.RunScenarioResultModel; @@ -64,23 +67,15 @@ public class TestWithScriptFile { } private void startTest() throws JAXBException { - File file = new File(this.getFilePath()); - if (!file.exists()) { - System.out.println("this script not exists!"); - return; - } - String scriptContent; try { - scriptContent = FileUtils.readFileToString(file); - RunScenarioModel runScenarioModel = extractRunScenarioModel(scriptContent); + RunScenarioModel runScenarioModel = getScenarioModel(); if (runScenarioModel == null) { - System.out.println("can't execute an unvalid script"); + System.out.println("can't execute an invalid script"); return; } assertTrue(runScenarioModel.getPages().size() > 0); assertTrue(runScenarioModel.getPages().get(0).getBatches().get(0) .getBehaviors().size() > 0); - runScenarioModel.setPoolSize(load); HttpResponse httpResponse = this.getHttpRequester().sendPostXml( this.url + "/runWithoutParams", @@ -94,6 +89,19 @@ public class TestWithScriptFile { } } + private RunScenarioModel getScenarioModel() throws IOException { + String scriptContent; + File file = new File(this.getFilePath()); + if (!file.exists()) { + System.out.println("this script not exists!"); + return null; + } + scriptContent = FileUtils.readFileToString(file); + RunScenarioModel runScenarioModel = extractRunScenarioModel(scriptContent); + runScenarioModel.setPoolSize(load); + return runScenarioModel; + } + private RunScenarioModel extractRunScenarioModel(String scriptContent) { try { Unmarshaller unmarshaller = JAXBContext.newInstance( @@ -178,17 +186,39 @@ public class TestWithScriptFile { } @Test - public void testSubmitParams() throws IOException { + public void testSubmitParamsAndRun() throws Exception { List files = new ArrayList(); files.add(new File("Scripts" + System.getProperty("file.separator") + "forGoodRecord.xml")); files.add(new File("Scripts" + System.getProperty("file.separator") + "testJD.xml")); HttpResponse httpResponse = this.getHttpRequester().postFiles( - url + "/submit", "files[]", files); + url + "/submit", "files[]", files, "scenarioModel", + new LinkedList() { + private static final long serialVersionUID = 1L; + { + add(MarshalHelper.tryMarshal(getScenarioModel())); + } + }); assertNotNull(httpResponse); assertNotNull(httpResponse.getContent()); assertEquals(200, httpResponse.getCode()); + RunScenarioResultModel resultModel = (RunScenarioResultModel) MarshalHelper + .tryUnmarshal(RunScenarioResultModel.class, + httpResponse.getContent()); + String dirPath = (String) TestHelper.invokePrivate( + ParameterFileCollector.class, new ParameterFileCollector(), + "guardDirExists", new Class[] { UUID.class }, + new Object[] { resultModel.getRunId() }); + File file = new File(dirPath); + assertTrue(file.exists()); + assertEquals(2, file.listFiles().length); + System.out.println(httpResponse.getContent()); + + httpResponse = this.getHttpRequester().sendPost( + this.url + "/runWithParams/" + + resultModel.getRunId().toString(), null, null); + assertNotNull(httpResponse); System.out.println(httpResponse.getContent()); } From ae730989ba4b75dca86dcefd2dfc2b8d48f809c4 Mon Sep 17 00:00:00 2001 From: coderfengyun Date: Tue, 18 Mar 2014 17:32:51 +0800 Subject: [PATCH 187/196] refa the name of api --- src/main/java/org/bench4q/agent/api/TestController.java | 2 +- src/test/java/org/bench4q/agent/test/TestWithScriptFile.java | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/main/java/org/bench4q/agent/api/TestController.java b/src/main/java/org/bench4q/agent/api/TestController.java index 2357f52e..7ac0e847 100644 --- a/src/main/java/org/bench4q/agent/api/TestController.java +++ b/src/main/java/org/bench4q/agent/api/TestController.java @@ -65,7 +65,7 @@ public class TestController { this.paramFileCollector = paramFileCollector; } - @RequestMapping(value = "/submit", method = RequestMethod.POST) + @RequestMapping(value = "/submitScenarioWithModel", method = RequestMethod.POST) @ResponseBody public String submitParams( @RequestParam("files[]") List files, diff --git a/src/test/java/org/bench4q/agent/test/TestWithScriptFile.java b/src/test/java/org/bench4q/agent/test/TestWithScriptFile.java index 9fcbcf29..7793652c 100644 --- a/src/test/java/org/bench4q/agent/test/TestWithScriptFile.java +++ b/src/test/java/org/bench4q/agent/test/TestWithScriptFile.java @@ -193,8 +193,8 @@ public class TestWithScriptFile { files.add(new File("Scripts" + System.getProperty("file.separator") + "testJD.xml")); HttpResponse httpResponse = this.getHttpRequester().postFiles( - url + "/submit", "files[]", files, "scenarioModel", - new LinkedList() { + url + "/submitScenarioWithModel", "files[]", files, + "scenarioModel", new LinkedList() { private static final long serialVersionUID = 1L; { add(MarshalHelper.tryMarshal(getScenarioModel())); From 40da5adf12fb90937f10105d0408a5c44653c284 Mon Sep 17 00:00:00 2001 From: coderfengyun Date: Wed, 19 Mar 2014 10:19:13 +0800 Subject: [PATCH 188/196] a little refactor --- .../java/org/bench4q/agent/api/TestController.java | 10 +++++----- .../org/bench4q/agent/test/TestWithScriptFile.java | 2 +- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/src/main/java/org/bench4q/agent/api/TestController.java b/src/main/java/org/bench4q/agent/api/TestController.java index 7ac0e847..736b1032 100644 --- a/src/main/java/org/bench4q/agent/api/TestController.java +++ b/src/main/java/org/bench4q/agent/api/TestController.java @@ -65,24 +65,24 @@ public class TestController { this.paramFileCollector = paramFileCollector; } - @RequestMapping(value = "/submitScenarioWithModel", method = RequestMethod.POST) + @RequestMapping(value = "/submitScenarioWithParams", method = RequestMethod.POST) @ResponseBody public String submitParams( @RequestParam("files[]") List files, - @RequestParam("scenarioModel") String scenarioContent) { + @RequestParam("scenarioModel") String scenarioModel) { try { UUID runId = UUID.randomUUID(); this.getParamFileCollector().collectParamFiles(files, runId); - System.out.println(scenarioContent); + System.out.println(scenarioModel); RunScenarioModel runScenarioModel = (RunScenarioModel) MarshalHelper - .unmarshal(RunScenarioModel.class, scenarioContent); + .unmarshal(RunScenarioModel.class, scenarioModel); this.getScenarioEngine().submitScenario(runId, Scenario.scenarioBuilder(runScenarioModel), runScenarioModel.getPoolSize()); return MarshalHelper.tryMarshal(buildWith(runId)); } catch (Exception e) { - logger.error("/submit", e); + logger.error("/submitScenarioWithParams", e); return null; } } diff --git a/src/test/java/org/bench4q/agent/test/TestWithScriptFile.java b/src/test/java/org/bench4q/agent/test/TestWithScriptFile.java index 7793652c..e2aebbc4 100644 --- a/src/test/java/org/bench4q/agent/test/TestWithScriptFile.java +++ b/src/test/java/org/bench4q/agent/test/TestWithScriptFile.java @@ -193,7 +193,7 @@ public class TestWithScriptFile { files.add(new File("Scripts" + System.getProperty("file.separator") + "testJD.xml")); HttpResponse httpResponse = this.getHttpRequester().postFiles( - url + "/submitScenarioWithModel", "files[]", files, + url + "/submitScenarioWithParams", "files[]", files, "scenarioModel", new LinkedList() { private static final long serialVersionUID = 1L; { From b968e8bac6a7f07049f735b4f614e814e2b84a36 Mon Sep 17 00:00:00 2001 From: coderfengyun Date: Wed, 19 Mar 2014 15:43:07 +0800 Subject: [PATCH 189/196] refactor refactor --- .../impl/InstanceControler.java | 17 +++++++--------- .../agent/test/TestWithScriptFile.java | 4 ++-- .../parameterization/TEST_HelloThread.java | 8 +++++++- .../Test_ParameterizationParser.java | 4 ++-- .../agent/test/plugin/Test_HttpPlugin.java | 8 ++++---- .../scenario/utils/Test_ParameterParser.java | 20 +++++++++---------- .../test/storage/TestDoubleBufferStorage.java | 4 ++-- 7 files changed, 33 insertions(+), 32 deletions(-) diff --git a/src/main/java/org/bench4q/agent/parameterization/impl/InstanceControler.java b/src/main/java/org/bench4q/agent/parameterization/impl/InstanceControler.java index 53df2055..e35511a7 100644 --- a/src/main/java/org/bench4q/agent/parameterization/impl/InstanceControler.java +++ b/src/main/java/org/bench4q/agent/parameterization/impl/InstanceControler.java @@ -17,10 +17,10 @@ public class InstanceControler implements SessionObject { private Set usedClassName = new HashSet(); private Map objMap = new HashMap(); private Map runtimeParaMap = new HashMap(); - public Map cacheObjMap = new HashMap(); - ReentrantReadWriteLock mapRWLock = new ReentrantReadWriteLock(); + private Map cacheObjMap = new HashMap(); + private ReentrantReadWriteLock mapRWLock = new ReentrantReadWriteLock(); - public String instanceLevelGetParameter(String name, String className, + String instanceLevelGetParameter(String name, String className, String functionName, Object[] args) { boolean hasThisClass = false; @@ -56,7 +56,7 @@ public class InstanceControler implements SessionObject { } - public String getParameterByContext(String name) { + String getParameterByContext(String name) { if (false == this.runtimeParaMap.containsKey(name)) { return null; } @@ -79,7 +79,7 @@ public class InstanceControler implements SessionObject { return true; } - public Object getObj(String className) { + private Object getObj(String className) { Object result = null; mapRWLock.readLock().lock(); objMap.get(className); @@ -87,8 +87,8 @@ public class InstanceControler implements SessionObject { return result; } - public String getParameter(String name, String className, - String functionName, Object[] args) { + String getParameter(String name, String className, String functionName, + Object[] args) { ParametersFactory pf = ParametersFactory.getInstance(); boolean hasThisClass = pf.containObj(className); @@ -152,9 +152,6 @@ public class InstanceControler implements SessionObject { /** * Implement SessionObject end */ - protected void finalize() { - // releaseAll(); - } public void releaseAll() { for (String xx : usedClassName) { diff --git a/src/test/java/org/bench4q/agent/test/TestWithScriptFile.java b/src/test/java/org/bench4q/agent/test/TestWithScriptFile.java index e2aebbc4..d9a83b3a 100644 --- a/src/test/java/org/bench4q/agent/test/TestWithScriptFile.java +++ b/src/test/java/org/bench4q/agent/test/TestWithScriptFile.java @@ -207,8 +207,8 @@ public class TestWithScriptFile { .tryUnmarshal(RunScenarioResultModel.class, httpResponse.getContent()); String dirPath = (String) TestHelper.invokePrivate( - ParameterFileCollector.class, new ParameterFileCollector(), - "guardDirExists", new Class[] { UUID.class }, + new ParameterFileCollector(), "guardDirExists", + new Class[] { UUID.class }, new Object[] { resultModel.getRunId() }); File file = new File(dirPath); assertTrue(file.exists()); diff --git a/src/test/java/org/bench4q/agent/test/parameterization/TEST_HelloThread.java b/src/test/java/org/bench4q/agent/test/parameterization/TEST_HelloThread.java index 162ec160..b93f6413 100644 --- a/src/test/java/org/bench4q/agent/test/parameterization/TEST_HelloThread.java +++ b/src/test/java/org/bench4q/agent/test/parameterization/TEST_HelloThread.java @@ -1,6 +1,7 @@ package org.bench4q.agent.test.parameterization; import org.bench4q.agent.parameterization.impl.InstanceControler; +import org.bench4q.share.helper.TestHelper; public class TEST_HelloThread extends Thread { InstanceControler ic; @@ -36,7 +37,12 @@ public class TEST_HelloThread extends Thread { // TODO Auto-generated catch block e.printStackTrace(); } - ic.releaseAll(); + // ic.releaseAll(); + try { + TestHelper.invokePrivate(ic, "releaseAll", null, null); + } catch (Exception e) { + e.printStackTrace(); + } } diff --git a/src/test/java/org/bench4q/agent/test/parameterization/Test_ParameterizationParser.java b/src/test/java/org/bench4q/agent/test/parameterization/Test_ParameterizationParser.java index f4140855..368a1fce 100644 --- a/src/test/java/org/bench4q/agent/test/parameterization/Test_ParameterizationParser.java +++ b/src/test/java/org/bench4q/agent/test/parameterization/Test_ParameterizationParser.java @@ -11,8 +11,8 @@ public class Test_ParameterizationParser { @Test public void testGetClassName() throws Exception { String result = (String) TestHelper.invokePrivate( - ParameterizationParser.class, new ParameterizationParser(), - "getCurrentPackageFullName", null, null); + new ParameterizationParser(), "getCurrentPackageFullName", + null, null); assertEquals("org.bench4q.agent.parameterization.impl", result); } diff --git a/src/test/java/org/bench4q/agent/test/plugin/Test_HttpPlugin.java b/src/test/java/org/bench4q/agent/test/plugin/Test_HttpPlugin.java index c7a89826..930951c4 100644 --- a/src/test/java/org/bench4q/agent/test/plugin/Test_HttpPlugin.java +++ b/src/test/java/org/bench4q/agent/test/plugin/Test_HttpPlugin.java @@ -121,10 +121,10 @@ public class Test_HttpPlugin { + "}"; @SuppressWarnings("unchecked") Map nameValueMap = (Map) TestHelper - .invokePrivate(this.getHttpPlugin().getClass(), - this.getHttpPlugin(), "doExtractResponseVariables", - new Class[] { String.class, String.class }, - new Object[] { respVarsToSave, responseBodyAsString }); + .invokePrivate(this.getHttpPlugin(), + "doExtractResponseVariables", new Class[] { + String.class, String.class }, new Object[] { + respVarsToSave, responseBodyAsString }); assertEquals(1, nameValueMap.size()); assertTrue(nameValueMap.containsKey("ticket")); System.out.println(nameValueMap.get("ticket")); diff --git a/src/test/java/org/bench4q/agent/test/scenario/utils/Test_ParameterParser.java b/src/test/java/org/bench4q/agent/test/scenario/utils/Test_ParameterParser.java index 7554daf6..a7bb2c72 100644 --- a/src/test/java/org/bench4q/agent/test/scenario/utils/Test_ParameterParser.java +++ b/src/test/java/org/bench4q/agent/test/scenario/utils/Test_ParameterParser.java @@ -40,7 +40,7 @@ public class Test_ParameterParser { @Test public void testGetNumberOfEscapeCharacter() throws Exception { assertEquals(3, "\\\\\\".length()); - assertEquals(2, TestHelper.invokePrivate(ParameterParser.class, null, + assertEquals(2, TestHelper.invokePrivate(null, "getNumberOfEscapeCharacter", new Class[] { String.class }, new Object[] { "\\\\" })); } @@ -69,8 +69,7 @@ public class Test_ParameterParser { columnList.get(1)); @SuppressWarnings("unchecked") List> result = (List>) TestHelper - .invokePrivate(Table.class, null, - "extractValueFromWellFormedTable", + .invokePrivate(null, "extractValueFromWellFormedTable", new Class[] { List.class }, new Object[] { new LinkedList>() { private static final long serialVersionUID = 1L; @@ -94,10 +93,9 @@ public class Test_ParameterParser { @SuppressWarnings("unchecked") private List invokeGetRealTokens(String separator, String value, boolean toUnescapeSeparator) throws Exception { - return (List) TestHelper.invokePrivate(ParameterParser.class, - null, "getRealTokens", new Class[] { String.class, - String.class, boolean.class }, new Object[] { - separator, value, true }); + return (List) TestHelper.invokePrivate(null, "getRealTokens", + new Class[] { String.class, String.class, boolean.class }, + new Object[] { separator, value, true }); } @Test @@ -164,8 +162,8 @@ public class Test_ParameterParser { public void testGetHeadersWithRightCase() throws Exception { @SuppressWarnings("unchecked") List nvPairs = (List) TestHelper - .invokePrivate(HttpPlugin.class, new HttpPlugin(), - "parseHeaders", new Class[] { String.class }, + .invokePrivate(new HttpPlugin(), "parseHeaders", + new Class[] { String.class }, new Object[] { testHeaders }); assertEquals(3, nvPairs.size()); @@ -183,8 +181,8 @@ public class Test_ParameterParser { public void testGetHeadersWithUpperCase() throws Exception { @SuppressWarnings("unchecked") List nvPairs = (List) TestHelper - .invokePrivate(HttpPlugin.class, new HttpPlugin(), - "parseHeaders", new Class[] { String.class }, + .invokePrivate(new HttpPlugin(), "parseHeaders", + new Class[] { String.class }, new Object[] { testheaderWithUpperCase }); assertEquals(3, nvPairs.size()); assertEquals("Content-Type", nvPairs.get(0).getName()); diff --git a/src/test/java/org/bench4q/agent/test/storage/TestDoubleBufferStorage.java b/src/test/java/org/bench4q/agent/test/storage/TestDoubleBufferStorage.java index cc068736..3559adc2 100644 --- a/src/test/java/org/bench4q/agent/test/storage/TestDoubleBufferStorage.java +++ b/src/test/java/org/bench4q/agent/test/storage/TestDoubleBufferStorage.java @@ -191,8 +191,8 @@ public class TestDoubleBufferStorage { private static Object invokePrivateMethod(Class containerClass, Object targetObject, String methodName, Class[] paramClasses, Object[] params) throws Exception { - return TestHelper.invokePrivate(containerClass, targetObject, - methodName, paramClasses, params); + return TestHelper.invokePrivate(targetObject, methodName, paramClasses, + params); } @Test From 4b5aa3cb583e2937ac0d469f0ad23ff18fa80ad4 Mon Sep 17 00:00:00 2001 From: coderfengyun Date: Wed, 19 Mar 2014 15:46:23 +0800 Subject: [PATCH 190/196] refactor go on refactor go on --- .../agent/parameterization/impl/InstanceControler.java | 8 ++------ .../agent/test/parameterization/TEST_UserName.java | 6 ++++-- 2 files changed, 6 insertions(+), 8 deletions(-) diff --git a/src/main/java/org/bench4q/agent/parameterization/impl/InstanceControler.java b/src/main/java/org/bench4q/agent/parameterization/impl/InstanceControler.java index e35511a7..47350580 100644 --- a/src/main/java/org/bench4q/agent/parameterization/impl/InstanceControler.java +++ b/src/main/java/org/bench4q/agent/parameterization/impl/InstanceControler.java @@ -153,18 +153,14 @@ public class InstanceControler implements SessionObject { * Implement SessionObject end */ - public void releaseAll() { + private void releaseAll() { for (String xx : usedClassName) { release(xx); } } - public void release(String className) { + private void release(String className) { ParametersFactory pf = ParametersFactory.getInstance(); - // for(String s: pf.objMap.keySet()) - // { - // System.out.println(s); - // } boolean hasThisClass = pf.containObj(className); if (false == hasThisClass) { pf.createObj(className); diff --git a/src/test/java/org/bench4q/agent/test/parameterization/TEST_UserName.java b/src/test/java/org/bench4q/agent/test/parameterization/TEST_UserName.java index 40568dfd..3db75627 100644 --- a/src/test/java/org/bench4q/agent/test/parameterization/TEST_UserName.java +++ b/src/test/java/org/bench4q/agent/test/parameterization/TEST_UserName.java @@ -1,10 +1,11 @@ package org.bench4q.agent.test.parameterization; import org.bench4q.agent.parameterization.impl.InstanceControler; +import org.bench4q.share.helper.TestHelper; public class TEST_UserName { - public static void main(String[] args) { + public static void main(String[] args) throws Exception { // TODO Auto-generated method stub // Para_UserNameAndPassword pp = new Para_UserNameAndPassword(); // UUID temp = java.util.UUID.randomUUID(); @@ -18,7 +19,8 @@ public class TEST_UserName { System.out.print("\t"); System.out.println(passwordName); // pp.unreg(temp); - ic.releaseAll(); + // ic.releaseAll(); + TestHelper.invokePrivate(ic, "releaseAll", null, null); } } From 259042343ee3615d0f11c3d74b00a8e9448e4d0c Mon Sep 17 00:00:00 2001 From: coderfengyun Date: Wed, 19 Mar 2014 16:31:46 +0800 Subject: [PATCH 191/196] update the test case and refactor --- ScenarioParameters/param1.txt | 1 + .../impl/InstanceControler.java | 3 +-- .../parameterization/impl/Para_Table.java | 2 ++ .../impl/ParameterizationParser.java | 8 ++++---- .../test/parameterization/TEST_UserName.java | 20 +++++++------------ .../Test_ParameterizationParser.java | 3 +-- 6 files changed, 16 insertions(+), 21 deletions(-) create mode 100644 ScenarioParameters/param1.txt diff --git a/ScenarioParameters/param1.txt b/ScenarioParameters/param1.txt new file mode 100644 index 00000000..748dc5f7 --- /dev/null +++ b/ScenarioParameters/param1.txt @@ -0,0 +1 @@ +row1;10;11~row2;20;21~row3,30,31~ \ No newline at end of file diff --git a/src/main/java/org/bench4q/agent/parameterization/impl/InstanceControler.java b/src/main/java/org/bench4q/agent/parameterization/impl/InstanceControler.java index 47350580..89b4b7ff 100644 --- a/src/main/java/org/bench4q/agent/parameterization/impl/InstanceControler.java +++ b/src/main/java/org/bench4q/agent/parameterization/impl/InstanceControler.java @@ -133,8 +133,7 @@ public class InstanceControler implements SessionObject { public String getParam(String name) { if (!(name.startsWith(""))) return name; - ParameterizationParser p = new ParameterizationParser(); - return p.parse(name, this); + return ParameterizationParser.parse(name, this); } public void saveRuntimeParam(String name, String value) { diff --git a/src/main/java/org/bench4q/agent/parameterization/impl/Para_Table.java b/src/main/java/org/bench4q/agent/parameterization/impl/Para_Table.java index 78115445..0eaf3577 100644 --- a/src/main/java/org/bench4q/agent/parameterization/impl/Para_Table.java +++ b/src/main/java/org/bench4q/agent/parameterization/impl/Para_Table.java @@ -148,11 +148,13 @@ public class Para_Table { } else if (readBuff == this.splitChar) { tempTableRow.AddCell(target.toString()); target.clear(); + continue; } else if (readBuff == this.lineChar) { tempTableRow.AddCell(target.toString()); result.add(tempTableRow); target.clear(); i++; + continue; } target.append(readBuff); } diff --git a/src/main/java/org/bench4q/agent/parameterization/impl/ParameterizationParser.java b/src/main/java/org/bench4q/agent/parameterization/impl/ParameterizationParser.java index 32e4d513..ff6f6684 100644 --- a/src/main/java/org/bench4q/agent/parameterization/impl/ParameterizationParser.java +++ b/src/main/java/org/bench4q/agent/parameterization/impl/ParameterizationParser.java @@ -11,7 +11,7 @@ import org.xml.sax.InputSource; public class ParameterizationParser { - public String parse(String text, InstanceControler insCon) { + public static String parse(String text, InstanceControler insCon) { // Pattern pattern = Pattern.compile(""); String result = ""; try { @@ -46,8 +46,8 @@ public class ParameterizationParser { return result; } - private String getCurrentPackageFullName() { - return this.getClass().getName() - .substring(0, this.getClass().getName().lastIndexOf('.')); + private static String getCurrentPackageFullName() { + return ParameterizationParser.class.getName().substring(0, + ParameterizationParser.class.getName().lastIndexOf('.')); } } diff --git a/src/test/java/org/bench4q/agent/test/parameterization/TEST_UserName.java b/src/test/java/org/bench4q/agent/test/parameterization/TEST_UserName.java index 3db75627..29156cfe 100644 --- a/src/test/java/org/bench4q/agent/test/parameterization/TEST_UserName.java +++ b/src/test/java/org/bench4q/agent/test/parameterization/TEST_UserName.java @@ -1,26 +1,20 @@ package org.bench4q.agent.test.parameterization; +import static org.junit.Assert.*; + import org.bench4q.agent.parameterization.impl.InstanceControler; import org.bench4q.share.helper.TestHelper; +import org.junit.Test; public class TEST_UserName { - public static void main(String[] args) throws Exception { - // TODO Auto-generated method stub - // Para_UserNameAndPassword pp = new Para_UserNameAndPassword(); - // UUID temp = java.util.UUID.randomUUID(); - // pp.getUserName(temp); + @Test + public void testGetParam() throws Exception { InstanceControler ic = new InstanceControler(); - String userName = ic - .getParam("!parameters class=\"Para_UserNameAndPassword\" method=\"getUserName\" args=\"\" !!"); String passwordName = ic - .getParam(""); - System.out.print(userName); - System.out.print("\t"); + .getParam(""); System.out.println(passwordName); - // pp.unreg(temp); - // ic.releaseAll(); + assertNotNull(passwordName); TestHelper.invokePrivate(ic, "releaseAll", null, null); } - } diff --git a/src/test/java/org/bench4q/agent/test/parameterization/Test_ParameterizationParser.java b/src/test/java/org/bench4q/agent/test/parameterization/Test_ParameterizationParser.java index 368a1fce..a802129b 100644 --- a/src/test/java/org/bench4q/agent/test/parameterization/Test_ParameterizationParser.java +++ b/src/test/java/org/bench4q/agent/test/parameterization/Test_ParameterizationParser.java @@ -18,8 +18,7 @@ public class Test_ParameterizationParser { @Test public void testParse() { - ParameterizationParser parameterParser = new ParameterizationParser(); - String result = parameterParser.parse( + String result = ParameterizationParser.parse( "", new InstanceControler()); System.out.println(result); From 0bf9cf3dc01ef185457bd307e7f1fd259dd098ef Mon Sep 17 00:00:00 2001 From: yxsh Date: Wed, 19 Mar 2014 19:04:54 +0800 Subject: [PATCH 192/196] fix para bug --- .../impl/InstanceControler.java | 4 +- .../parameterization/impl/Para_Table.java | 39 +++++++++++++------ .../impl/ParametersFactory.java | 4 +- .../test/parameterization/TEST_UserName.java | 12 +++++- 4 files changed, 43 insertions(+), 16 deletions(-) diff --git a/src/main/java/org/bench4q/agent/parameterization/impl/InstanceControler.java b/src/main/java/org/bench4q/agent/parameterization/impl/InstanceControler.java index 89b4b7ff..e14e9164 100644 --- a/src/main/java/org/bench4q/agent/parameterization/impl/InstanceControler.java +++ b/src/main/java/org/bench4q/agent/parameterization/impl/InstanceControler.java @@ -99,10 +99,10 @@ public class InstanceControler implements SessionObject { Object instance = pf.getObj(className); Object result = null; try { - Class[] argTypeArr = new Class[args.length + 1]; + Class[] argTypeArr = new Class[args.length + 2]; argTypeArr[0] = instandid.getClass(); argTypeArr[1] = this.cacheObjMap.getClass(); - Object[] totalArgs = new Object[args.length + 1]; + Object[] totalArgs = new Object[args.length + 2]; totalArgs[0] = instandid; totalArgs[1] = this.cacheObjMap; for (int i = 2; i < args.length + 2; i++) { diff --git a/src/main/java/org/bench4q/agent/parameterization/impl/Para_Table.java b/src/main/java/org/bench4q/agent/parameterization/impl/Para_Table.java index 0eaf3577..5a76d50d 100644 --- a/src/main/java/org/bench4q/agent/parameterization/impl/Para_Table.java +++ b/src/main/java/org/bench4q/agent/parameterization/impl/Para_Table.java @@ -6,6 +6,7 @@ import java.io.IOException; import java.io.InputStreamReader; import java.nio.CharBuffer; import java.util.ArrayList; +import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Random; @@ -57,7 +58,7 @@ public class Para_Table { } } result = queue.poll(); - } while (result != null); + } while (result == null); return result; } @@ -84,7 +85,7 @@ public class Para_Table { } } result = queue.poll(); - } while (result != null); + } while (result == null); return result; } @@ -119,7 +120,12 @@ public class Para_Table { super(sourceValue, firstRow); this.splitChar = splitChar; this.lineChar = lineChar; - + try { + createBFR(); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } } private void createBFR() throws IOException { @@ -136,23 +142,26 @@ public class Para_Table { @Override public List readRows() { - CharBuffer target = CharBuffer.allocate(readCharSize); + StringBuilder target = new StringBuilder(); List result = new ArrayList(); TableRow tempTableRow = new TableRow(); try { for (int i = 0; i < cacheSize;) { - char readBuff = (char) bfr.read(); - if (readBuff == -1) { + int tt = bfr.read(); + char readBuff = (char)tt; + if (tt == -1) { createBFR(); break; } else if (readBuff == this.splitChar) { - tempTableRow.AddCell(target.toString()); - target.clear(); + String cellString = target.toString(); + tempTableRow.AddCell(cellString); + target = new StringBuilder(); continue; } else if (readBuff == this.lineChar) { tempTableRow.AddCell(target.toString()); result.add(tempTableRow); - target.clear(); + tempTableRow = new TableRow(); + target = new StringBuilder(); i++; continue; } @@ -164,7 +173,7 @@ public class Para_Table { if (target.length() > 0) { tempTableRow.AddCell(target.toString()); result.add(tempTableRow); - target.clear(); + target = new StringBuilder(); } return result; } @@ -209,7 +218,11 @@ public class Para_Table { } } - public String getTableColumnValue(UUID id, Map objCache, + // org.bench4q.agent.parameterization.impl.Para_Table.getTableColumnValue(java.util.UUID, + // java.util.HashMap, java.lang.String, java.lang.String, java.lang.String, + // java.lang.String, java.lang.String, java.lang.String, java.lang.String) + + public String getTableColumnValue(UUID id, HashMap objCache, String source, String sourceValue, String firstRow, String nextRow, String splitChar, String lineChar, String column) { int fRow = Integer.parseInt(firstRow); @@ -245,4 +258,8 @@ public class Para_Table { return resultRow.cells.get(col); } + + public void unreg(UUID id) { + + } } diff --git a/src/main/java/org/bench4q/agent/parameterization/impl/ParametersFactory.java b/src/main/java/org/bench4q/agent/parameterization/impl/ParametersFactory.java index 4902a66d..13795e4e 100644 --- a/src/main/java/org/bench4q/agent/parameterization/impl/ParametersFactory.java +++ b/src/main/java/org/bench4q/agent/parameterization/impl/ParametersFactory.java @@ -29,7 +29,7 @@ public class ParametersFactory { public Object getObj(String className) { Object result = null; mapRWLock.readLock().lock(); - objMap.get(className); + result = objMap.get(className); mapRWLock.readLock().unlock(); return result; } @@ -48,7 +48,7 @@ public class ParametersFactory { objMap.put(className, instance); } catch (Exception ex) { - + System.out.println(ex.getMessage()); } mapRWLock.writeLock().unlock(); return true; diff --git a/src/test/java/org/bench4q/agent/test/parameterization/TEST_UserName.java b/src/test/java/org/bench4q/agent/test/parameterization/TEST_UserName.java index 29156cfe..a023beb1 100644 --- a/src/test/java/org/bench4q/agent/test/parameterization/TEST_UserName.java +++ b/src/test/java/org/bench4q/agent/test/parameterization/TEST_UserName.java @@ -2,7 +2,10 @@ package org.bench4q.agent.test.parameterization; import static org.junit.Assert.*; +import java.util.HashMap; + import org.bench4q.agent.parameterization.impl.InstanceControler; +import org.bench4q.agent.parameterization.impl.Para_Table; import org.bench4q.share.helper.TestHelper; import org.junit.Test; @@ -10,11 +13,18 @@ public class TEST_UserName { @Test public void testGetParam() throws Exception { + Para_Table table = new Para_Table(); + String ret = table.getTableColumnValue(java.util.UUID.randomUUID(), + new HashMap(), "file", + "ScenarioParameters\\param1.txt", "0", "sequence", ";", "~", + "2"); + System.out.println(ret); InstanceControler ic = new InstanceControler(); String passwordName = ic - .getParam(""); + .getParam(""); System.out.println(passwordName); assertNotNull(passwordName); TestHelper.invokePrivate(ic, "releaseAll", null, null); + } } From 0f116bb29be7b0484c34940760dab2f22dbec256 Mon Sep 17 00:00:00 2001 From: coderfengyun Date: Thu, 20 Mar 2014 09:16:25 +0800 Subject: [PATCH 193/196] add test case for this programe --- .../agent/parameterization/impl/Para_Table.java | 14 ++++++-------- .../agent/test/parameterization/TEST_UserName.java | 11 +++++++++-- 2 files changed, 15 insertions(+), 10 deletions(-) diff --git a/src/main/java/org/bench4q/agent/parameterization/impl/Para_Table.java b/src/main/java/org/bench4q/agent/parameterization/impl/Para_Table.java index 5a76d50d..c267c736 100644 --- a/src/main/java/org/bench4q/agent/parameterization/impl/Para_Table.java +++ b/src/main/java/org/bench4q/agent/parameterization/impl/Para_Table.java @@ -4,11 +4,9 @@ import java.io.BufferedReader; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; -import java.nio.CharBuffer; import java.util.ArrayList; import java.util.HashMap; import java.util.List; -import java.util.Map; import java.util.Random; import java.util.UUID; import java.util.concurrent.ArrayBlockingQueue; @@ -147,8 +145,8 @@ public class Para_Table { TableRow tempTableRow = new TableRow(); try { for (int i = 0; i < cacheSize;) { - int tt = bfr.read(); - char readBuff = (char)tt; + int tt = bfr.read(); + char readBuff = (char) tt; if (tt == -1) { createBFR(); break; @@ -222,8 +220,9 @@ public class Para_Table { // java.util.HashMap, java.lang.String, java.lang.String, java.lang.String, // java.lang.String, java.lang.String, java.lang.String, java.lang.String) - public String getTableColumnValue(UUID id, HashMap objCache, - String source, String sourceValue, String firstRow, String nextRow, + public String getTableColumnValue(UUID id, + HashMap objCache, String source, + String sourceValue, String firstRow, String nextRow, String splitChar, String lineChar, String column) { int fRow = Integer.parseInt(firstRow); char sChar = splitChar.charAt(0); @@ -258,8 +257,7 @@ public class Para_Table { return resultRow.cells.get(col); } - public void unreg(UUID id) { - + } } diff --git a/src/test/java/org/bench4q/agent/test/parameterization/TEST_UserName.java b/src/test/java/org/bench4q/agent/test/parameterization/TEST_UserName.java index a023beb1..89e4f2f2 100644 --- a/src/test/java/org/bench4q/agent/test/parameterization/TEST_UserName.java +++ b/src/test/java/org/bench4q/agent/test/parameterization/TEST_UserName.java @@ -19,12 +19,19 @@ public class TEST_UserName { "ScenarioParameters\\param1.txt", "0", "sequence", ";", "~", "2"); System.out.println(ret); + InstanceControler ic = new InstanceControler(); String passwordName = ic - .getParam(""); + .getParam(""); System.out.println(passwordName); assertNotNull(passwordName); + InstanceControler instanceControler = new InstanceControler(); + String password2 = instanceControler + .getParam(""); + System.out.println(password2); + assertNotNull(password2); + assertEquals(Integer.parseInt(passwordName) + 10, + Integer.parseInt(password2)); TestHelper.invokePrivate(ic, "releaseAll", null, null); - } } From 607707e3ec6c9f3702277813a2c370c752ef1d2c Mon Sep 17 00:00:00 2001 From: yxsh Date: Thu, 20 Mar 2014 09:22:35 +0800 Subject: [PATCH 194/196] fix sequence bug --- .../parameterization/impl/Para_Table.java | 40 +++++++++++-------- 1 file changed, 24 insertions(+), 16 deletions(-) diff --git a/src/main/java/org/bench4q/agent/parameterization/impl/Para_Table.java b/src/main/java/org/bench4q/agent/parameterization/impl/Para_Table.java index c267c736..201003a5 100644 --- a/src/main/java/org/bench4q/agent/parameterization/impl/Para_Table.java +++ b/src/main/java/org/bench4q/agent/parameterization/impl/Para_Table.java @@ -10,11 +10,13 @@ import java.util.List; import java.util.Random; import java.util.UUID; import java.util.concurrent.ArrayBlockingQueue; +import java.util.concurrent.ConcurrentHashMap; public class Para_Table { public final int cacheCap = 5000;// 1 sequence 2 random public final int cacheSize = 1000;// 1 sequence 2 random public final int readCharSize = 10000; + public ConcurrentHashMap readerMap = new ConcurrentHashMap(); public abstract class Reader { public final Table t; @@ -235,23 +237,29 @@ public class Para_Table { resultRow = (TableRow) objCache.get(sourceValue); return resultRow.cells.get(col); } - if (source.equals("file")) { - table = new FileTable(sourceValue, fRow, sChar, lChar); - } else if (source.equals("input")) { - table = new StringTable(sourceValue, fRow, sChar, lChar); + + if (this.readerMap.containsKey(sourceValue)) { + reader = readerMap.get(sourceValue); + + } else { + if (source.equals("file")) { + table = new FileTable(sourceValue, fRow, sChar, lChar); + } else if (source.equals("input")) { + table = new StringTable(sourceValue, fRow, sChar, lChar); + } + + if (nextRow.equals("random")) { + ArrayBlockingQueue queue = new ArrayBlockingQueue( + cacheCap); + reader = new RandomReader(queue, table); + } else if (nextRow.equals("sequence")) { + + ArrayBlockingQueue queue = new ArrayBlockingQueue( + cacheCap); + reader = new SequenceReader(queue, table); + } + readerMap.put(sourceValue, reader); } - - if (nextRow.equals("random")) { - ArrayBlockingQueue queue = new ArrayBlockingQueue( - cacheCap); - reader = new RandomReader(queue, table); - } else if (nextRow.equals("sequence")) { - - ArrayBlockingQueue queue = new ArrayBlockingQueue( - cacheCap); - reader = new SequenceReader(queue, table); - } - resultRow = reader.nextRow(); objCache.put(sourceValue, resultRow); return resultRow.cells.get(col); From 318ce8b8383171305fa6f04e09c48ccb77220f77 Mon Sep 17 00:00:00 2001 From: Zhen Tang Date: Wed, 19 Mar 2014 19:41:44 -0700 Subject: [PATCH 195/196] Initial commit --- LICENSE | 674 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ README.md | 4 + 2 files changed, 678 insertions(+) create mode 100644 LICENSE create mode 100644 README.md diff --git a/LICENSE b/LICENSE new file mode 100644 index 00000000..70566f2d --- /dev/null +++ b/LICENSE @@ -0,0 +1,674 @@ +GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + {one line to give the program's name and a brief idea of what it does.} + Copyright (C) {year} {name of author} + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + {project} Copyright (C) {year} {fullname} + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 00000000..d9df9ded --- /dev/null +++ b/README.md @@ -0,0 +1,4 @@ +Bench4Q +======= + +A QoS-Oriented E-Commerce Benchmark From 16d4ec7248dc0f2ebe95f97ff939f875febc7cdc Mon Sep 17 00:00:00 2001 From: coderfengyun Date: Thu, 20 Mar 2014 11:11:56 +0800 Subject: [PATCH 196/196] Merge Bench4Q-Agent --- .../ScenarioParameters}/param1.txt | 0 .../345376a7-d01c-4faa-af89-4a3e1a182048.xml | 0 .../Scripts}/behaviorModel.xml | 32 +- .../Scripts}/forGoodRecord.xml | 0 .../Scripts}/goodForBatch.xml | 290 ++++----- .../Scripts}/goodForPage.xml | 0 {Scripts => Bench4Q-Agent/Scripts}/testJD.xml | 0 .../StorageTest}/testInput.txt | 0 .../StorageTest}/test_123.txt | 0 .../configure}/agent-config.properties | 0 .../descriptor.xml | 48 +- pom.xml => Bench4Q-Agent/pom.xml | 0 .../java/org/bench4q/agent/AgentServer.java | 128 ++-- .../main/java/org/bench4q/agent/Main.java | 0 .../org/bench4q/agent/api/HomeController.java | 98 +-- .../bench4q/agent/api/PluginController.java | 162 ++--- .../org/bench4q/agent/api/TestController.java | 0 .../agent/datacollector/DataCollector.java | 0 .../impl/AbstractDataCollector.java | 0 .../impl/BehaviorResultCollector.java | 10 +- .../impl/BehaviorStatusCodeResult.java | 102 ++-- .../impl/PageResultCollector.java | 220 +++---- .../impl/ScenarioResultCollector.java | 556 +++++++++--------- .../helper/ApplicationContextHelper.java | 52 +- .../ParameterFileCollector.java | 0 .../agent/parameterization/SessionObject.java | 0 .../impl/InstanceControler.java | 0 .../impl/MyFileClassLoader.java | 0 .../parameterization/impl/Para_File.java | 0 .../impl/Para_GetEletronicCombine.java | 0 .../impl/Para_IteratorNumber.java | 0 .../impl/Para_RandomNumber.java | 0 .../parameterization/impl/Para_Table.java | 0 .../parameterization/impl/Para_Table.xml | 0 .../impl/Para_UniqueNumber.java | 0 .../impl/Para_UserNameAndPassword.java | 0 .../impl/ParameterThreadOption.java | 0 .../impl/ParameterizationParser.java | 0 .../impl/ParametersFactory.java | 0 .../org/bench4q/agent/plugin/Behavior.java | 22 +- .../bench4q/agent/plugin/BehaviorInfo.java | 46 +- .../org/bench4q/agent/plugin/ClassHelper.java | 248 ++++---- .../org/bench4q/agent/plugin/Parameter.java | 24 +- .../bench4q/agent/plugin/ParameterInfo.java | 46 +- .../java/org/bench4q/agent/plugin/Plugin.java | 24 +- .../org/bench4q/agent/plugin/PluginInfo.java | 64 +- .../bench4q/agent/plugin/PluginManager.java | 538 ++++++++--------- .../bench4q/agent/plugin/TypeConverter.java | 88 +-- .../agent/plugin/basic/CommandLinePlugin.java | 178 +++--- .../plugin/basic/ConstantTimerPlugin.java | 54 +- .../bench4q/agent/plugin/basic/LogPlugin.java | 38 +- .../agent/plugin/basic/http/HttpPlugin.java | 0 .../plugin/basic/http/ParameterConstant.java | 0 .../plugin/result/CommandLineReturn.java | 14 +- .../agent/plugin/result/HttpReturn.java | 0 .../agent/plugin/result/LogReturn.java | 14 +- .../agent/plugin/result/PluginReturn.java | 0 .../agent/plugin/result/TimerReturn.java | 24 +- .../org/bench4q/agent/scenario/Batch.java | 86 +-- .../agent/scenario/BehaviorResult.java | 250 ++++---- .../java/org/bench4q/agent/scenario/Page.java | 0 .../bench4q/agent/scenario/PageResult.java | 154 ++--- .../org/bench4q/agent/scenario/Parameter.java | 46 +- .../org/bench4q/agent/scenario/Scenario.java | 0 .../agent/scenario/ScenarioContext.java | 0 .../agent/scenario/ScenarioEngine.java | 0 .../agent/scenario/SessionContext.java | 0 .../bench4q/agent/scenario/TestResult.java | 222 +++---- .../agent/scenario/TestResultItem.java | 186 +++--- .../org/bench4q/agent/scenario/UsePlugin.java | 64 +- .../org/bench4q/agent/scenario/Worker.java | 0 .../agent/scenario/behavior/Behavior.java | 0 .../scenario/behavior/BehaviorFactory.java | 28 +- .../scenario/behavior/TimerBehavior.java | 0 .../agent/scenario/behavior/UserBehavior.java | 0 .../agent/scenario/util/ParameterParser.java | 0 .../bench4q/agent/scenario/util/Table.java | 0 .../org/bench4q/agent/share/DealWithLog.java | 26 +- .../org/bench4q/agent/storage/Buffer.java | 114 ++-- .../agent/storage/DoubleBufferStorage.java | 314 +++++----- .../bench4q/agent/storage/HdfsStorage.java | 280 ++++----- .../bench4q/agent/storage/LocalStorage.java | 0 .../bench4q/agent/storage/MooseStorage.java | 34 +- .../org/bench4q/agent/storage/Storage.java | 0 .../bench4q/agent/storage/StorageHelper.java | 0 .../src}/main/resources/log4j.properties | 62 +- .../agent/config/application-context.xml | 0 .../agent/test/ExtractScenarioTest.java | 54 +- .../agent/test/HomeControllerTest.java | 10 +- .../java/org/bench4q/agent/test/MainTest.java | 0 .../agent/test/PluginControllerTest.java | 10 +- .../agent/test/TestWithScriptFile.java | 0 .../datastatistics/DetailStatisticsTest.java | 0 .../PageResultStatisticsTest.java | 0 .../ScenarioStatisticsTest.java | 0 .../bench4q/agent/test/model/ModelTest.java | 60 +- .../test/model/UserBehaviorModelTest.java | 52 +- .../parameterization/TEST_HelloThread.java | 0 .../test/parameterization/TEST_UserName.java | 0 .../Test_ParameterizationParser.java | 0 .../agent/test/plugin/Test_HttpPlugin.java | 0 .../test/scenario/Test_ScenarioContext.java | 0 .../scenario/utils/Test_ParameterParser.java | 0 .../utils/Test_RegularExpression.java | 0 .../test/storage/TestDoubleBufferStorage.java | 0 .../test/resources/test-storage-context.xml | 22 +- license.txt | 339 ----------- 107 files changed, 2597 insertions(+), 2936 deletions(-) rename {ScenarioParameters => Bench4Q-Agent/ScenarioParameters}/param1.txt (100%) rename {Scripts => Bench4Q-Agent/Scripts}/345376a7-d01c-4faa-af89-4a3e1a182048.xml (100%) rename {Scripts => Bench4Q-Agent/Scripts}/behaviorModel.xml (90%) rename {Scripts => Bench4Q-Agent/Scripts}/forGoodRecord.xml (100%) rename {Scripts => Bench4Q-Agent/Scripts}/goodForBatch.xml (95%) rename {Scripts => Bench4Q-Agent/Scripts}/goodForPage.xml (100%) rename {Scripts => Bench4Q-Agent/Scripts}/testJD.xml (100%) rename {StorageTest => Bench4Q-Agent/StorageTest}/testInput.txt (100%) rename {StorageTest => Bench4Q-Agent/StorageTest}/test_123.txt (100%) rename {configure => Bench4Q-Agent/configure}/agent-config.properties (100%) rename descriptor.xml => Bench4Q-Agent/descriptor.xml (95%) rename pom.xml => Bench4Q-Agent/pom.xml (100%) rename {src => Bench4Q-Agent/src}/main/java/org/bench4q/agent/AgentServer.java (95%) rename {src => Bench4Q-Agent/src}/main/java/org/bench4q/agent/Main.java (100%) rename {src => Bench4Q-Agent/src}/main/java/org/bench4q/agent/api/HomeController.java (97%) rename {src => Bench4Q-Agent/src}/main/java/org/bench4q/agent/api/PluginController.java (97%) rename {src => Bench4Q-Agent/src}/main/java/org/bench4q/agent/api/TestController.java (100%) rename {src => Bench4Q-Agent/src}/main/java/org/bench4q/agent/datacollector/DataCollector.java (100%) rename {src => Bench4Q-Agent/src}/main/java/org/bench4q/agent/datacollector/impl/AbstractDataCollector.java (100%) rename {src => Bench4Q-Agent/src}/main/java/org/bench4q/agent/datacollector/impl/BehaviorResultCollector.java (94%) rename {src => Bench4Q-Agent/src}/main/java/org/bench4q/agent/datacollector/impl/BehaviorStatusCodeResult.java (96%) rename {src => Bench4Q-Agent/src}/main/java/org/bench4q/agent/datacollector/impl/PageResultCollector.java (96%) rename {src => Bench4Q-Agent/src}/main/java/org/bench4q/agent/datacollector/impl/ScenarioResultCollector.java (97%) rename {src => Bench4Q-Agent/src}/main/java/org/bench4q/agent/helper/ApplicationContextHelper.java (96%) rename {src => Bench4Q-Agent/src}/main/java/org/bench4q/agent/parameterization/ParameterFileCollector.java (100%) rename {src => Bench4Q-Agent/src}/main/java/org/bench4q/agent/parameterization/SessionObject.java (100%) rename {src => Bench4Q-Agent/src}/main/java/org/bench4q/agent/parameterization/impl/InstanceControler.java (100%) rename {src => Bench4Q-Agent/src}/main/java/org/bench4q/agent/parameterization/impl/MyFileClassLoader.java (100%) rename {src => Bench4Q-Agent/src}/main/java/org/bench4q/agent/parameterization/impl/Para_File.java (100%) rename {src => Bench4Q-Agent/src}/main/java/org/bench4q/agent/parameterization/impl/Para_GetEletronicCombine.java (100%) rename {src => Bench4Q-Agent/src}/main/java/org/bench4q/agent/parameterization/impl/Para_IteratorNumber.java (100%) rename {src => Bench4Q-Agent/src}/main/java/org/bench4q/agent/parameterization/impl/Para_RandomNumber.java (100%) rename {src => Bench4Q-Agent/src}/main/java/org/bench4q/agent/parameterization/impl/Para_Table.java (100%) rename {src => Bench4Q-Agent/src}/main/java/org/bench4q/agent/parameterization/impl/Para_Table.xml (100%) rename {src => Bench4Q-Agent/src}/main/java/org/bench4q/agent/parameterization/impl/Para_UniqueNumber.java (100%) rename {src => Bench4Q-Agent/src}/main/java/org/bench4q/agent/parameterization/impl/Para_UserNameAndPassword.java (100%) rename {src => Bench4Q-Agent/src}/main/java/org/bench4q/agent/parameterization/impl/ParameterThreadOption.java (100%) rename {src => Bench4Q-Agent/src}/main/java/org/bench4q/agent/parameterization/impl/ParameterizationParser.java (100%) rename {src => Bench4Q-Agent/src}/main/java/org/bench4q/agent/parameterization/impl/ParametersFactory.java (100%) rename {src => Bench4Q-Agent/src}/main/java/org/bench4q/agent/plugin/Behavior.java (96%) rename {src => Bench4Q-Agent/src}/main/java/org/bench4q/agent/plugin/BehaviorInfo.java (94%) rename {src => Bench4Q-Agent/src}/main/java/org/bench4q/agent/plugin/ClassHelper.java (96%) rename {src => Bench4Q-Agent/src}/main/java/org/bench4q/agent/plugin/Parameter.java (96%) rename {src => Bench4Q-Agent/src}/main/java/org/bench4q/agent/plugin/ParameterInfo.java (93%) rename {src => Bench4Q-Agent/src}/main/java/org/bench4q/agent/plugin/Plugin.java (96%) rename {src => Bench4Q-Agent/src}/main/java/org/bench4q/agent/plugin/PluginInfo.java (94%) rename {src => Bench4Q-Agent/src}/main/java/org/bench4q/agent/plugin/PluginManager.java (96%) rename {src => Bench4Q-Agent/src}/main/java/org/bench4q/agent/plugin/TypeConverter.java (96%) rename {src => Bench4Q-Agent/src}/main/java/org/bench4q/agent/plugin/basic/CommandLinePlugin.java (96%) rename {src => Bench4Q-Agent/src}/main/java/org/bench4q/agent/plugin/basic/ConstantTimerPlugin.java (96%) rename {src => Bench4Q-Agent/src}/main/java/org/bench4q/agent/plugin/basic/LogPlugin.java (95%) rename {src => Bench4Q-Agent/src}/main/java/org/bench4q/agent/plugin/basic/http/HttpPlugin.java (100%) rename {src => Bench4Q-Agent/src}/main/java/org/bench4q/agent/plugin/basic/http/ParameterConstant.java (100%) rename {src => Bench4Q-Agent/src}/main/java/org/bench4q/agent/plugin/result/CommandLineReturn.java (96%) rename {src => Bench4Q-Agent/src}/main/java/org/bench4q/agent/plugin/result/HttpReturn.java (100%) rename {src => Bench4Q-Agent/src}/main/java/org/bench4q/agent/plugin/result/LogReturn.java (95%) rename {src => Bench4Q-Agent/src}/main/java/org/bench4q/agent/plugin/result/PluginReturn.java (100%) rename {src => Bench4Q-Agent/src}/main/java/org/bench4q/agent/plugin/result/TimerReturn.java (94%) rename {src => Bench4Q-Agent/src}/main/java/org/bench4q/agent/scenario/Batch.java (94%) rename {src => Bench4Q-Agent/src}/main/java/org/bench4q/agent/scenario/BehaviorResult.java (94%) rename {src => Bench4Q-Agent/src}/main/java/org/bench4q/agent/scenario/Page.java (100%) rename {src => Bench4Q-Agent/src}/main/java/org/bench4q/agent/scenario/PageResult.java (96%) rename {src => Bench4Q-Agent/src}/main/java/org/bench4q/agent/scenario/Parameter.java (93%) rename {src => Bench4Q-Agent/src}/main/java/org/bench4q/agent/scenario/Scenario.java (100%) rename {src => Bench4Q-Agent/src}/main/java/org/bench4q/agent/scenario/ScenarioContext.java (100%) rename {src => Bench4Q-Agent/src}/main/java/org/bench4q/agent/scenario/ScenarioEngine.java (100%) rename {src => Bench4Q-Agent/src}/main/java/org/bench4q/agent/scenario/SessionContext.java (100%) rename {src => Bench4Q-Agent/src}/main/java/org/bench4q/agent/scenario/TestResult.java (95%) rename {src => Bench4Q-Agent/src}/main/java/org/bench4q/agent/scenario/TestResultItem.java (94%) rename {src => Bench4Q-Agent/src}/main/java/org/bench4q/agent/scenario/UsePlugin.java (93%) rename {src => Bench4Q-Agent/src}/main/java/org/bench4q/agent/scenario/Worker.java (100%) rename {src => Bench4Q-Agent/src}/main/java/org/bench4q/agent/scenario/behavior/Behavior.java (100%) rename {src => Bench4Q-Agent/src}/main/java/org/bench4q/agent/scenario/behavior/BehaviorFactory.java (96%) rename {src => Bench4Q-Agent/src}/main/java/org/bench4q/agent/scenario/behavior/TimerBehavior.java (100%) rename {src => Bench4Q-Agent/src}/main/java/org/bench4q/agent/scenario/behavior/UserBehavior.java (100%) rename {src => Bench4Q-Agent/src}/main/java/org/bench4q/agent/scenario/util/ParameterParser.java (100%) rename {src => Bench4Q-Agent/src}/main/java/org/bench4q/agent/scenario/util/Table.java (100%) rename {src => Bench4Q-Agent/src}/main/java/org/bench4q/agent/share/DealWithLog.java (96%) rename {src => Bench4Q-Agent/src}/main/java/org/bench4q/agent/storage/Buffer.java (95%) rename {src => Bench4Q-Agent/src}/main/java/org/bench4q/agent/storage/DoubleBufferStorage.java (96%) rename {src => Bench4Q-Agent/src}/main/java/org/bench4q/agent/storage/HdfsStorage.java (96%) rename {src => Bench4Q-Agent/src}/main/java/org/bench4q/agent/storage/LocalStorage.java (100%) rename {src => Bench4Q-Agent/src}/main/java/org/bench4q/agent/storage/MooseStorage.java (94%) rename {src => Bench4Q-Agent/src}/main/java/org/bench4q/agent/storage/Storage.java (100%) rename {src => Bench4Q-Agent/src}/main/java/org/bench4q/agent/storage/StorageHelper.java (100%) rename {src => Bench4Q-Agent/src}/main/resources/log4j.properties (97%) rename {src => Bench4Q-Agent/src}/main/resources/org/bench4q/agent/config/application-context.xml (100%) rename {src => Bench4Q-Agent/src}/test/java/org/bench4q/agent/test/ExtractScenarioTest.java (96%) rename {src => Bench4Q-Agent/src}/test/java/org/bench4q/agent/test/HomeControllerTest.java (93%) rename {src => Bench4Q-Agent/src}/test/java/org/bench4q/agent/test/MainTest.java (100%) rename {src => Bench4Q-Agent/src}/test/java/org/bench4q/agent/test/PluginControllerTest.java (93%) rename {src => Bench4Q-Agent/src}/test/java/org/bench4q/agent/test/TestWithScriptFile.java (100%) rename {src => Bench4Q-Agent/src}/test/java/org/bench4q/agent/test/datastatistics/DetailStatisticsTest.java (100%) rename {src => Bench4Q-Agent/src}/test/java/org/bench4q/agent/test/datastatistics/PageResultStatisticsTest.java (100%) rename {src => Bench4Q-Agent/src}/test/java/org/bench4q/agent/test/datastatistics/ScenarioStatisticsTest.java (100%) rename {src => Bench4Q-Agent/src}/test/java/org/bench4q/agent/test/model/ModelTest.java (96%) rename {src => Bench4Q-Agent/src}/test/java/org/bench4q/agent/test/model/UserBehaviorModelTest.java (96%) rename {src => Bench4Q-Agent/src}/test/java/org/bench4q/agent/test/parameterization/TEST_HelloThread.java (100%) rename {src => Bench4Q-Agent/src}/test/java/org/bench4q/agent/test/parameterization/TEST_UserName.java (100%) rename {src => Bench4Q-Agent/src}/test/java/org/bench4q/agent/test/parameterization/Test_ParameterizationParser.java (100%) rename {src => Bench4Q-Agent/src}/test/java/org/bench4q/agent/test/plugin/Test_HttpPlugin.java (100%) rename {src => Bench4Q-Agent/src}/test/java/org/bench4q/agent/test/scenario/Test_ScenarioContext.java (100%) rename {src => Bench4Q-Agent/src}/test/java/org/bench4q/agent/test/scenario/utils/Test_ParameterParser.java (100%) rename {src => Bench4Q-Agent/src}/test/java/org/bench4q/agent/test/scenario/utils/Test_RegularExpression.java (100%) rename {src => Bench4Q-Agent/src}/test/java/org/bench4q/agent/test/storage/TestDoubleBufferStorage.java (100%) rename {src => Bench4Q-Agent/src}/test/resources/test-storage-context.xml (98%) delete mode 100644 license.txt diff --git a/ScenarioParameters/param1.txt b/Bench4Q-Agent/ScenarioParameters/param1.txt similarity index 100% rename from ScenarioParameters/param1.txt rename to Bench4Q-Agent/ScenarioParameters/param1.txt diff --git a/Scripts/345376a7-d01c-4faa-af89-4a3e1a182048.xml b/Bench4Q-Agent/Scripts/345376a7-d01c-4faa-af89-4a3e1a182048.xml similarity index 100% rename from Scripts/345376a7-d01c-4faa-af89-4a3e1a182048.xml rename to Bench4Q-Agent/Scripts/345376a7-d01c-4faa-af89-4a3e1a182048.xml diff --git a/Scripts/behaviorModel.xml b/Bench4Q-Agent/Scripts/behaviorModel.xml similarity index 90% rename from Scripts/behaviorModel.xml rename to Bench4Q-Agent/Scripts/behaviorModel.xml index 22f09364..136480d0 100644 --- a/Scripts/behaviorModel.xml +++ b/Bench4Q-Agent/Scripts/behaviorModel.xml @@ -1,17 +1,17 @@ - - 0 - Get - - - url - http://133.133.12.3:8080/Bench4QTestCase/testcase.html - - - - parameters - - - - USERBEHAVIOR - http + + 0 + Get + + + url + http://133.133.12.3:8080/Bench4QTestCase/testcase.html + + + + parameters + + + + USERBEHAVIOR + http \ No newline at end of file diff --git a/Scripts/forGoodRecord.xml b/Bench4Q-Agent/Scripts/forGoodRecord.xml similarity index 100% rename from Scripts/forGoodRecord.xml rename to Bench4Q-Agent/Scripts/forGoodRecord.xml diff --git a/Scripts/goodForBatch.xml b/Bench4Q-Agent/Scripts/goodForBatch.xml similarity index 95% rename from Scripts/goodForBatch.xml rename to Bench4Q-Agent/Scripts/goodForBatch.xml index 985d6fa6..8be2d6e7 100644 --- a/Scripts/goodForBatch.xml +++ b/Bench4Q-Agent/Scripts/goodForBatch.xml @@ -1,146 +1,146 @@ - - - - - - - 1 - Get - - - url - http://133.133.12.3:8080/Bench4QTestCase/testcase.html - - - - parameters - - - - http - - - 2 - 0 - -1 - - - - - 0 - Sleep - - - time - 2500 - - - timer - - - -1 - 1 - -1 - - - - - 3 - Get - - - url - http://133.133.12.3:8080/Bench4QTestCase/images/3.jpg - - - - parameters - - - - http - - - 4 - Get - - - url - http://133.133.12.3:8080/Bench4QTestCase/script/agentTable.js - - - - parameters - - - - http - - - 5 - Get - - - url - http://133.133.12.3:8080/Bench4QTestCase/script/base.js - - - - parameters - - - - http - - - 6 - Get - - - url - http://133.133.12.3:8080/Bench4QTestCase/images/1.jpg - - - - parameters - - - - http - - - 7 - Get - - - url - http://133.133.12.3:8080/Bench4QTestCase/images/2.jpg - - - - parameters - - - - http - - - -1 - 2 - 0 - - - 0 - - - http - Http - - - - timer - ConstantTimer - - - + + + + + + + 1 + Get + + + url + http://133.133.12.3:8080/Bench4QTestCase/testcase.html + + + + parameters + + + + http + + + 2 + 0 + -1 + + + + + 0 + Sleep + + + time + 2500 + + + timer + + + -1 + 1 + -1 + + + + + 3 + Get + + + url + http://133.133.12.3:8080/Bench4QTestCase/images/3.jpg + + + + parameters + + + + http + + + 4 + Get + + + url + http://133.133.12.3:8080/Bench4QTestCase/script/agentTable.js + + + + parameters + + + + http + + + 5 + Get + + + url + http://133.133.12.3:8080/Bench4QTestCase/script/base.js + + + + parameters + + + + http + + + 6 + Get + + + url + http://133.133.12.3:8080/Bench4QTestCase/images/1.jpg + + + + parameters + + + + http + + + 7 + Get + + + url + http://133.133.12.3:8080/Bench4QTestCase/images/2.jpg + + + + parameters + + + + http + + + -1 + 2 + 0 + + + 0 + + + http + Http + + + + timer + ConstantTimer + + + \ No newline at end of file diff --git a/Scripts/goodForPage.xml b/Bench4Q-Agent/Scripts/goodForPage.xml similarity index 100% rename from Scripts/goodForPage.xml rename to Bench4Q-Agent/Scripts/goodForPage.xml diff --git a/Scripts/testJD.xml b/Bench4Q-Agent/Scripts/testJD.xml similarity index 100% rename from Scripts/testJD.xml rename to Bench4Q-Agent/Scripts/testJD.xml diff --git a/StorageTest/testInput.txt b/Bench4Q-Agent/StorageTest/testInput.txt similarity index 100% rename from StorageTest/testInput.txt rename to Bench4Q-Agent/StorageTest/testInput.txt diff --git a/StorageTest/test_123.txt b/Bench4Q-Agent/StorageTest/test_123.txt similarity index 100% rename from StorageTest/test_123.txt rename to Bench4Q-Agent/StorageTest/test_123.txt diff --git a/configure/agent-config.properties b/Bench4Q-Agent/configure/agent-config.properties similarity index 100% rename from configure/agent-config.properties rename to Bench4Q-Agent/configure/agent-config.properties diff --git a/descriptor.xml b/Bench4Q-Agent/descriptor.xml similarity index 95% rename from descriptor.xml rename to Bench4Q-Agent/descriptor.xml index a7581f81..ca85606d 100644 --- a/descriptor.xml +++ b/Bench4Q-Agent/descriptor.xml @@ -1,25 +1,25 @@ - - - publish - - tar.gz - - false - - - lib - false - false - runtime - - - - - target/bench4q-agent.jar - / - - + + + publish + + tar.gz + + false + + + lib + false + false + runtime + + + + + target/bench4q-agent.jar + / + + \ No newline at end of file diff --git a/pom.xml b/Bench4Q-Agent/pom.xml similarity index 100% rename from pom.xml rename to Bench4Q-Agent/pom.xml diff --git a/src/main/java/org/bench4q/agent/AgentServer.java b/Bench4Q-Agent/src/main/java/org/bench4q/agent/AgentServer.java similarity index 95% rename from src/main/java/org/bench4q/agent/AgentServer.java rename to Bench4Q-Agent/src/main/java/org/bench4q/agent/AgentServer.java index 0f21e431..66a95382 100644 --- a/src/main/java/org/bench4q/agent/AgentServer.java +++ b/Bench4Q-Agent/src/main/java/org/bench4q/agent/AgentServer.java @@ -1,64 +1,64 @@ -package org.bench4q.agent; - -import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.servlet.ServletContextHandler; -import org.eclipse.jetty.servlet.ServletHolder; -import org.springframework.web.servlet.DispatcherServlet; - -public class AgentServer { - private Server server; - private int port; - - private Server getServer() { - return server; - } - - private void setServer(Server server) { - this.server = server; - } - - private int getPort() { - return port; - } - - private void setPort(int port) { - this.port = port; - } - - public AgentServer(int port) { - this.setPort(port); - } - - public boolean start() { - try { - this.setServer(new Server(this.getPort())); - ServletContextHandler servletContextHandler = new ServletContextHandler(); - ServletHolder servletHolder = servletContextHandler.addServlet( - DispatcherServlet.class, "/"); - servletHolder - .setInitParameter("contextConfigLocation", - "classpath*:/org/bench4q/agent/config/application-context.xml"); - servletHolder.setInitOrder(1); - this.getServer().setHandler(servletContextHandler); - this.getServer().start(); - return true; - } catch (Exception e) { - e.printStackTrace(); - return false; - } - } - - public boolean stop() { - try { - if (this.getServer() != null) { - this.getServer().stop(); - } - return true; - } catch (Exception e) { - e.printStackTrace(); - return false; - } finally { - this.setServer(null); - } - } -} +package org.bench4q.agent; + +import org.eclipse.jetty.server.Server; +import org.eclipse.jetty.servlet.ServletContextHandler; +import org.eclipse.jetty.servlet.ServletHolder; +import org.springframework.web.servlet.DispatcherServlet; + +public class AgentServer { + private Server server; + private int port; + + private Server getServer() { + return server; + } + + private void setServer(Server server) { + this.server = server; + } + + private int getPort() { + return port; + } + + private void setPort(int port) { + this.port = port; + } + + public AgentServer(int port) { + this.setPort(port); + } + + public boolean start() { + try { + this.setServer(new Server(this.getPort())); + ServletContextHandler servletContextHandler = new ServletContextHandler(); + ServletHolder servletHolder = servletContextHandler.addServlet( + DispatcherServlet.class, "/"); + servletHolder + .setInitParameter("contextConfigLocation", + "classpath*:/org/bench4q/agent/config/application-context.xml"); + servletHolder.setInitOrder(1); + this.getServer().setHandler(servletContextHandler); + this.getServer().start(); + return true; + } catch (Exception e) { + e.printStackTrace(); + return false; + } + } + + public boolean stop() { + try { + if (this.getServer() != null) { + this.getServer().stop(); + } + return true; + } catch (Exception e) { + e.printStackTrace(); + return false; + } finally { + this.setServer(null); + } + } +} diff --git a/src/main/java/org/bench4q/agent/Main.java b/Bench4Q-Agent/src/main/java/org/bench4q/agent/Main.java similarity index 100% rename from src/main/java/org/bench4q/agent/Main.java rename to Bench4Q-Agent/src/main/java/org/bench4q/agent/Main.java diff --git a/src/main/java/org/bench4q/agent/api/HomeController.java b/Bench4Q-Agent/src/main/java/org/bench4q/agent/api/HomeController.java similarity index 97% rename from src/main/java/org/bench4q/agent/api/HomeController.java rename to Bench4Q-Agent/src/main/java/org/bench4q/agent/api/HomeController.java index 6c3599cd..22d6d739 100644 --- a/src/main/java/org/bench4q/agent/api/HomeController.java +++ b/Bench4Q-Agent/src/main/java/org/bench4q/agent/api/HomeController.java @@ -1,49 +1,49 @@ -package org.bench4q.agent.api; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Map; -import java.util.UUID; - -import org.bench4q.agent.scenario.ScenarioContext; -import org.bench4q.agent.scenario.ScenarioEngine; -import org.bench4q.share.models.agent.ServerStatusModel; -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.ResponseBody; - -@Controller -@RequestMapping("/") -public class HomeController { - private ScenarioEngine scenarioEngine; - - private ScenarioEngine getScenarioEngine() { - return scenarioEngine; - } - - @Autowired - private void setScenarioEngine(ScenarioEngine scenarioEngine) { - this.scenarioEngine = scenarioEngine; - } - - @RequestMapping(method = { RequestMethod.GET, RequestMethod.POST }) - @ResponseBody - public ServerStatusModel index() { - ServerStatusModel serverStatusModel = new ServerStatusModel(); - serverStatusModel.setFinishedTests(new ArrayList()); - serverStatusModel.setRunningTests(new ArrayList()); - Map contexts = new HashMap( - getScenarioEngine().getRunningTests()); - for (UUID key : contexts.keySet()) { - ScenarioContext value = contexts.get(key); - if (value.isFinished()) { - serverStatusModel.getFinishedTests().add(key); - } else { - serverStatusModel.getRunningTests().add(key); - } - } - return serverStatusModel; - } -} +package org.bench4q.agent.api; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; + +import org.bench4q.agent.scenario.ScenarioContext; +import org.bench4q.agent.scenario.ScenarioEngine; +import org.bench4q.share.models.agent.ServerStatusModel; +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.ResponseBody; + +@Controller +@RequestMapping("/") +public class HomeController { + private ScenarioEngine scenarioEngine; + + private ScenarioEngine getScenarioEngine() { + return scenarioEngine; + } + + @Autowired + private void setScenarioEngine(ScenarioEngine scenarioEngine) { + this.scenarioEngine = scenarioEngine; + } + + @RequestMapping(method = { RequestMethod.GET, RequestMethod.POST }) + @ResponseBody + public ServerStatusModel index() { + ServerStatusModel serverStatusModel = new ServerStatusModel(); + serverStatusModel.setFinishedTests(new ArrayList()); + serverStatusModel.setRunningTests(new ArrayList()); + Map contexts = new HashMap( + getScenarioEngine().getRunningTests()); + for (UUID key : contexts.keySet()) { + ScenarioContext value = contexts.get(key); + if (value.isFinished()) { + serverStatusModel.getFinishedTests().add(key); + } else { + serverStatusModel.getRunningTests().add(key); + } + } + return serverStatusModel; + } +} diff --git a/src/main/java/org/bench4q/agent/api/PluginController.java b/Bench4Q-Agent/src/main/java/org/bench4q/agent/api/PluginController.java similarity index 97% rename from src/main/java/org/bench4q/agent/api/PluginController.java rename to Bench4Q-Agent/src/main/java/org/bench4q/agent/api/PluginController.java index 244a08ec..f903984b 100644 --- a/src/main/java/org/bench4q/agent/api/PluginController.java +++ b/Bench4Q-Agent/src/main/java/org/bench4q/agent/api/PluginController.java @@ -1,81 +1,81 @@ -package org.bench4q.agent.api; - -import java.util.ArrayList; -import java.util.List; - -import org.bench4q.agent.plugin.BehaviorInfo; -import org.bench4q.agent.plugin.ParameterInfo; -import org.bench4q.agent.plugin.PluginInfo; -import org.bench4q.agent.plugin.PluginManager; -import org.bench4q.share.models.agent.BehaviorInfoModel; -import org.bench4q.share.models.agent.ParameterInfoModel; -import org.bench4q.share.models.agent.PluginInfoListModel; -import org.bench4q.share.models.agent.PluginInfoModel; -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.ResponseBody; - -@Controller -@RequestMapping("/plugin") -public class PluginController { - private PluginManager pluginManager; - - public PluginManager getPluginManager() { - return pluginManager; - } - - @Autowired - public void setPluginManager(PluginManager pluginManager) { - this.pluginManager = pluginManager; - } - - @RequestMapping(method = RequestMethod.GET) - @ResponseBody - public PluginInfoListModel list() { - List pluginInfos = this.getPluginManager().getPluginInfo(); - PluginInfoListModel pluginInfoListModel = new PluginInfoListModel(); - pluginInfoListModel.setPlugins(new ArrayList()); - for (PluginInfo pluginInfo : pluginInfos) { - PluginInfoModel pluginInfoModel = buildPluginInfoModel(pluginInfo); - pluginInfoListModel.getPlugins().add(pluginInfoModel); - } - return pluginInfoListModel; - } - - private PluginInfoModel buildPluginInfoModel(PluginInfo pluginInfo) { - PluginInfoModel pluginInfoModel = new PluginInfoModel(); - pluginInfoModel.setName(pluginInfo.getName()); - pluginInfoModel.setParameters(new ArrayList()); - for (ParameterInfo param : pluginInfo.getParameters()) { - ParameterInfoModel model = buildParameterInfoModel(param); - pluginInfoModel.getParameters().add(model); - } - pluginInfoModel.setBehaviors(new ArrayList()); - for (BehaviorInfo behaviorInfo : pluginInfo.getBehaviors()) { - BehaviorInfoModel behaviorInfoModel = buildBehaviorInfoModel(behaviorInfo); - pluginInfoModel.getBehaviors().add(behaviorInfoModel); - } - return pluginInfoModel; - } - - private BehaviorInfoModel buildBehaviorInfoModel(BehaviorInfo behaviorInfo) { - BehaviorInfoModel behaviorInfoModel = new BehaviorInfoModel(); - behaviorInfoModel.setName(behaviorInfo.getName()); - behaviorInfoModel.setParameters(new ArrayList()); - for (ParameterInfo param : behaviorInfo.getParameters()) { - ParameterInfoModel model = buildParameterInfoModel(param); - behaviorInfoModel.getParameters().add(model); - } - return behaviorInfoModel; - } - - private ParameterInfoModel buildParameterInfoModel(ParameterInfo param) { - ParameterInfoModel model = new ParameterInfoModel(); - model.setName(param.getName()); - model.setType(param.getType()); - return model; - } - -} +package org.bench4q.agent.api; + +import java.util.ArrayList; +import java.util.List; + +import org.bench4q.agent.plugin.BehaviorInfo; +import org.bench4q.agent.plugin.ParameterInfo; +import org.bench4q.agent.plugin.PluginInfo; +import org.bench4q.agent.plugin.PluginManager; +import org.bench4q.share.models.agent.BehaviorInfoModel; +import org.bench4q.share.models.agent.ParameterInfoModel; +import org.bench4q.share.models.agent.PluginInfoListModel; +import org.bench4q.share.models.agent.PluginInfoModel; +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.ResponseBody; + +@Controller +@RequestMapping("/plugin") +public class PluginController { + private PluginManager pluginManager; + + public PluginManager getPluginManager() { + return pluginManager; + } + + @Autowired + public void setPluginManager(PluginManager pluginManager) { + this.pluginManager = pluginManager; + } + + @RequestMapping(method = RequestMethod.GET) + @ResponseBody + public PluginInfoListModel list() { + List pluginInfos = this.getPluginManager().getPluginInfo(); + PluginInfoListModel pluginInfoListModel = new PluginInfoListModel(); + pluginInfoListModel.setPlugins(new ArrayList()); + for (PluginInfo pluginInfo : pluginInfos) { + PluginInfoModel pluginInfoModel = buildPluginInfoModel(pluginInfo); + pluginInfoListModel.getPlugins().add(pluginInfoModel); + } + return pluginInfoListModel; + } + + private PluginInfoModel buildPluginInfoModel(PluginInfo pluginInfo) { + PluginInfoModel pluginInfoModel = new PluginInfoModel(); + pluginInfoModel.setName(pluginInfo.getName()); + pluginInfoModel.setParameters(new ArrayList()); + for (ParameterInfo param : pluginInfo.getParameters()) { + ParameterInfoModel model = buildParameterInfoModel(param); + pluginInfoModel.getParameters().add(model); + } + pluginInfoModel.setBehaviors(new ArrayList()); + for (BehaviorInfo behaviorInfo : pluginInfo.getBehaviors()) { + BehaviorInfoModel behaviorInfoModel = buildBehaviorInfoModel(behaviorInfo); + pluginInfoModel.getBehaviors().add(behaviorInfoModel); + } + return pluginInfoModel; + } + + private BehaviorInfoModel buildBehaviorInfoModel(BehaviorInfo behaviorInfo) { + BehaviorInfoModel behaviorInfoModel = new BehaviorInfoModel(); + behaviorInfoModel.setName(behaviorInfo.getName()); + behaviorInfoModel.setParameters(new ArrayList()); + for (ParameterInfo param : behaviorInfo.getParameters()) { + ParameterInfoModel model = buildParameterInfoModel(param); + behaviorInfoModel.getParameters().add(model); + } + return behaviorInfoModel; + } + + private ParameterInfoModel buildParameterInfoModel(ParameterInfo param) { + ParameterInfoModel model = new ParameterInfoModel(); + model.setName(param.getName()); + model.setType(param.getType()); + return model; + } + +} diff --git a/src/main/java/org/bench4q/agent/api/TestController.java b/Bench4Q-Agent/src/main/java/org/bench4q/agent/api/TestController.java similarity index 100% rename from src/main/java/org/bench4q/agent/api/TestController.java rename to Bench4Q-Agent/src/main/java/org/bench4q/agent/api/TestController.java diff --git a/src/main/java/org/bench4q/agent/datacollector/DataCollector.java b/Bench4Q-Agent/src/main/java/org/bench4q/agent/datacollector/DataCollector.java similarity index 100% rename from src/main/java/org/bench4q/agent/datacollector/DataCollector.java rename to Bench4Q-Agent/src/main/java/org/bench4q/agent/datacollector/DataCollector.java diff --git a/src/main/java/org/bench4q/agent/datacollector/impl/AbstractDataCollector.java b/Bench4Q-Agent/src/main/java/org/bench4q/agent/datacollector/impl/AbstractDataCollector.java similarity index 100% rename from src/main/java/org/bench4q/agent/datacollector/impl/AbstractDataCollector.java rename to Bench4Q-Agent/src/main/java/org/bench4q/agent/datacollector/impl/AbstractDataCollector.java diff --git a/src/main/java/org/bench4q/agent/datacollector/impl/BehaviorResultCollector.java b/Bench4Q-Agent/src/main/java/org/bench4q/agent/datacollector/impl/BehaviorResultCollector.java similarity index 94% rename from src/main/java/org/bench4q/agent/datacollector/impl/BehaviorResultCollector.java rename to Bench4Q-Agent/src/main/java/org/bench4q/agent/datacollector/impl/BehaviorResultCollector.java index 82db2c4b..09cd8dab 100644 --- a/src/main/java/org/bench4q/agent/datacollector/impl/BehaviorResultCollector.java +++ b/Bench4Q-Agent/src/main/java/org/bench4q/agent/datacollector/impl/BehaviorResultCollector.java @@ -1,5 +1,5 @@ -package org.bench4q.agent.datacollector.impl; - -public class BehaviorResultCollector { - -} +package org.bench4q.agent.datacollector.impl; + +public class BehaviorResultCollector { + +} diff --git a/src/main/java/org/bench4q/agent/datacollector/impl/BehaviorStatusCodeResult.java b/Bench4Q-Agent/src/main/java/org/bench4q/agent/datacollector/impl/BehaviorStatusCodeResult.java similarity index 96% rename from src/main/java/org/bench4q/agent/datacollector/impl/BehaviorStatusCodeResult.java rename to Bench4Q-Agent/src/main/java/org/bench4q/agent/datacollector/impl/BehaviorStatusCodeResult.java index 771aaaa0..5fe233de 100644 --- a/src/main/java/org/bench4q/agent/datacollector/impl/BehaviorStatusCodeResult.java +++ b/Bench4Q-Agent/src/main/java/org/bench4q/agent/datacollector/impl/BehaviorStatusCodeResult.java @@ -1,52 +1,52 @@ -package org.bench4q.agent.datacollector.impl; - -import java.lang.reflect.Field; - -public class BehaviorStatusCodeResult { - public long count; - public long contentLength; - public long minResponseTime; - public long maxResponseTime; - public long totalResponseTimeThisTime; - public String contentType; - - public BehaviorStatusCodeResult(String contentType) { - this.totalResponseTimeThisTime = 0; - this.contentType = contentType; - this.count = 0; - this.contentLength = 0; - this.minResponseTime = Long.MAX_VALUE; - this.maxResponseTime = Long.MIN_VALUE; - } - - public static boolean isSuccess(int statusCode) { - return statusCode == 200; - } - - public boolean equals(Object expectedObj) { - Field[] fields = this.getClass().getDeclaredFields(); - boolean equal = true; - try { - for (Field field : fields) { - field.setAccessible(true); - if (field.getName().equals("contentType")) { - field.get(expectedObj).equals(field.get(this)); - continue; - } - if (field.getLong(this) != field.getLong(expectedObj)) { - System.out.println(field.getName() - + " is diferent, this is " + field.getLong(this) - + ", and the expected is " - + field.getLong(expectedObj)); - equal = false; - } - - } - } catch (Exception e) { - e.printStackTrace(); - equal = false; - - } - return equal; - } +package org.bench4q.agent.datacollector.impl; + +import java.lang.reflect.Field; + +public class BehaviorStatusCodeResult { + public long count; + public long contentLength; + public long minResponseTime; + public long maxResponseTime; + public long totalResponseTimeThisTime; + public String contentType; + + public BehaviorStatusCodeResult(String contentType) { + this.totalResponseTimeThisTime = 0; + this.contentType = contentType; + this.count = 0; + this.contentLength = 0; + this.minResponseTime = Long.MAX_VALUE; + this.maxResponseTime = Long.MIN_VALUE; + } + + public static boolean isSuccess(int statusCode) { + return statusCode == 200; + } + + public boolean equals(Object expectedObj) { + Field[] fields = this.getClass().getDeclaredFields(); + boolean equal = true; + try { + for (Field field : fields) { + field.setAccessible(true); + if (field.getName().equals("contentType")) { + field.get(expectedObj).equals(field.get(this)); + continue; + } + if (field.getLong(this) != field.getLong(expectedObj)) { + System.out.println(field.getName() + + " is diferent, this is " + field.getLong(this) + + ", and the expected is " + + field.getLong(expectedObj)); + equal = false; + } + + } + } catch (Exception e) { + e.printStackTrace(); + equal = false; + + } + return equal; + } } \ No newline at end of file diff --git a/src/main/java/org/bench4q/agent/datacollector/impl/PageResultCollector.java b/Bench4Q-Agent/src/main/java/org/bench4q/agent/datacollector/impl/PageResultCollector.java similarity index 96% rename from src/main/java/org/bench4q/agent/datacollector/impl/PageResultCollector.java rename to Bench4Q-Agent/src/main/java/org/bench4q/agent/datacollector/impl/PageResultCollector.java index 7638549f..f046c746 100644 --- a/src/main/java/org/bench4q/agent/datacollector/impl/PageResultCollector.java +++ b/Bench4Q-Agent/src/main/java/org/bench4q/agent/datacollector/impl/PageResultCollector.java @@ -1,110 +1,110 @@ -package org.bench4q.agent.datacollector.impl; - -import java.util.Date; -import java.util.HashMap; -import java.util.Map; - -import org.bench4q.agent.scenario.BehaviorResult; -import org.bench4q.agent.scenario.PageResult; -import org.bench4q.share.models.agent.statistics.AgentPageBriefModel; - -public class PageResultCollector extends AbstractDataCollector { - Map pageBriefMap; - - private Map getPageBriefMap() { - return pageBriefMap; - } - - private void setPageBriefMap(Map pageBriefMap) { - this.pageBriefMap = pageBriefMap; - } - - public PageResultCollector() { - this.setPageBriefMap(new HashMap()); - } - - public void add(PageResult pageResult) { - if (pageResult == null || pageResult.getPageId() < 0) { - return; - } - PageBrief pageBrief = guardTheValueOfThePageIdExists(pageResult - .getPageId()); - pageBrief.countThisTime++; - pageBrief.countFromBegin++; - pageBrief.totalResponseTimeThisTime += pageResult.getExecuteRange(); - pageBrief.latesTimeResponseTime = pageResult.getExecuteRange(); - if (pageResult.getExecuteRange() > pageBrief.maxResponseTimeFromBegin) { - pageBrief.maxResponseTimeFromBegin = pageResult.getExecuteRange(); - } - if (pageResult.getExecuteRange() < pageBrief.minResponseTimeFromBegin) { - pageBrief.minResponseTimeFromBegin = pageResult.getExecuteRange(); - } - } - - private synchronized PageBrief guardTheValueOfThePageIdExists(int pageId) { - if (!this.getPageBriefMap().containsKey(pageId)) { - this.getPageBriefMap().put(pageId, new PageBrief()); - } - return this.getPageBriefMap().get(pageId); - } - - public Object getPageBriefStatistics(int pageId) { - PageBrief pageBrief = guardTheValueOfThePageIdExists(pageId); - AgentPageBriefModel result = new AgentPageBriefModel(); - result.setCountFromBegin(pageBrief.countFromBegin); - result.setCountThisTime(pageBrief.countThisTime); - result.setMaxResponseTimeFromBegin(pageBrief.maxResponseTimeFromBegin); - result.setMinResponseTimeFromBegin(pageBrief.minResponseTimeFromBegin); - result.setTotalResponseTimeThisTime(pageBrief.totalResponseTimeThisTime); - result.setPageId(pageId); - long nowTime = new Date().getTime(); - result.setTimeFrame(nowTime - pageBrief.lastSampleTime); - result.setLatestResponseTime(pageBrief.latesTimeResponseTime); - pageBrief.resetTemperatyField(); - return result; - } - - @Override - public void add(BehaviorResult behaviorResult) { - } - - @Override - protected String calculateSavePath(BehaviorResult behaviorResult) { - return null; - } - - @Override - public Object getScenarioBriefStatistics() { - return null; - } - - @Override - public Map getBehaviorBriefStatistics( - int id) { - return null; - } - - public class PageBrief { - public long lastSampleTime; - public long countThisTime; - public long totalResponseTimeThisTime; - public long maxResponseTimeFromBegin; - public long minResponseTimeFromBegin; - public long countFromBegin; - public long latesTimeResponseTime; - - public PageBrief() { - resetTemperatyField(); - this.maxResponseTimeFromBegin = Long.MIN_VALUE; - this.minResponseTimeFromBegin = Long.MAX_VALUE; - this.countFromBegin = 0; - this.latesTimeResponseTime = 0; - } - - public void resetTemperatyField() { - this.lastSampleTime = new Date().getTime(); - this.countThisTime = 0; - this.totalResponseTimeThisTime = 0; - } - } -} +package org.bench4q.agent.datacollector.impl; + +import java.util.Date; +import java.util.HashMap; +import java.util.Map; + +import org.bench4q.agent.scenario.BehaviorResult; +import org.bench4q.agent.scenario.PageResult; +import org.bench4q.share.models.agent.statistics.AgentPageBriefModel; + +public class PageResultCollector extends AbstractDataCollector { + Map pageBriefMap; + + private Map getPageBriefMap() { + return pageBriefMap; + } + + private void setPageBriefMap(Map pageBriefMap) { + this.pageBriefMap = pageBriefMap; + } + + public PageResultCollector() { + this.setPageBriefMap(new HashMap()); + } + + public void add(PageResult pageResult) { + if (pageResult == null || pageResult.getPageId() < 0) { + return; + } + PageBrief pageBrief = guardTheValueOfThePageIdExists(pageResult + .getPageId()); + pageBrief.countThisTime++; + pageBrief.countFromBegin++; + pageBrief.totalResponseTimeThisTime += pageResult.getExecuteRange(); + pageBrief.latesTimeResponseTime = pageResult.getExecuteRange(); + if (pageResult.getExecuteRange() > pageBrief.maxResponseTimeFromBegin) { + pageBrief.maxResponseTimeFromBegin = pageResult.getExecuteRange(); + } + if (pageResult.getExecuteRange() < pageBrief.minResponseTimeFromBegin) { + pageBrief.minResponseTimeFromBegin = pageResult.getExecuteRange(); + } + } + + private synchronized PageBrief guardTheValueOfThePageIdExists(int pageId) { + if (!this.getPageBriefMap().containsKey(pageId)) { + this.getPageBriefMap().put(pageId, new PageBrief()); + } + return this.getPageBriefMap().get(pageId); + } + + public Object getPageBriefStatistics(int pageId) { + PageBrief pageBrief = guardTheValueOfThePageIdExists(pageId); + AgentPageBriefModel result = new AgentPageBriefModel(); + result.setCountFromBegin(pageBrief.countFromBegin); + result.setCountThisTime(pageBrief.countThisTime); + result.setMaxResponseTimeFromBegin(pageBrief.maxResponseTimeFromBegin); + result.setMinResponseTimeFromBegin(pageBrief.minResponseTimeFromBegin); + result.setTotalResponseTimeThisTime(pageBrief.totalResponseTimeThisTime); + result.setPageId(pageId); + long nowTime = new Date().getTime(); + result.setTimeFrame(nowTime - pageBrief.lastSampleTime); + result.setLatestResponseTime(pageBrief.latesTimeResponseTime); + pageBrief.resetTemperatyField(); + return result; + } + + @Override + public void add(BehaviorResult behaviorResult) { + } + + @Override + protected String calculateSavePath(BehaviorResult behaviorResult) { + return null; + } + + @Override + public Object getScenarioBriefStatistics() { + return null; + } + + @Override + public Map getBehaviorBriefStatistics( + int id) { + return null; + } + + public class PageBrief { + public long lastSampleTime; + public long countThisTime; + public long totalResponseTimeThisTime; + public long maxResponseTimeFromBegin; + public long minResponseTimeFromBegin; + public long countFromBegin; + public long latesTimeResponseTime; + + public PageBrief() { + resetTemperatyField(); + this.maxResponseTimeFromBegin = Long.MIN_VALUE; + this.minResponseTimeFromBegin = Long.MAX_VALUE; + this.countFromBegin = 0; + this.latesTimeResponseTime = 0; + } + + public void resetTemperatyField() { + this.lastSampleTime = new Date().getTime(); + this.countThisTime = 0; + this.totalResponseTimeThisTime = 0; + } + } +} diff --git a/src/main/java/org/bench4q/agent/datacollector/impl/ScenarioResultCollector.java b/Bench4Q-Agent/src/main/java/org/bench4q/agent/datacollector/impl/ScenarioResultCollector.java similarity index 97% rename from src/main/java/org/bench4q/agent/datacollector/impl/ScenarioResultCollector.java rename to Bench4Q-Agent/src/main/java/org/bench4q/agent/datacollector/impl/ScenarioResultCollector.java index 04958f4d..557282d1 100644 --- a/src/main/java/org/bench4q/agent/datacollector/impl/ScenarioResultCollector.java +++ b/Bench4Q-Agent/src/main/java/org/bench4q/agent/datacollector/impl/ScenarioResultCollector.java @@ -1,278 +1,278 @@ -package org.bench4q.agent.datacollector.impl; - -import java.text.SimpleDateFormat; -import java.util.Collections; -import java.util.Date; -import java.util.HashMap; -import java.util.Map; -import java.util.UUID; - -import org.bench4q.agent.scenario.BehaviorResult; -import org.bench4q.agent.scenario.PageResult; -import org.bench4q.share.models.agent.statistics.AgentBriefStatusModel; - -/** - * This class collect the behavior result and statistic it. - * - * @author coderfengyun - * - */ -public class ScenarioResultCollector extends AbstractDataCollector { - private long timeOfPreviousCall; - private long failCountOfThisCall; - private long successCountOfThisCall; - private long totalResponseTimeOfThisCall; - private long maxResponseTimeOfThisCall; - private long minResponseTimeOfThisCall; - private long totalSqureResponseTimeOfThisCall; - private long cumulativeSucessfulCount; - private long cumulativeFailCount; - private static long TIME_UNIT = 1000; - private UUID testID; - private PageResultCollector pageResultCollector; - // The first integer is the behavior's id, and the second integer is - // the StatusCode of this behaviorResult. - private Map> detailMap; - - private void setTimeOfPreviousCall(long timeOfPreviousCall) { - this.timeOfPreviousCall = timeOfPreviousCall; - } - - private void setFailCountOfThisCall(long failCountOfThisCall) { - this.failCountOfThisCall = failCountOfThisCall; - } - - private long getSuccessCountOfThisCall() { - return successCountOfThisCall; - } - - private void setSuccessCountOfThisCall(long successCountOfThisCall) { - this.successCountOfThisCall = successCountOfThisCall; - } - - private void setTotalResponseTimeOfThisCall(long totalResponseTimeOfThisCall) { - this.totalResponseTimeOfThisCall = totalResponseTimeOfThisCall; - } - - private long getMaxResponseTimeOfThisCall() { - return maxResponseTimeOfThisCall; - } - - private void setMaxResponseTimeOfThisCall(long maxResponseTimeOfThisCall) { - this.maxResponseTimeOfThisCall = maxResponseTimeOfThisCall; - } - - private long getMinResponseTimeOfThisCall() { - return minResponseTimeOfThisCall; - } - - private void setMinResponseTimeOfThisCall(long minResponseTimeOfThisCall) { - this.minResponseTimeOfThisCall = minResponseTimeOfThisCall; - } - - private void setTotalSqureResponseTimeOfThisCall( - long totalSqureResponseTimeOfThisCall) { - this.totalSqureResponseTimeOfThisCall = totalSqureResponseTimeOfThisCall; - } - - private void setCumulativeSucessfulCount(long cumulativeSucessfulCount) { - this.cumulativeSucessfulCount = cumulativeSucessfulCount; - } - - private void setCumulativeFailCount(long cumulativeFailCount) { - this.cumulativeFailCount = cumulativeFailCount; - } - - private String getTestID() { - return testID == null ? "default" : testID.toString(); - } - - private void setTestID(UUID testID) { - this.testID = testID; - } - - private void setDetailMap( - Map> detailMap) { - this.detailMap = detailMap; - } - - private PageResultCollector getPageResultCollector() { - return pageResultCollector; - } - - private void setPageResultCollector(PageResultCollector pageResultCollector) { - this.pageResultCollector = pageResultCollector; - } - - public ScenarioResultCollector(UUID testId) { - this.setTestID(testId); - this.setPageResultCollector(new PageResultCollector()); - init(); - } - - private void init() { - reset(); - this.setCumulativeFailCount(0); - this.setCumulativeSucessfulCount(0); - this.setDetailMap(new HashMap>()); - } - - private void reset() { - this.setTimeOfPreviousCall(System.currentTimeMillis()); - this.setFailCountOfThisCall(0); - this.setMaxResponseTimeOfThisCall(Long.MIN_VALUE); - this.setMinResponseTimeOfThisCall(Long.MAX_VALUE); - this.setSuccessCountOfThisCall(0); - this.setTotalResponseTimeOfThisCall(0); - this.setTotalSqureResponseTimeOfThisCall(0); - } - - // /////////////////////////////// - // DataStatistics Interface start - // /////////////////////////////// - - public AgentBriefStatusModel getScenarioBriefStatistics() { - AgentBriefStatusModel result = new AgentBriefStatusModel(); - result.setTimeFrame(System.currentTimeMillis() - - this.timeOfPreviousCall); - if (this.getSuccessCountOfThisCall() == 0) { - result.setMaxResponseTime(0); - result.setMinResponseTime(0); - } else { - result.setMinResponseTime(this.minResponseTimeOfThisCall); - result.setMaxResponseTime(this.maxResponseTimeOfThisCall); - } - this.cumulativeSucessfulCount += this.successCountOfThisCall; - result.setSuccessCountFromBegin(this.cumulativeSucessfulCount); - this.cumulativeFailCount += this.failCountOfThisCall; - result.setFailCountFromBegin(this.cumulativeFailCount); - if (result.getTimeFrame() == 0) { - result.setSuccessThroughputThisTime(0); - result.setFailThroughputThisTime(0); - } else { - result.setSuccessThroughputThisTime(this.successCountOfThisCall - * TIME_UNIT / result.getTimeFrame()); - result.setFailThroughputThisTime(this.failCountOfThisCall - * TIME_UNIT / result.getTimeFrame()); - } - result.setTotalResponseTimeThisTime(this.totalResponseTimeOfThisCall); - result.setSuccessCountThisTime(this.successCountOfThisCall); - result.setFailCountThisTime(this.failCountOfThisCall); - result.setTotalSqureResponseTimeThisTime(this.totalSqureResponseTimeOfThisCall); - reset(); - return result; - } - - // /////////////////////////////// - // DataStatistics Interface end - // /////////////////////////////// - /** - * For the failed one, only the fail count statistics will be added, Others - * of this failed one will be ignored. - * - * @param behaviorResult - */ - - private void statisticScenarioBriefResult(BehaviorResult behaviorResult) { - if (behaviorResult.isSuccess()) { - this.successCountOfThisCall++; - this.totalResponseTimeOfThisCall += behaviorResult - .getResponseTime(); - this.totalSqureResponseTimeOfThisCall += ((long) behaviorResult - .getResponseTime()) * behaviorResult.getResponseTime(); - if (behaviorResult.getResponseTime() > this - .getMaxResponseTimeOfThisCall()) { - this.setMaxResponseTimeOfThisCall(behaviorResult - .getResponseTime()); - } - if (behaviorResult.getResponseTime() < this - .getMinResponseTimeOfThisCall()) { - this.setMinResponseTimeOfThisCall(behaviorResult - .getResponseTime()); - } - } else { - this.failCountOfThisCall++; - } - } - - private void statisticBehaviorBriefResult(BehaviorResult behaviorResult) { - insertWhenNotExist(behaviorResult); - Map detailStatusMap = this.detailMap - .get(behaviorResult.getBehaviorId()); - // TODO: there's a problem about concurrency - guardStatusMapExists(behaviorResult, detailStatusMap); - BehaviorStatusCodeResult statusCodeResult = detailStatusMap - .get(behaviorResult.getStatusCode()); - statusCodeResult.count++; - if (!behaviorResult.isSuccess()) { - statusCodeResult.maxResponseTime = 0; - statusCodeResult.minResponseTime = 0; - statusCodeResult.contentLength = 0; - statusCodeResult.totalResponseTimeThisTime = 0; - return; - } - statusCodeResult.contentLength += behaviorResult.getContentLength(); - statusCodeResult.totalResponseTimeThisTime += behaviorResult - .getResponseTime(); - if (behaviorResult.getResponseTime() > statusCodeResult.maxResponseTime) { - statusCodeResult.maxResponseTime = behaviorResult.getResponseTime(); - } - if (behaviorResult.getResponseTime() < statusCodeResult.minResponseTime) { - statusCodeResult.minResponseTime = behaviorResult.getResponseTime(); - } - } - - private synchronized void guardStatusMapExists( - BehaviorResult behaviorResult, - Map detailStatusMap) { - if (!detailStatusMap.containsKey(behaviorResult.getStatusCode())) { - detailStatusMap.put( - new Integer(behaviorResult.getStatusCode()), - new BehaviorStatusCodeResult(behaviorResult - .getContentType())); - } - } - - private synchronized void insertWhenNotExist(BehaviorResult behaviorResult) { - if (!this.detailMap.containsKey(behaviorResult.getBehaviorId())) { - this.detailMap.put(new Integer(behaviorResult.getBehaviorId()), - new HashMap()); - } - } - - @Override - protected String calculateSavePath(BehaviorResult behaviorResult) { - Date now = new Date(); - - return "DetailResults" + System.getProperty("file.separator") - + new SimpleDateFormat("yyyyMMdd").format(now) - + System.getProperty("file.separator") + this.getTestID() + "_" - + behaviorResult.getBehaviorId() + "_" - + new SimpleDateFormat("hhmm") + ".txt"; - } - - public void add(PageResult pageResult) { - this.getPageResultCollector().add(pageResult); - } - - @Override - public void add(BehaviorResult behaviorResult) { - super.add(behaviorResult); - statisticScenarioBriefResult(behaviorResult); - statisticBehaviorBriefResult(behaviorResult); - } - - @Override - public Map getBehaviorBriefStatistics( - int behaviorId) { - if (!this.detailMap.containsKey(behaviorId)) { - return null; - } - return Collections.unmodifiableMap(this.detailMap.get(behaviorId)); - } - - public Object getPageBriefStatistics(int pageId) { - return this.getPageResultCollector().getPageBriefStatistics(pageId); - } - -} +package org.bench4q.agent.datacollector.impl; + +import java.text.SimpleDateFormat; +import java.util.Collections; +import java.util.Date; +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; + +import org.bench4q.agent.scenario.BehaviorResult; +import org.bench4q.agent.scenario.PageResult; +import org.bench4q.share.models.agent.statistics.AgentBriefStatusModel; + +/** + * This class collect the behavior result and statistic it. + * + * @author coderfengyun + * + */ +public class ScenarioResultCollector extends AbstractDataCollector { + private long timeOfPreviousCall; + private long failCountOfThisCall; + private long successCountOfThisCall; + private long totalResponseTimeOfThisCall; + private long maxResponseTimeOfThisCall; + private long minResponseTimeOfThisCall; + private long totalSqureResponseTimeOfThisCall; + private long cumulativeSucessfulCount; + private long cumulativeFailCount; + private static long TIME_UNIT = 1000; + private UUID testID; + private PageResultCollector pageResultCollector; + // The first integer is the behavior's id, and the second integer is + // the StatusCode of this behaviorResult. + private Map> detailMap; + + private void setTimeOfPreviousCall(long timeOfPreviousCall) { + this.timeOfPreviousCall = timeOfPreviousCall; + } + + private void setFailCountOfThisCall(long failCountOfThisCall) { + this.failCountOfThisCall = failCountOfThisCall; + } + + private long getSuccessCountOfThisCall() { + return successCountOfThisCall; + } + + private void setSuccessCountOfThisCall(long successCountOfThisCall) { + this.successCountOfThisCall = successCountOfThisCall; + } + + private void setTotalResponseTimeOfThisCall(long totalResponseTimeOfThisCall) { + this.totalResponseTimeOfThisCall = totalResponseTimeOfThisCall; + } + + private long getMaxResponseTimeOfThisCall() { + return maxResponseTimeOfThisCall; + } + + private void setMaxResponseTimeOfThisCall(long maxResponseTimeOfThisCall) { + this.maxResponseTimeOfThisCall = maxResponseTimeOfThisCall; + } + + private long getMinResponseTimeOfThisCall() { + return minResponseTimeOfThisCall; + } + + private void setMinResponseTimeOfThisCall(long minResponseTimeOfThisCall) { + this.minResponseTimeOfThisCall = minResponseTimeOfThisCall; + } + + private void setTotalSqureResponseTimeOfThisCall( + long totalSqureResponseTimeOfThisCall) { + this.totalSqureResponseTimeOfThisCall = totalSqureResponseTimeOfThisCall; + } + + private void setCumulativeSucessfulCount(long cumulativeSucessfulCount) { + this.cumulativeSucessfulCount = cumulativeSucessfulCount; + } + + private void setCumulativeFailCount(long cumulativeFailCount) { + this.cumulativeFailCount = cumulativeFailCount; + } + + private String getTestID() { + return testID == null ? "default" : testID.toString(); + } + + private void setTestID(UUID testID) { + this.testID = testID; + } + + private void setDetailMap( + Map> detailMap) { + this.detailMap = detailMap; + } + + private PageResultCollector getPageResultCollector() { + return pageResultCollector; + } + + private void setPageResultCollector(PageResultCollector pageResultCollector) { + this.pageResultCollector = pageResultCollector; + } + + public ScenarioResultCollector(UUID testId) { + this.setTestID(testId); + this.setPageResultCollector(new PageResultCollector()); + init(); + } + + private void init() { + reset(); + this.setCumulativeFailCount(0); + this.setCumulativeSucessfulCount(0); + this.setDetailMap(new HashMap>()); + } + + private void reset() { + this.setTimeOfPreviousCall(System.currentTimeMillis()); + this.setFailCountOfThisCall(0); + this.setMaxResponseTimeOfThisCall(Long.MIN_VALUE); + this.setMinResponseTimeOfThisCall(Long.MAX_VALUE); + this.setSuccessCountOfThisCall(0); + this.setTotalResponseTimeOfThisCall(0); + this.setTotalSqureResponseTimeOfThisCall(0); + } + + // /////////////////////////////// + // DataStatistics Interface start + // /////////////////////////////// + + public AgentBriefStatusModel getScenarioBriefStatistics() { + AgentBriefStatusModel result = new AgentBriefStatusModel(); + result.setTimeFrame(System.currentTimeMillis() + - this.timeOfPreviousCall); + if (this.getSuccessCountOfThisCall() == 0) { + result.setMaxResponseTime(0); + result.setMinResponseTime(0); + } else { + result.setMinResponseTime(this.minResponseTimeOfThisCall); + result.setMaxResponseTime(this.maxResponseTimeOfThisCall); + } + this.cumulativeSucessfulCount += this.successCountOfThisCall; + result.setSuccessCountFromBegin(this.cumulativeSucessfulCount); + this.cumulativeFailCount += this.failCountOfThisCall; + result.setFailCountFromBegin(this.cumulativeFailCount); + if (result.getTimeFrame() == 0) { + result.setSuccessThroughputThisTime(0); + result.setFailThroughputThisTime(0); + } else { + result.setSuccessThroughputThisTime(this.successCountOfThisCall + * TIME_UNIT / result.getTimeFrame()); + result.setFailThroughputThisTime(this.failCountOfThisCall + * TIME_UNIT / result.getTimeFrame()); + } + result.setTotalResponseTimeThisTime(this.totalResponseTimeOfThisCall); + result.setSuccessCountThisTime(this.successCountOfThisCall); + result.setFailCountThisTime(this.failCountOfThisCall); + result.setTotalSqureResponseTimeThisTime(this.totalSqureResponseTimeOfThisCall); + reset(); + return result; + } + + // /////////////////////////////// + // DataStatistics Interface end + // /////////////////////////////// + /** + * For the failed one, only the fail count statistics will be added, Others + * of this failed one will be ignored. + * + * @param behaviorResult + */ + + private void statisticScenarioBriefResult(BehaviorResult behaviorResult) { + if (behaviorResult.isSuccess()) { + this.successCountOfThisCall++; + this.totalResponseTimeOfThisCall += behaviorResult + .getResponseTime(); + this.totalSqureResponseTimeOfThisCall += ((long) behaviorResult + .getResponseTime()) * behaviorResult.getResponseTime(); + if (behaviorResult.getResponseTime() > this + .getMaxResponseTimeOfThisCall()) { + this.setMaxResponseTimeOfThisCall(behaviorResult + .getResponseTime()); + } + if (behaviorResult.getResponseTime() < this + .getMinResponseTimeOfThisCall()) { + this.setMinResponseTimeOfThisCall(behaviorResult + .getResponseTime()); + } + } else { + this.failCountOfThisCall++; + } + } + + private void statisticBehaviorBriefResult(BehaviorResult behaviorResult) { + insertWhenNotExist(behaviorResult); + Map detailStatusMap = this.detailMap + .get(behaviorResult.getBehaviorId()); + // TODO: there's a problem about concurrency + guardStatusMapExists(behaviorResult, detailStatusMap); + BehaviorStatusCodeResult statusCodeResult = detailStatusMap + .get(behaviorResult.getStatusCode()); + statusCodeResult.count++; + if (!behaviorResult.isSuccess()) { + statusCodeResult.maxResponseTime = 0; + statusCodeResult.minResponseTime = 0; + statusCodeResult.contentLength = 0; + statusCodeResult.totalResponseTimeThisTime = 0; + return; + } + statusCodeResult.contentLength += behaviorResult.getContentLength(); + statusCodeResult.totalResponseTimeThisTime += behaviorResult + .getResponseTime(); + if (behaviorResult.getResponseTime() > statusCodeResult.maxResponseTime) { + statusCodeResult.maxResponseTime = behaviorResult.getResponseTime(); + } + if (behaviorResult.getResponseTime() < statusCodeResult.minResponseTime) { + statusCodeResult.minResponseTime = behaviorResult.getResponseTime(); + } + } + + private synchronized void guardStatusMapExists( + BehaviorResult behaviorResult, + Map detailStatusMap) { + if (!detailStatusMap.containsKey(behaviorResult.getStatusCode())) { + detailStatusMap.put( + new Integer(behaviorResult.getStatusCode()), + new BehaviorStatusCodeResult(behaviorResult + .getContentType())); + } + } + + private synchronized void insertWhenNotExist(BehaviorResult behaviorResult) { + if (!this.detailMap.containsKey(behaviorResult.getBehaviorId())) { + this.detailMap.put(new Integer(behaviorResult.getBehaviorId()), + new HashMap()); + } + } + + @Override + protected String calculateSavePath(BehaviorResult behaviorResult) { + Date now = new Date(); + + return "DetailResults" + System.getProperty("file.separator") + + new SimpleDateFormat("yyyyMMdd").format(now) + + System.getProperty("file.separator") + this.getTestID() + "_" + + behaviorResult.getBehaviorId() + "_" + + new SimpleDateFormat("hhmm") + ".txt"; + } + + public void add(PageResult pageResult) { + this.getPageResultCollector().add(pageResult); + } + + @Override + public void add(BehaviorResult behaviorResult) { + super.add(behaviorResult); + statisticScenarioBriefResult(behaviorResult); + statisticBehaviorBriefResult(behaviorResult); + } + + @Override + public Map getBehaviorBriefStatistics( + int behaviorId) { + if (!this.detailMap.containsKey(behaviorId)) { + return null; + } + return Collections.unmodifiableMap(this.detailMap.get(behaviorId)); + } + + public Object getPageBriefStatistics(int pageId) { + return this.getPageResultCollector().getPageBriefStatistics(pageId); + } + +} diff --git a/src/main/java/org/bench4q/agent/helper/ApplicationContextHelper.java b/Bench4Q-Agent/src/main/java/org/bench4q/agent/helper/ApplicationContextHelper.java similarity index 96% rename from src/main/java/org/bench4q/agent/helper/ApplicationContextHelper.java rename to Bench4Q-Agent/src/main/java/org/bench4q/agent/helper/ApplicationContextHelper.java index fcfa9dfc..4ace1b14 100644 --- a/src/main/java/org/bench4q/agent/helper/ApplicationContextHelper.java +++ b/Bench4Q-Agent/src/main/java/org/bench4q/agent/helper/ApplicationContextHelper.java @@ -1,26 +1,26 @@ -package org.bench4q.agent.helper; - -import org.springframework.beans.BeansException; -import org.springframework.context.ApplicationContext; -import org.springframework.context.ApplicationContextAware; -import org.springframework.stereotype.Component; - -@Component -public class ApplicationContextHelper implements ApplicationContextAware { - - private static ApplicationContext context; - - public static ApplicationContext getContext() { - return context; - } - - private void setContext(ApplicationContext context) { - ApplicationContextHelper.context = context; - } - - public void setApplicationContext(ApplicationContext applicationContext) - throws BeansException { - this.setContext(applicationContext); - } - -} +package org.bench4q.agent.helper; + +import org.springframework.beans.BeansException; +import org.springframework.context.ApplicationContext; +import org.springframework.context.ApplicationContextAware; +import org.springframework.stereotype.Component; + +@Component +public class ApplicationContextHelper implements ApplicationContextAware { + + private static ApplicationContext context; + + public static ApplicationContext getContext() { + return context; + } + + private void setContext(ApplicationContext context) { + ApplicationContextHelper.context = context; + } + + public void setApplicationContext(ApplicationContext applicationContext) + throws BeansException { + this.setContext(applicationContext); + } + +} diff --git a/src/main/java/org/bench4q/agent/parameterization/ParameterFileCollector.java b/Bench4Q-Agent/src/main/java/org/bench4q/agent/parameterization/ParameterFileCollector.java similarity index 100% rename from src/main/java/org/bench4q/agent/parameterization/ParameterFileCollector.java rename to Bench4Q-Agent/src/main/java/org/bench4q/agent/parameterization/ParameterFileCollector.java diff --git a/src/main/java/org/bench4q/agent/parameterization/SessionObject.java b/Bench4Q-Agent/src/main/java/org/bench4q/agent/parameterization/SessionObject.java similarity index 100% rename from src/main/java/org/bench4q/agent/parameterization/SessionObject.java rename to Bench4Q-Agent/src/main/java/org/bench4q/agent/parameterization/SessionObject.java diff --git a/src/main/java/org/bench4q/agent/parameterization/impl/InstanceControler.java b/Bench4Q-Agent/src/main/java/org/bench4q/agent/parameterization/impl/InstanceControler.java similarity index 100% rename from src/main/java/org/bench4q/agent/parameterization/impl/InstanceControler.java rename to Bench4Q-Agent/src/main/java/org/bench4q/agent/parameterization/impl/InstanceControler.java diff --git a/src/main/java/org/bench4q/agent/parameterization/impl/MyFileClassLoader.java b/Bench4Q-Agent/src/main/java/org/bench4q/agent/parameterization/impl/MyFileClassLoader.java similarity index 100% rename from src/main/java/org/bench4q/agent/parameterization/impl/MyFileClassLoader.java rename to Bench4Q-Agent/src/main/java/org/bench4q/agent/parameterization/impl/MyFileClassLoader.java diff --git a/src/main/java/org/bench4q/agent/parameterization/impl/Para_File.java b/Bench4Q-Agent/src/main/java/org/bench4q/agent/parameterization/impl/Para_File.java similarity index 100% rename from src/main/java/org/bench4q/agent/parameterization/impl/Para_File.java rename to Bench4Q-Agent/src/main/java/org/bench4q/agent/parameterization/impl/Para_File.java diff --git a/src/main/java/org/bench4q/agent/parameterization/impl/Para_GetEletronicCombine.java b/Bench4Q-Agent/src/main/java/org/bench4q/agent/parameterization/impl/Para_GetEletronicCombine.java similarity index 100% rename from src/main/java/org/bench4q/agent/parameterization/impl/Para_GetEletronicCombine.java rename to Bench4Q-Agent/src/main/java/org/bench4q/agent/parameterization/impl/Para_GetEletronicCombine.java diff --git a/src/main/java/org/bench4q/agent/parameterization/impl/Para_IteratorNumber.java b/Bench4Q-Agent/src/main/java/org/bench4q/agent/parameterization/impl/Para_IteratorNumber.java similarity index 100% rename from src/main/java/org/bench4q/agent/parameterization/impl/Para_IteratorNumber.java rename to Bench4Q-Agent/src/main/java/org/bench4q/agent/parameterization/impl/Para_IteratorNumber.java diff --git a/src/main/java/org/bench4q/agent/parameterization/impl/Para_RandomNumber.java b/Bench4Q-Agent/src/main/java/org/bench4q/agent/parameterization/impl/Para_RandomNumber.java similarity index 100% rename from src/main/java/org/bench4q/agent/parameterization/impl/Para_RandomNumber.java rename to Bench4Q-Agent/src/main/java/org/bench4q/agent/parameterization/impl/Para_RandomNumber.java diff --git a/src/main/java/org/bench4q/agent/parameterization/impl/Para_Table.java b/Bench4Q-Agent/src/main/java/org/bench4q/agent/parameterization/impl/Para_Table.java similarity index 100% rename from src/main/java/org/bench4q/agent/parameterization/impl/Para_Table.java rename to Bench4Q-Agent/src/main/java/org/bench4q/agent/parameterization/impl/Para_Table.java diff --git a/src/main/java/org/bench4q/agent/parameterization/impl/Para_Table.xml b/Bench4Q-Agent/src/main/java/org/bench4q/agent/parameterization/impl/Para_Table.xml similarity index 100% rename from src/main/java/org/bench4q/agent/parameterization/impl/Para_Table.xml rename to Bench4Q-Agent/src/main/java/org/bench4q/agent/parameterization/impl/Para_Table.xml diff --git a/src/main/java/org/bench4q/agent/parameterization/impl/Para_UniqueNumber.java b/Bench4Q-Agent/src/main/java/org/bench4q/agent/parameterization/impl/Para_UniqueNumber.java similarity index 100% rename from src/main/java/org/bench4q/agent/parameterization/impl/Para_UniqueNumber.java rename to Bench4Q-Agent/src/main/java/org/bench4q/agent/parameterization/impl/Para_UniqueNumber.java diff --git a/src/main/java/org/bench4q/agent/parameterization/impl/Para_UserNameAndPassword.java b/Bench4Q-Agent/src/main/java/org/bench4q/agent/parameterization/impl/Para_UserNameAndPassword.java similarity index 100% rename from src/main/java/org/bench4q/agent/parameterization/impl/Para_UserNameAndPassword.java rename to Bench4Q-Agent/src/main/java/org/bench4q/agent/parameterization/impl/Para_UserNameAndPassword.java diff --git a/src/main/java/org/bench4q/agent/parameterization/impl/ParameterThreadOption.java b/Bench4Q-Agent/src/main/java/org/bench4q/agent/parameterization/impl/ParameterThreadOption.java similarity index 100% rename from src/main/java/org/bench4q/agent/parameterization/impl/ParameterThreadOption.java rename to Bench4Q-Agent/src/main/java/org/bench4q/agent/parameterization/impl/ParameterThreadOption.java diff --git a/src/main/java/org/bench4q/agent/parameterization/impl/ParameterizationParser.java b/Bench4Q-Agent/src/main/java/org/bench4q/agent/parameterization/impl/ParameterizationParser.java similarity index 100% rename from src/main/java/org/bench4q/agent/parameterization/impl/ParameterizationParser.java rename to Bench4Q-Agent/src/main/java/org/bench4q/agent/parameterization/impl/ParameterizationParser.java diff --git a/src/main/java/org/bench4q/agent/parameterization/impl/ParametersFactory.java b/Bench4Q-Agent/src/main/java/org/bench4q/agent/parameterization/impl/ParametersFactory.java similarity index 100% rename from src/main/java/org/bench4q/agent/parameterization/impl/ParametersFactory.java rename to Bench4Q-Agent/src/main/java/org/bench4q/agent/parameterization/impl/ParametersFactory.java diff --git a/src/main/java/org/bench4q/agent/plugin/Behavior.java b/Bench4Q-Agent/src/main/java/org/bench4q/agent/plugin/Behavior.java similarity index 96% rename from src/main/java/org/bench4q/agent/plugin/Behavior.java rename to Bench4Q-Agent/src/main/java/org/bench4q/agent/plugin/Behavior.java index 3fab5f99..ad20e417 100644 --- a/src/main/java/org/bench4q/agent/plugin/Behavior.java +++ b/Bench4Q-Agent/src/main/java/org/bench4q/agent/plugin/Behavior.java @@ -1,12 +1,12 @@ -package org.bench4q.agent.plugin; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -@Target(ElementType.METHOD) -@Retention(RetentionPolicy.RUNTIME) -public @interface Behavior { - String value(); +package org.bench4q.agent.plugin; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Target(ElementType.METHOD) +@Retention(RetentionPolicy.RUNTIME) +public @interface Behavior { + String value(); } \ No newline at end of file diff --git a/src/main/java/org/bench4q/agent/plugin/BehaviorInfo.java b/Bench4Q-Agent/src/main/java/org/bench4q/agent/plugin/BehaviorInfo.java similarity index 94% rename from src/main/java/org/bench4q/agent/plugin/BehaviorInfo.java rename to Bench4Q-Agent/src/main/java/org/bench4q/agent/plugin/BehaviorInfo.java index 8489b801..d09d4b88 100644 --- a/src/main/java/org/bench4q/agent/plugin/BehaviorInfo.java +++ b/Bench4Q-Agent/src/main/java/org/bench4q/agent/plugin/BehaviorInfo.java @@ -1,23 +1,23 @@ -package org.bench4q.agent.plugin; - -public class BehaviorInfo { - private String name; - private ParameterInfo[] parameters; - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public ParameterInfo[] getParameters() { - return parameters; - } - - public void setParameters(ParameterInfo[] parameters) { - this.parameters = parameters; - } - -} +package org.bench4q.agent.plugin; + +public class BehaviorInfo { + private String name; + private ParameterInfo[] parameters; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public ParameterInfo[] getParameters() { + return parameters; + } + + public void setParameters(ParameterInfo[] parameters) { + this.parameters = parameters; + } + +} diff --git a/src/main/java/org/bench4q/agent/plugin/ClassHelper.java b/Bench4Q-Agent/src/main/java/org/bench4q/agent/plugin/ClassHelper.java similarity index 96% rename from src/main/java/org/bench4q/agent/plugin/ClassHelper.java rename to Bench4Q-Agent/src/main/java/org/bench4q/agent/plugin/ClassHelper.java index cf5edc7f..950bab2f 100644 --- a/src/main/java/org/bench4q/agent/plugin/ClassHelper.java +++ b/Bench4Q-Agent/src/main/java/org/bench4q/agent/plugin/ClassHelper.java @@ -1,124 +1,124 @@ -package org.bench4q.agent.plugin; - -import java.io.File; -import java.io.IOException; -import java.net.URL; -import java.net.URLClassLoader; -import java.util.ArrayList; -import java.util.Enumeration; -import java.util.List; -import java.util.jar.JarEntry; -import java.util.jar.JarFile; - -import org.springframework.stereotype.Component; - -@Component -public class ClassHelper { - - public List getClassNames(String packageName, - boolean searchInChildPackage) { - try { - List classNames = new ArrayList(); - URLClassLoader classLoader = (URLClassLoader) Thread - .currentThread().getContextClassLoader(); - URL[] urls = classLoader.getURLs(); - for (URL url : urls) { - if (url.getProtocol().equals("file")) { - File file = new File(url.getFile()); - String root = file.getPath().replace("\\", "/"); - if (file.isDirectory()) { - classNames.addAll(this.getClassNamesFromDirectory(root, - packageName, searchInChildPackage, file, true)); - } else if (file.getName().endsWith(".jar")) { - classNames.addAll(this.getClassNameFromJar(packageName, - searchInChildPackage, file)); - } - } - } - return classNames; - } catch (Exception e) { - e.printStackTrace(); - return null; - } - } - - private List getClassNamesFromDirectory(String root, - String packageName, boolean searchInChildPackage, File directory, - boolean continueSearch) { - List classNames = new ArrayList(); - File[] files = directory.listFiles(); - for (File file : files) { - String filePath = file.getPath().replace("\\", "/"); - if (file.isDirectory()) { - if (searchInChildPackage || continueSearch) { - boolean needToContinue = continueSearch; - if (filePath.endsWith(packageName.replace(".", "/"))) { - needToContinue = needToContinue & false; - } - classNames.addAll(this.getClassNamesFromDirectory(root, - packageName, searchInChildPackage, file, - needToContinue)); - } - } else { - if (filePath.endsWith(".class")) { - String classFileName = filePath.replace(root + "/", ""); - if (classFileName.startsWith(packageName.replace(".", "/"))) { - String className = classFileName.substring(0, - classFileName.length() - ".class".length()) - .replace("/", "."); - classNames.add(className); - } - } - } - } - return classNames; - } - - private List getClassNameFromJar(String packageName, - boolean searchInChildPackage, File file) { - List classNames = new ArrayList(); - JarFile jarFile = null; - try { - jarFile = new JarFile(file); - Enumeration jarEntries = jarFile.entries(); - while (jarEntries.hasMoreElements()) { - JarEntry jarEntry = jarEntries.nextElement(); - String entryName = jarEntry.getName(); - if (entryName.endsWith(".class")) { - String packagePath = packageName.replace(".", "/"); - if (searchInChildPackage) { - if (entryName.startsWith(packagePath)) { - entryName = entryName.replace("/", ".").substring( - 0, entryName.lastIndexOf(".")); - classNames.add(entryName); - } - } else { - int index = entryName.lastIndexOf("/"); - String entryPath; - if (index != -1) { - entryPath = entryName.substring(0, index); - } else { - entryPath = entryName; - } - if (entryPath.equals(packagePath)) { - entryName = entryName.replace("/", ".").substring( - 0, entryName.lastIndexOf(".")); - classNames.add(entryName); - } - } - } - } - } catch (IOException e) { - e.printStackTrace(); - } finally { - if (jarFile != null) { - try { - jarFile.close(); - } catch (IOException e) { - e.printStackTrace(); - } - } - } - return classNames; - } -} +package org.bench4q.agent.plugin; + +import java.io.File; +import java.io.IOException; +import java.net.URL; +import java.net.URLClassLoader; +import java.util.ArrayList; +import java.util.Enumeration; +import java.util.List; +import java.util.jar.JarEntry; +import java.util.jar.JarFile; + +import org.springframework.stereotype.Component; + +@Component +public class ClassHelper { + + public List getClassNames(String packageName, + boolean searchInChildPackage) { + try { + List classNames = new ArrayList(); + URLClassLoader classLoader = (URLClassLoader) Thread + .currentThread().getContextClassLoader(); + URL[] urls = classLoader.getURLs(); + for (URL url : urls) { + if (url.getProtocol().equals("file")) { + File file = new File(url.getFile()); + String root = file.getPath().replace("\\", "/"); + if (file.isDirectory()) { + classNames.addAll(this.getClassNamesFromDirectory(root, + packageName, searchInChildPackage, file, true)); + } else if (file.getName().endsWith(".jar")) { + classNames.addAll(this.getClassNameFromJar(packageName, + searchInChildPackage, file)); + } + } + } + return classNames; + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } + + private List getClassNamesFromDirectory(String root, + String packageName, boolean searchInChildPackage, File directory, + boolean continueSearch) { + List classNames = new ArrayList(); + File[] files = directory.listFiles(); + for (File file : files) { + String filePath = file.getPath().replace("\\", "/"); + if (file.isDirectory()) { + if (searchInChildPackage || continueSearch) { + boolean needToContinue = continueSearch; + if (filePath.endsWith(packageName.replace(".", "/"))) { + needToContinue = needToContinue & false; + } + classNames.addAll(this.getClassNamesFromDirectory(root, + packageName, searchInChildPackage, file, + needToContinue)); + } + } else { + if (filePath.endsWith(".class")) { + String classFileName = filePath.replace(root + "/", ""); + if (classFileName.startsWith(packageName.replace(".", "/"))) { + String className = classFileName.substring(0, + classFileName.length() - ".class".length()) + .replace("/", "."); + classNames.add(className); + } + } + } + } + return classNames; + } + + private List getClassNameFromJar(String packageName, + boolean searchInChildPackage, File file) { + List classNames = new ArrayList(); + JarFile jarFile = null; + try { + jarFile = new JarFile(file); + Enumeration jarEntries = jarFile.entries(); + while (jarEntries.hasMoreElements()) { + JarEntry jarEntry = jarEntries.nextElement(); + String entryName = jarEntry.getName(); + if (entryName.endsWith(".class")) { + String packagePath = packageName.replace(".", "/"); + if (searchInChildPackage) { + if (entryName.startsWith(packagePath)) { + entryName = entryName.replace("/", ".").substring( + 0, entryName.lastIndexOf(".")); + classNames.add(entryName); + } + } else { + int index = entryName.lastIndexOf("/"); + String entryPath; + if (index != -1) { + entryPath = entryName.substring(0, index); + } else { + entryPath = entryName; + } + if (entryPath.equals(packagePath)) { + entryName = entryName.replace("/", ".").substring( + 0, entryName.lastIndexOf(".")); + classNames.add(entryName); + } + } + } + } + } catch (IOException e) { + e.printStackTrace(); + } finally { + if (jarFile != null) { + try { + jarFile.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + return classNames; + } +} diff --git a/src/main/java/org/bench4q/agent/plugin/Parameter.java b/Bench4Q-Agent/src/main/java/org/bench4q/agent/plugin/Parameter.java similarity index 96% rename from src/main/java/org/bench4q/agent/plugin/Parameter.java rename to Bench4Q-Agent/src/main/java/org/bench4q/agent/plugin/Parameter.java index ee7d8a11..a9e0a171 100644 --- a/src/main/java/org/bench4q/agent/plugin/Parameter.java +++ b/Bench4Q-Agent/src/main/java/org/bench4q/agent/plugin/Parameter.java @@ -1,12 +1,12 @@ -package org.bench4q.agent.plugin; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -@Target(ElementType.PARAMETER) -@Retention(RetentionPolicy.RUNTIME) -public @interface Parameter { - String value(); -} +package org.bench4q.agent.plugin; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Target(ElementType.PARAMETER) +@Retention(RetentionPolicy.RUNTIME) +public @interface Parameter { + String value(); +} diff --git a/src/main/java/org/bench4q/agent/plugin/ParameterInfo.java b/Bench4Q-Agent/src/main/java/org/bench4q/agent/plugin/ParameterInfo.java similarity index 93% rename from src/main/java/org/bench4q/agent/plugin/ParameterInfo.java rename to Bench4Q-Agent/src/main/java/org/bench4q/agent/plugin/ParameterInfo.java index 52be6ee2..4db0e540 100644 --- a/src/main/java/org/bench4q/agent/plugin/ParameterInfo.java +++ b/Bench4Q-Agent/src/main/java/org/bench4q/agent/plugin/ParameterInfo.java @@ -1,23 +1,23 @@ -package org.bench4q.agent.plugin; - -public class ParameterInfo { - private String name; - private String type; - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getType() { - return type; - } - - public void setType(String type) { - this.type = type; - } - -} +package org.bench4q.agent.plugin; + +public class ParameterInfo { + private String name; + private String type; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + +} diff --git a/src/main/java/org/bench4q/agent/plugin/Plugin.java b/Bench4Q-Agent/src/main/java/org/bench4q/agent/plugin/Plugin.java similarity index 96% rename from src/main/java/org/bench4q/agent/plugin/Plugin.java rename to Bench4Q-Agent/src/main/java/org/bench4q/agent/plugin/Plugin.java index 7841b547..4647553c 100644 --- a/src/main/java/org/bench4q/agent/plugin/Plugin.java +++ b/Bench4Q-Agent/src/main/java/org/bench4q/agent/plugin/Plugin.java @@ -1,12 +1,12 @@ -package org.bench4q.agent.plugin; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -@Target(ElementType.TYPE) -@Retention(RetentionPolicy.RUNTIME) -public @interface Plugin { - String value(); -} +package org.bench4q.agent.plugin; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Target(ElementType.TYPE) +@Retention(RetentionPolicy.RUNTIME) +public @interface Plugin { + String value(); +} diff --git a/src/main/java/org/bench4q/agent/plugin/PluginInfo.java b/Bench4Q-Agent/src/main/java/org/bench4q/agent/plugin/PluginInfo.java similarity index 94% rename from src/main/java/org/bench4q/agent/plugin/PluginInfo.java rename to Bench4Q-Agent/src/main/java/org/bench4q/agent/plugin/PluginInfo.java index 0063d172..aadc176a 100644 --- a/src/main/java/org/bench4q/agent/plugin/PluginInfo.java +++ b/Bench4Q-Agent/src/main/java/org/bench4q/agent/plugin/PluginInfo.java @@ -1,32 +1,32 @@ -package org.bench4q.agent.plugin; - -public class PluginInfo { - private String name; - private ParameterInfo[] parameters; - private BehaviorInfo[] behaviors; - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public ParameterInfo[] getParameters() { - return parameters; - } - - public void setParameters(ParameterInfo[] parameters) { - this.parameters = parameters; - } - - public BehaviorInfo[] getBehaviors() { - return behaviors; - } - - public void setBehaviors(BehaviorInfo[] behaviors) { - this.behaviors = behaviors; - } - -} +package org.bench4q.agent.plugin; + +public class PluginInfo { + private String name; + private ParameterInfo[] parameters; + private BehaviorInfo[] behaviors; + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public ParameterInfo[] getParameters() { + return parameters; + } + + public void setParameters(ParameterInfo[] parameters) { + this.parameters = parameters; + } + + public BehaviorInfo[] getBehaviors() { + return behaviors; + } + + public void setBehaviors(BehaviorInfo[] behaviors) { + this.behaviors = behaviors; + } + +} diff --git a/src/main/java/org/bench4q/agent/plugin/PluginManager.java b/Bench4Q-Agent/src/main/java/org/bench4q/agent/plugin/PluginManager.java similarity index 96% rename from src/main/java/org/bench4q/agent/plugin/PluginManager.java rename to Bench4Q-Agent/src/main/java/org/bench4q/agent/plugin/PluginManager.java index d5e6629f..735d3a37 100644 --- a/src/main/java/org/bench4q/agent/plugin/PluginManager.java +++ b/Bench4Q-Agent/src/main/java/org/bench4q/agent/plugin/PluginManager.java @@ -1,269 +1,269 @@ -package org.bench4q.agent.plugin; - -import java.lang.annotation.Annotation; -import java.lang.reflect.Constructor; -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.apache.log4j.Logger; -import org.bench4q.agent.share.DealWithLog; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; - -@Component -public class PluginManager { - private ClassHelper classHelper; - private TypeConverter typeConverter; - private Map> plugins; - private Logger logger = Logger.getLogger(PluginManager.class); - - @Autowired - public PluginManager(ClassHelper classHelper, TypeConverter typeConverter) { - this.setClassHelper(classHelper); - this.setTypeConverter(typeConverter); - this.setPlugins(this.loadPlugins("org.bench4q.agent.plugin")); - } - - private ClassHelper getClassHelper() { - return classHelper; - } - - private void setClassHelper(ClassHelper classHelper) { - this.classHelper = classHelper; - } - - private TypeConverter getTypeConverter() { - return typeConverter; - } - - private void setTypeConverter(TypeConverter typeConverter) { - this.typeConverter = typeConverter; - } - - public Map> getPlugins() { - return plugins; - } - - private void setPlugins(Map> plugins) { - this.plugins = plugins; - } - - public Map> loadPlugins(String packageName) { - try { - List classNames = this.getClassHelper().getClassNames( - packageName, true); - Map> ret = new HashMap>(); - for (String className : classNames) { - Class plugin = Class.forName(className); - if (plugin.isAnnotationPresent(Plugin.class)) { - ret.put(plugin.getAnnotation(Plugin.class).value(), plugin); - } - } - return ret; - } catch (Exception e) { - e.printStackTrace(); - return null; - } - } - - public List getPluginInfo() { - try { - Map> plugins = this.getPlugins(); - List ret = new ArrayList(); - for (Class plugin : plugins.values()) { - PluginInfo pluginInfo = new PluginInfo(); - pluginInfo - .setName((plugin.getAnnotation(Plugin.class)).value()); - pluginInfo.setParameters(this.getParameters(plugin - .getConstructors()[0])); - Method[] behaviors = this.getBehaviors(plugin); - pluginInfo.setBehaviors(new BehaviorInfo[behaviors.length]); - int i = 0; - for (i = 0; i < behaviors.length; i++) { - Method behaviorMethod = behaviors[i]; - BehaviorInfo behaviorInfo = buildBehaviorInfo(behaviorMethod); - pluginInfo.getBehaviors()[i] = behaviorInfo; - } - ret.add(pluginInfo); - } - return ret; - } catch (Exception e) { - e.printStackTrace(); - return null; - } - } - - private BehaviorInfo buildBehaviorInfo(Method behaviorMethod) - throws ClassNotFoundException { - BehaviorInfo behaviorInfo = new BehaviorInfo(); - behaviorInfo.setName((behaviorMethod.getAnnotation(Behavior.class)) - .value()); - behaviorInfo.setParameters(this.getParameters(behaviorMethod)); - return behaviorInfo; - } - - private ParameterInfo[] getParameters(Method behavior) { - try { - int parameterCount = behavior.getParameterTypes().length; - Annotation[][] parameterAnnotations = behavior - .getParameterAnnotations(); - ParameterInfo[] parameterNames = new ParameterInfo[parameterCount]; - int i; - for (i = 0; i < parameterCount; i++) { - Annotation[] annotations = parameterAnnotations[i]; - Parameter parameter = (Parameter) annotations[0]; - Class type = behavior.getParameterTypes()[i]; - ParameterInfo parameterInfo = buildParameterInfo( - parameter.value(), type.getName()); - parameterNames[i] = parameterInfo; - } - return parameterNames; - } catch (Exception e) { - logger.error(DealWithLog.getExceptionStackTrace(e)); - return null; - } - } - - private ParameterInfo[] getParameters(Constructor behavior) { - try { - int parameterCount = behavior.getParameterTypes().length; - Annotation[][] parameterAnnotations = behavior - .getParameterAnnotations(); - ParameterInfo[] parameterNames = new ParameterInfo[parameterCount]; - int i; - for (i = 0; i < parameterCount; i++) { - Annotation[] annotations = parameterAnnotations[i]; - Parameter parameter = (Parameter) annotations[0]; - Class type = behavior.getParameterTypes()[i]; - ParameterInfo parameterInfo = buildParameterInfo( - parameter.value(), type.getName()); - parameterNames[i] = parameterInfo; - } - return parameterNames; - } catch (Exception e) { - e.printStackTrace(); - return null; - } - } - - private ParameterInfo buildParameterInfo(String name, String type) { - ParameterInfo parameterInfo = new ParameterInfo(); - parameterInfo.setName(name); - parameterInfo.setType(type); - return parameterInfo; - } - - private Method[] getBehaviors(Class plugin) { - try { - Method[] methods = plugin.getMethods(); - List ret = new ArrayList(); - int i = 0; - for (i = 0; i < methods.length; i++) { - if (methods[i].isAnnotationPresent(Behavior.class)) { - ret.add(methods[i]); - } - } - return ret.toArray(new Method[0]); - } catch (Exception e) { - e.printStackTrace(); - return null; - } - } - - public Object initializePlugin(Class plugin, - Map parameters) { - try { - Constructor[] ctConstructors = plugin.getConstructors(); - if (ctConstructors.length != 1) { - return null; - } - Constructor constructor = ctConstructors[0]; - Object[] params = prepareParameters(constructor, parameters); - return plugin.getConstructors()[0].newInstance(params); - } catch (Exception e) { - e.printStackTrace(); - return null; - } - } - - private Object[] prepareParameters(Constructor behavior, - Map parameters) { - try { - ParameterInfo[] parameterInfo = this.getParameters(behavior); - Object values[] = new Object[parameterInfo.length]; - int i = 0; - for (i = 0; i < parameterInfo.length; i++) { - Object value = parameters.get(parameterInfo[i].getName()); - if (value == null) { - values[i] = null; - } else { - values[i] = this.getTypeConverter().convert(value, - parameterInfo[i].getType()); - } - } - return values; - } catch (Exception e) { - e.printStackTrace(); - return null; - } - } - - private Object[] prepareParameters(Method behavior, - Map parameters) { - try { - ParameterInfo[] parameterInfo = this.getParameters(behavior); - Object values[] = new Object[parameterInfo.length]; - int i = 0; - for (i = 0; i < parameterInfo.length; i++) { - Object value = parameters.get(parameterInfo[i].getName()); - if (value == null) { - values[i] = null; - } else { - values[i] = this.getTypeConverter().convert(value, - parameterInfo[i].getType()); - } - } - return values; - } catch (Exception e) { - e.printStackTrace(); - return null; - } - } - - public Object doBehavior(Object plugin, String behaviorName, - Map parameters) { - try { - Method method = findMethod(plugin, behaviorName); - if (method == null) { - return null; - } - Object[] params = prepareParameters(method, parameters); - return method.invoke(plugin, params); - } catch (Exception e) { - - return null; - } - } - - private Method findMethod(Object plugin, String behaviorName) { - try { - Method[] methods = plugin.getClass().getMethods(); - int i = 0; - for (i = 0; i < methods.length; i++) { - if (methods[i].isAnnotationPresent(Behavior.class)) { - if (((Behavior) methods[i].getAnnotation(Behavior.class)) - .value().equals(behaviorName)) { - return methods[i]; - } - } - } - return null; - } catch (Exception e) { - e.printStackTrace(); - return null; - } - } -} +package org.bench4q.agent.plugin; + +import java.lang.annotation.Annotation; +import java.lang.reflect.Constructor; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.apache.log4j.Logger; +import org.bench4q.agent.share.DealWithLog; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +@Component +public class PluginManager { + private ClassHelper classHelper; + private TypeConverter typeConverter; + private Map> plugins; + private Logger logger = Logger.getLogger(PluginManager.class); + + @Autowired + public PluginManager(ClassHelper classHelper, TypeConverter typeConverter) { + this.setClassHelper(classHelper); + this.setTypeConverter(typeConverter); + this.setPlugins(this.loadPlugins("org.bench4q.agent.plugin")); + } + + private ClassHelper getClassHelper() { + return classHelper; + } + + private void setClassHelper(ClassHelper classHelper) { + this.classHelper = classHelper; + } + + private TypeConverter getTypeConverter() { + return typeConverter; + } + + private void setTypeConverter(TypeConverter typeConverter) { + this.typeConverter = typeConverter; + } + + public Map> getPlugins() { + return plugins; + } + + private void setPlugins(Map> plugins) { + this.plugins = plugins; + } + + public Map> loadPlugins(String packageName) { + try { + List classNames = this.getClassHelper().getClassNames( + packageName, true); + Map> ret = new HashMap>(); + for (String className : classNames) { + Class plugin = Class.forName(className); + if (plugin.isAnnotationPresent(Plugin.class)) { + ret.put(plugin.getAnnotation(Plugin.class).value(), plugin); + } + } + return ret; + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } + + public List getPluginInfo() { + try { + Map> plugins = this.getPlugins(); + List ret = new ArrayList(); + for (Class plugin : plugins.values()) { + PluginInfo pluginInfo = new PluginInfo(); + pluginInfo + .setName((plugin.getAnnotation(Plugin.class)).value()); + pluginInfo.setParameters(this.getParameters(plugin + .getConstructors()[0])); + Method[] behaviors = this.getBehaviors(plugin); + pluginInfo.setBehaviors(new BehaviorInfo[behaviors.length]); + int i = 0; + for (i = 0; i < behaviors.length; i++) { + Method behaviorMethod = behaviors[i]; + BehaviorInfo behaviorInfo = buildBehaviorInfo(behaviorMethod); + pluginInfo.getBehaviors()[i] = behaviorInfo; + } + ret.add(pluginInfo); + } + return ret; + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } + + private BehaviorInfo buildBehaviorInfo(Method behaviorMethod) + throws ClassNotFoundException { + BehaviorInfo behaviorInfo = new BehaviorInfo(); + behaviorInfo.setName((behaviorMethod.getAnnotation(Behavior.class)) + .value()); + behaviorInfo.setParameters(this.getParameters(behaviorMethod)); + return behaviorInfo; + } + + private ParameterInfo[] getParameters(Method behavior) { + try { + int parameterCount = behavior.getParameterTypes().length; + Annotation[][] parameterAnnotations = behavior + .getParameterAnnotations(); + ParameterInfo[] parameterNames = new ParameterInfo[parameterCount]; + int i; + for (i = 0; i < parameterCount; i++) { + Annotation[] annotations = parameterAnnotations[i]; + Parameter parameter = (Parameter) annotations[0]; + Class type = behavior.getParameterTypes()[i]; + ParameterInfo parameterInfo = buildParameterInfo( + parameter.value(), type.getName()); + parameterNames[i] = parameterInfo; + } + return parameterNames; + } catch (Exception e) { + logger.error(DealWithLog.getExceptionStackTrace(e)); + return null; + } + } + + private ParameterInfo[] getParameters(Constructor behavior) { + try { + int parameterCount = behavior.getParameterTypes().length; + Annotation[][] parameterAnnotations = behavior + .getParameterAnnotations(); + ParameterInfo[] parameterNames = new ParameterInfo[parameterCount]; + int i; + for (i = 0; i < parameterCount; i++) { + Annotation[] annotations = parameterAnnotations[i]; + Parameter parameter = (Parameter) annotations[0]; + Class type = behavior.getParameterTypes()[i]; + ParameterInfo parameterInfo = buildParameterInfo( + parameter.value(), type.getName()); + parameterNames[i] = parameterInfo; + } + return parameterNames; + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } + + private ParameterInfo buildParameterInfo(String name, String type) { + ParameterInfo parameterInfo = new ParameterInfo(); + parameterInfo.setName(name); + parameterInfo.setType(type); + return parameterInfo; + } + + private Method[] getBehaviors(Class plugin) { + try { + Method[] methods = plugin.getMethods(); + List ret = new ArrayList(); + int i = 0; + for (i = 0; i < methods.length; i++) { + if (methods[i].isAnnotationPresent(Behavior.class)) { + ret.add(methods[i]); + } + } + return ret.toArray(new Method[0]); + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } + + public Object initializePlugin(Class plugin, + Map parameters) { + try { + Constructor[] ctConstructors = plugin.getConstructors(); + if (ctConstructors.length != 1) { + return null; + } + Constructor constructor = ctConstructors[0]; + Object[] params = prepareParameters(constructor, parameters); + return plugin.getConstructors()[0].newInstance(params); + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } + + private Object[] prepareParameters(Constructor behavior, + Map parameters) { + try { + ParameterInfo[] parameterInfo = this.getParameters(behavior); + Object values[] = new Object[parameterInfo.length]; + int i = 0; + for (i = 0; i < parameterInfo.length; i++) { + Object value = parameters.get(parameterInfo[i].getName()); + if (value == null) { + values[i] = null; + } else { + values[i] = this.getTypeConverter().convert(value, + parameterInfo[i].getType()); + } + } + return values; + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } + + private Object[] prepareParameters(Method behavior, + Map parameters) { + try { + ParameterInfo[] parameterInfo = this.getParameters(behavior); + Object values[] = new Object[parameterInfo.length]; + int i = 0; + for (i = 0; i < parameterInfo.length; i++) { + Object value = parameters.get(parameterInfo[i].getName()); + if (value == null) { + values[i] = null; + } else { + values[i] = this.getTypeConverter().convert(value, + parameterInfo[i].getType()); + } + } + return values; + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } + + public Object doBehavior(Object plugin, String behaviorName, + Map parameters) { + try { + Method method = findMethod(plugin, behaviorName); + if (method == null) { + return null; + } + Object[] params = prepareParameters(method, parameters); + return method.invoke(plugin, params); + } catch (Exception e) { + + return null; + } + } + + private Method findMethod(Object plugin, String behaviorName) { + try { + Method[] methods = plugin.getClass().getMethods(); + int i = 0; + for (i = 0; i < methods.length; i++) { + if (methods[i].isAnnotationPresent(Behavior.class)) { + if (((Behavior) methods[i].getAnnotation(Behavior.class)) + .value().equals(behaviorName)) { + return methods[i]; + } + } + } + return null; + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } +} diff --git a/src/main/java/org/bench4q/agent/plugin/TypeConverter.java b/Bench4Q-Agent/src/main/java/org/bench4q/agent/plugin/TypeConverter.java similarity index 96% rename from src/main/java/org/bench4q/agent/plugin/TypeConverter.java rename to Bench4Q-Agent/src/main/java/org/bench4q/agent/plugin/TypeConverter.java index de1216e3..8b6b29b0 100644 --- a/src/main/java/org/bench4q/agent/plugin/TypeConverter.java +++ b/Bench4Q-Agent/src/main/java/org/bench4q/agent/plugin/TypeConverter.java @@ -1,44 +1,44 @@ -package org.bench4q.agent.plugin; - -import org.springframework.stereotype.Component; - -@Component -public class TypeConverter { - public Object convert(Object source, String targetClassName) { - if (targetClassName.equals("boolean")) { - return Boolean.parseBoolean(source.toString()); - } - if (targetClassName.equals("char")) { - return source.toString().toCharArray()[0]; - } - if (targetClassName.equals("byte")) { - return Byte.parseByte(source.toString()); - } - if (targetClassName.equals("short")) { - return Short.parseShort(source.toString()); - } - if (targetClassName.equals("int")) { - return Integer.parseInt(source.toString()); - } - if (targetClassName.equals("long")) { - return Long.parseLong(source.toString()); - } - if (targetClassName.equals("float")) { - return Float.parseFloat(source.toString()); - } - if (targetClassName.equals("double")) { - return Double.parseDouble(source.toString()); - } - - try { - Class targetClass = Class.forName(targetClassName); - if (targetClass.isAssignableFrom(String.class)) { - return source.toString(); - } - return targetClass.cast(source); - } catch (Exception e) { - e.printStackTrace(); - return null; - } - } -} +package org.bench4q.agent.plugin; + +import org.springframework.stereotype.Component; + +@Component +public class TypeConverter { + public Object convert(Object source, String targetClassName) { + if (targetClassName.equals("boolean")) { + return Boolean.parseBoolean(source.toString()); + } + if (targetClassName.equals("char")) { + return source.toString().toCharArray()[0]; + } + if (targetClassName.equals("byte")) { + return Byte.parseByte(source.toString()); + } + if (targetClassName.equals("short")) { + return Short.parseShort(source.toString()); + } + if (targetClassName.equals("int")) { + return Integer.parseInt(source.toString()); + } + if (targetClassName.equals("long")) { + return Long.parseLong(source.toString()); + } + if (targetClassName.equals("float")) { + return Float.parseFloat(source.toString()); + } + if (targetClassName.equals("double")) { + return Double.parseDouble(source.toString()); + } + + try { + Class targetClass = Class.forName(targetClassName); + if (targetClass.isAssignableFrom(String.class)) { + return source.toString(); + } + return targetClass.cast(source); + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } +} diff --git a/src/main/java/org/bench4q/agent/plugin/basic/CommandLinePlugin.java b/Bench4Q-Agent/src/main/java/org/bench4q/agent/plugin/basic/CommandLinePlugin.java similarity index 96% rename from src/main/java/org/bench4q/agent/plugin/basic/CommandLinePlugin.java rename to Bench4Q-Agent/src/main/java/org/bench4q/agent/plugin/basic/CommandLinePlugin.java index 1ab199af..97072a39 100644 --- a/src/main/java/org/bench4q/agent/plugin/basic/CommandLinePlugin.java +++ b/Bench4Q-Agent/src/main/java/org/bench4q/agent/plugin/basic/CommandLinePlugin.java @@ -1,89 +1,89 @@ -package org.bench4q.agent.plugin.basic; - -import java.io.BufferedReader; -import java.io.InputStreamReader; - -import org.bench4q.agent.plugin.Behavior; -import org.bench4q.agent.plugin.Parameter; -import org.bench4q.agent.plugin.Plugin; -import org.bench4q.agent.plugin.result.CommandLineReturn; - -@Plugin("CommandLine") -public class CommandLinePlugin { - private String standardOutput; - private String standardError; - - public String getStandardOutput() { - return standardOutput; - } - - private void setStandardOutput(String standardOutput) { - this.standardOutput = standardOutput; - } - - public String getStandardError() { - return standardError; - } - - private void setStandardError(String standardError) { - this.standardError = standardError; - } - - public CommandLinePlugin() { - - } - - @Behavior("Command") - public CommandLineReturn command(@Parameter("command") String command) { - try { - final Process process = Runtime.getRuntime().exec(command); - new Thread() { - public void run() { - try { - BufferedReader reader = new BufferedReader( - new InputStreamReader(process.getInputStream())); - String streamline = ""; - try { - setStandardOutput(""); - while ((streamline = reader.readLine()) != null) { - setStandardOutput(getStandardOutput() - + streamline - + System.getProperty("line.separator")); - } - } finally { - reader.close(); - } - } catch (Exception e) { - e.printStackTrace(); - } - } - }.start(); - new Thread() { - public void run() { - try { - BufferedReader reader = new BufferedReader( - new InputStreamReader(process.getErrorStream())); - String streamline = ""; - try { - setStandardError(""); - while ((streamline = reader.readLine()) != null) { - setStandardError(getStandardError() - + streamline - + System.getProperty("line.separator")); - } - } finally { - reader.close(); - } - } catch (Exception e) { - e.printStackTrace(); - } - } - }.start(); - process.waitFor(); - return new CommandLineReturn(true); - } catch (Exception e) { - e.printStackTrace(); - return new CommandLineReturn(false); - } - } -} +package org.bench4q.agent.plugin.basic; + +import java.io.BufferedReader; +import java.io.InputStreamReader; + +import org.bench4q.agent.plugin.Behavior; +import org.bench4q.agent.plugin.Parameter; +import org.bench4q.agent.plugin.Plugin; +import org.bench4q.agent.plugin.result.CommandLineReturn; + +@Plugin("CommandLine") +public class CommandLinePlugin { + private String standardOutput; + private String standardError; + + public String getStandardOutput() { + return standardOutput; + } + + private void setStandardOutput(String standardOutput) { + this.standardOutput = standardOutput; + } + + public String getStandardError() { + return standardError; + } + + private void setStandardError(String standardError) { + this.standardError = standardError; + } + + public CommandLinePlugin() { + + } + + @Behavior("Command") + public CommandLineReturn command(@Parameter("command") String command) { + try { + final Process process = Runtime.getRuntime().exec(command); + new Thread() { + public void run() { + try { + BufferedReader reader = new BufferedReader( + new InputStreamReader(process.getInputStream())); + String streamline = ""; + try { + setStandardOutput(""); + while ((streamline = reader.readLine()) != null) { + setStandardOutput(getStandardOutput() + + streamline + + System.getProperty("line.separator")); + } + } finally { + reader.close(); + } + } catch (Exception e) { + e.printStackTrace(); + } + } + }.start(); + new Thread() { + public void run() { + try { + BufferedReader reader = new BufferedReader( + new InputStreamReader(process.getErrorStream())); + String streamline = ""; + try { + setStandardError(""); + while ((streamline = reader.readLine()) != null) { + setStandardError(getStandardError() + + streamline + + System.getProperty("line.separator")); + } + } finally { + reader.close(); + } + } catch (Exception e) { + e.printStackTrace(); + } + } + }.start(); + process.waitFor(); + return new CommandLineReturn(true); + } catch (Exception e) { + e.printStackTrace(); + return new CommandLineReturn(false); + } + } +} diff --git a/src/main/java/org/bench4q/agent/plugin/basic/ConstantTimerPlugin.java b/Bench4Q-Agent/src/main/java/org/bench4q/agent/plugin/basic/ConstantTimerPlugin.java similarity index 96% rename from src/main/java/org/bench4q/agent/plugin/basic/ConstantTimerPlugin.java rename to Bench4Q-Agent/src/main/java/org/bench4q/agent/plugin/basic/ConstantTimerPlugin.java index 12af61e7..589d0b40 100644 --- a/src/main/java/org/bench4q/agent/plugin/basic/ConstantTimerPlugin.java +++ b/Bench4Q-Agent/src/main/java/org/bench4q/agent/plugin/basic/ConstantTimerPlugin.java @@ -1,27 +1,27 @@ -package org.bench4q.agent.plugin.basic; - -import org.apache.log4j.Logger; -import org.bench4q.agent.plugin.Behavior; -import org.bench4q.agent.plugin.Parameter; -import org.bench4q.agent.plugin.Plugin; -import org.bench4q.agent.plugin.result.TimerReturn; - -@Plugin("ConstantTimer") -public class ConstantTimerPlugin { - private Logger logger = Logger.getLogger(ConstantTimerPlugin.class); - - public ConstantTimerPlugin() { - - } - - @Behavior("Sleep") - public TimerReturn sleep(@Parameter("time") int time) { - try { - Thread.sleep(time); - return new TimerReturn(true); - } catch (Exception e) { - logger.info("sleep interrupted!"); - return new TimerReturn(false); - } - } -} +package org.bench4q.agent.plugin.basic; + +import org.apache.log4j.Logger; +import org.bench4q.agent.plugin.Behavior; +import org.bench4q.agent.plugin.Parameter; +import org.bench4q.agent.plugin.Plugin; +import org.bench4q.agent.plugin.result.TimerReturn; + +@Plugin("ConstantTimer") +public class ConstantTimerPlugin { + private Logger logger = Logger.getLogger(ConstantTimerPlugin.class); + + public ConstantTimerPlugin() { + + } + + @Behavior("Sleep") + public TimerReturn sleep(@Parameter("time") int time) { + try { + Thread.sleep(time); + return new TimerReturn(true); + } catch (Exception e) { + logger.info("sleep interrupted!"); + return new TimerReturn(false); + } + } +} diff --git a/src/main/java/org/bench4q/agent/plugin/basic/LogPlugin.java b/Bench4Q-Agent/src/main/java/org/bench4q/agent/plugin/basic/LogPlugin.java similarity index 95% rename from src/main/java/org/bench4q/agent/plugin/basic/LogPlugin.java rename to Bench4Q-Agent/src/main/java/org/bench4q/agent/plugin/basic/LogPlugin.java index 01ed60e2..473ef163 100644 --- a/src/main/java/org/bench4q/agent/plugin/basic/LogPlugin.java +++ b/Bench4Q-Agent/src/main/java/org/bench4q/agent/plugin/basic/LogPlugin.java @@ -1,19 +1,19 @@ -package org.bench4q.agent.plugin.basic; - -import org.bench4q.agent.plugin.Behavior; -import org.bench4q.agent.plugin.Parameter; -import org.bench4q.agent.plugin.Plugin; -import org.bench4q.agent.plugin.result.LogReturn; - -@Plugin("Log") -public class LogPlugin { - public LogPlugin() { - - } - - @Behavior("Log") - public LogReturn log(@Parameter("message") String message) { - System.out.println(message); - return new LogReturn(true); - } -} +package org.bench4q.agent.plugin.basic; + +import org.bench4q.agent.plugin.Behavior; +import org.bench4q.agent.plugin.Parameter; +import org.bench4q.agent.plugin.Plugin; +import org.bench4q.agent.plugin.result.LogReturn; + +@Plugin("Log") +public class LogPlugin { + public LogPlugin() { + + } + + @Behavior("Log") + public LogReturn log(@Parameter("message") String message) { + System.out.println(message); + return new LogReturn(true); + } +} diff --git a/src/main/java/org/bench4q/agent/plugin/basic/http/HttpPlugin.java b/Bench4Q-Agent/src/main/java/org/bench4q/agent/plugin/basic/http/HttpPlugin.java similarity index 100% rename from src/main/java/org/bench4q/agent/plugin/basic/http/HttpPlugin.java rename to Bench4Q-Agent/src/main/java/org/bench4q/agent/plugin/basic/http/HttpPlugin.java diff --git a/src/main/java/org/bench4q/agent/plugin/basic/http/ParameterConstant.java b/Bench4Q-Agent/src/main/java/org/bench4q/agent/plugin/basic/http/ParameterConstant.java similarity index 100% rename from src/main/java/org/bench4q/agent/plugin/basic/http/ParameterConstant.java rename to Bench4Q-Agent/src/main/java/org/bench4q/agent/plugin/basic/http/ParameterConstant.java diff --git a/src/main/java/org/bench4q/agent/plugin/result/CommandLineReturn.java b/Bench4Q-Agent/src/main/java/org/bench4q/agent/plugin/result/CommandLineReturn.java similarity index 96% rename from src/main/java/org/bench4q/agent/plugin/result/CommandLineReturn.java rename to Bench4Q-Agent/src/main/java/org/bench4q/agent/plugin/result/CommandLineReturn.java index 4e682097..15679f69 100644 --- a/src/main/java/org/bench4q/agent/plugin/result/CommandLineReturn.java +++ b/Bench4Q-Agent/src/main/java/org/bench4q/agent/plugin/result/CommandLineReturn.java @@ -1,7 +1,7 @@ -package org.bench4q.agent.plugin.result; - -public class CommandLineReturn extends PluginReturn { - public CommandLineReturn(boolean success) { - this.setSuccess(success); - } -} +package org.bench4q.agent.plugin.result; + +public class CommandLineReturn extends PluginReturn { + public CommandLineReturn(boolean success) { + this.setSuccess(success); + } +} diff --git a/src/main/java/org/bench4q/agent/plugin/result/HttpReturn.java b/Bench4Q-Agent/src/main/java/org/bench4q/agent/plugin/result/HttpReturn.java similarity index 100% rename from src/main/java/org/bench4q/agent/plugin/result/HttpReturn.java rename to Bench4Q-Agent/src/main/java/org/bench4q/agent/plugin/result/HttpReturn.java diff --git a/src/main/java/org/bench4q/agent/plugin/result/LogReturn.java b/Bench4Q-Agent/src/main/java/org/bench4q/agent/plugin/result/LogReturn.java similarity index 95% rename from src/main/java/org/bench4q/agent/plugin/result/LogReturn.java rename to Bench4Q-Agent/src/main/java/org/bench4q/agent/plugin/result/LogReturn.java index 3fdfaa05..d26ff1eb 100644 --- a/src/main/java/org/bench4q/agent/plugin/result/LogReturn.java +++ b/Bench4Q-Agent/src/main/java/org/bench4q/agent/plugin/result/LogReturn.java @@ -1,7 +1,7 @@ -package org.bench4q.agent.plugin.result; - -public class LogReturn extends PluginReturn { - public LogReturn(boolean success) { - this.setSuccess(success); - } -} +package org.bench4q.agent.plugin.result; + +public class LogReturn extends PluginReturn { + public LogReturn(boolean success) { + this.setSuccess(success); + } +} diff --git a/src/main/java/org/bench4q/agent/plugin/result/PluginReturn.java b/Bench4Q-Agent/src/main/java/org/bench4q/agent/plugin/result/PluginReturn.java similarity index 100% rename from src/main/java/org/bench4q/agent/plugin/result/PluginReturn.java rename to Bench4Q-Agent/src/main/java/org/bench4q/agent/plugin/result/PluginReturn.java diff --git a/src/main/java/org/bench4q/agent/plugin/result/TimerReturn.java b/Bench4Q-Agent/src/main/java/org/bench4q/agent/plugin/result/TimerReturn.java similarity index 94% rename from src/main/java/org/bench4q/agent/plugin/result/TimerReturn.java rename to Bench4Q-Agent/src/main/java/org/bench4q/agent/plugin/result/TimerReturn.java index 97b7b183..9f3ecad0 100644 --- a/src/main/java/org/bench4q/agent/plugin/result/TimerReturn.java +++ b/Bench4Q-Agent/src/main/java/org/bench4q/agent/plugin/result/TimerReturn.java @@ -1,12 +1,12 @@ -package org.bench4q.agent.plugin.result; - -/** - * - * @author coderfengyun - * - */ -public class TimerReturn extends PluginReturn { - public TimerReturn(boolean success) { - this.setSuccess(success); - } -} +package org.bench4q.agent.plugin.result; + +/** + * + * @author coderfengyun + * + */ +public class TimerReturn extends PluginReturn { + public TimerReturn(boolean success) { + this.setSuccess(success); + } +} diff --git a/src/main/java/org/bench4q/agent/scenario/Batch.java b/Bench4Q-Agent/src/main/java/org/bench4q/agent/scenario/Batch.java similarity index 94% rename from src/main/java/org/bench4q/agent/scenario/Batch.java rename to Bench4Q-Agent/src/main/java/org/bench4q/agent/scenario/Batch.java index 82ee79d2..f05a3a2f 100644 --- a/src/main/java/org/bench4q/agent/scenario/Batch.java +++ b/Bench4Q-Agent/src/main/java/org/bench4q/agent/scenario/Batch.java @@ -1,43 +1,43 @@ -package org.bench4q.agent.scenario; - -import org.bench4q.agent.scenario.behavior.Behavior; - -public class Batch { - private int id; - private int parentId; - private int childId; - private Behavior[] behaviors; - - public int getId() { - return id; - } - - public void setId(int id) { - this.id = id; - } - - public int getParentId() { - return parentId; - } - - public void setParentId(int parentId) { - this.parentId = parentId; - } - - public int getChildId() { - return childId; - } - - public void setChildId(int childId) { - this.childId = childId; - } - - public Behavior[] getBehaviors() { - return behaviors; - } - - public void setBehaviors(Behavior[] behaviors) { - this.behaviors = behaviors; - } - -} +package org.bench4q.agent.scenario; + +import org.bench4q.agent.scenario.behavior.Behavior; + +public class Batch { + private int id; + private int parentId; + private int childId; + private Behavior[] behaviors; + + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + public int getParentId() { + return parentId; + } + + public void setParentId(int parentId) { + this.parentId = parentId; + } + + public int getChildId() { + return childId; + } + + public void setChildId(int childId) { + this.childId = childId; + } + + public Behavior[] getBehaviors() { + return behaviors; + } + + public void setBehaviors(Behavior[] behaviors) { + this.behaviors = behaviors; + } + +} diff --git a/src/main/java/org/bench4q/agent/scenario/BehaviorResult.java b/Bench4Q-Agent/src/main/java/org/bench4q/agent/scenario/BehaviorResult.java similarity index 94% rename from src/main/java/org/bench4q/agent/scenario/BehaviorResult.java rename to Bench4Q-Agent/src/main/java/org/bench4q/agent/scenario/BehaviorResult.java index 501cddc1..3311f076 100644 --- a/src/main/java/org/bench4q/agent/scenario/BehaviorResult.java +++ b/Bench4Q-Agent/src/main/java/org/bench4q/agent/scenario/BehaviorResult.java @@ -1,125 +1,125 @@ -package org.bench4q.agent.scenario; - -import java.util.Date; - -public class BehaviorResult { - private String pluginId; - private String pluginName; - private String behaviorName; - private Date startDate; - private Date endDate; - private long responseTime; - private boolean success; - - private int behaviorId; - private String behaviorUrl; - private long contentLength; - private int statusCode; - private String contentType; - private boolean shouldBeCountResponseTime; - - public String getPluginId() { - return pluginId; - } - - public void setPluginId(String pluginId) { - this.pluginId = pluginId; - } - - public String getPluginName() { - return pluginName; - } - - public void setPluginName(String pluginName) { - this.pluginName = pluginName; - } - - public String getBehaviorName() { - return behaviorName; - } - - public void setBehaviorName(String behaviorName) { - this.behaviorName = behaviorName; - } - - public Date getStartDate() { - return startDate; - } - - public void setStartDate(Date startDate) { - this.startDate = startDate; - } - - public Date getEndDate() { - return endDate; - } - - public void setEndDate(Date endDate) { - this.endDate = endDate; - } - - public long getResponseTime() { - return responseTime; - } - - public void setResponseTime(long responseTime) { - this.responseTime = responseTime; - } - - public boolean isSuccess() { - return success; - } - - public void setSuccess(boolean success) { - this.success = success; - } - - public int getBehaviorId() { - return behaviorId; - } - - public void setBehaviorId(int behaviorId) { - this.behaviorId = behaviorId; - } - - public String getBehaviorUrl() { - return behaviorUrl; - } - - public void setBehaviorUrl(String behaviorUrl) { - this.behaviorUrl = behaviorUrl; - } - - public long getContentLength() { - return contentLength; - } - - public void setContentLength(long contentLength) { - this.contentLength = contentLength; - } - - public int getStatusCode() { - return statusCode; - } - - public void setStatusCode(int statusCode) { - this.statusCode = statusCode; - } - - public String getContentType() { - return contentType; - } - - public void setContentType(String contentType) { - this.contentType = contentType; - } - - public boolean isShouldBeCountResponseTime() { - return shouldBeCountResponseTime; - } - - public void setShouldBeCountResponseTime(boolean shouldBeCountResponseTime) { - this.shouldBeCountResponseTime = shouldBeCountResponseTime; - } - -} +package org.bench4q.agent.scenario; + +import java.util.Date; + +public class BehaviorResult { + private String pluginId; + private String pluginName; + private String behaviorName; + private Date startDate; + private Date endDate; + private long responseTime; + private boolean success; + + private int behaviorId; + private String behaviorUrl; + private long contentLength; + private int statusCode; + private String contentType; + private boolean shouldBeCountResponseTime; + + public String getPluginId() { + return pluginId; + } + + public void setPluginId(String pluginId) { + this.pluginId = pluginId; + } + + public String getPluginName() { + return pluginName; + } + + public void setPluginName(String pluginName) { + this.pluginName = pluginName; + } + + public String getBehaviorName() { + return behaviorName; + } + + public void setBehaviorName(String behaviorName) { + this.behaviorName = behaviorName; + } + + public Date getStartDate() { + return startDate; + } + + public void setStartDate(Date startDate) { + this.startDate = startDate; + } + + public Date getEndDate() { + return endDate; + } + + public void setEndDate(Date endDate) { + this.endDate = endDate; + } + + public long getResponseTime() { + return responseTime; + } + + public void setResponseTime(long responseTime) { + this.responseTime = responseTime; + } + + public boolean isSuccess() { + return success; + } + + public void setSuccess(boolean success) { + this.success = success; + } + + public int getBehaviorId() { + return behaviorId; + } + + public void setBehaviorId(int behaviorId) { + this.behaviorId = behaviorId; + } + + public String getBehaviorUrl() { + return behaviorUrl; + } + + public void setBehaviorUrl(String behaviorUrl) { + this.behaviorUrl = behaviorUrl; + } + + public long getContentLength() { + return contentLength; + } + + public void setContentLength(long contentLength) { + this.contentLength = contentLength; + } + + public int getStatusCode() { + return statusCode; + } + + public void setStatusCode(int statusCode) { + this.statusCode = statusCode; + } + + public String getContentType() { + return contentType; + } + + public void setContentType(String contentType) { + this.contentType = contentType; + } + + public boolean isShouldBeCountResponseTime() { + return shouldBeCountResponseTime; + } + + public void setShouldBeCountResponseTime(boolean shouldBeCountResponseTime) { + this.shouldBeCountResponseTime = shouldBeCountResponseTime; + } + +} diff --git a/src/main/java/org/bench4q/agent/scenario/Page.java b/Bench4Q-Agent/src/main/java/org/bench4q/agent/scenario/Page.java similarity index 100% rename from src/main/java/org/bench4q/agent/scenario/Page.java rename to Bench4Q-Agent/src/main/java/org/bench4q/agent/scenario/Page.java diff --git a/src/main/java/org/bench4q/agent/scenario/PageResult.java b/Bench4Q-Agent/src/main/java/org/bench4q/agent/scenario/PageResult.java similarity index 96% rename from src/main/java/org/bench4q/agent/scenario/PageResult.java rename to Bench4Q-Agent/src/main/java/org/bench4q/agent/scenario/PageResult.java index e9572c94..fcadd468 100644 --- a/src/main/java/org/bench4q/agent/scenario/PageResult.java +++ b/Bench4Q-Agent/src/main/java/org/bench4q/agent/scenario/PageResult.java @@ -1,77 +1,77 @@ -package org.bench4q.agent.scenario; - -import java.util.ArrayList; -import java.util.List; - -public class PageResult { - private int pageId; - private long pageStartTime; - private long pageEndTime; - private long executeRange; - - public int getPageId() { - return pageId; - } - - private void setPageId(int pageId) { - this.pageId = pageId; - } - - public long getPageStartTime() { - return pageStartTime; - } - - private void setPageStartTime(long pageStartTime) { - this.pageStartTime = pageStartTime; - } - - public long getPageEndTime() { - return pageEndTime; - } - - private void setPageEndTime(long pageEndTime) { - this.pageEndTime = pageEndTime; - } - - public long getExecuteRange() { - return executeRange; - } - - private void setExecuteRange(long executeRange) { - this.executeRange = executeRange; - } - - private PageResult() { - init(); - } - - private void init() { - this.setPageStartTime(Long.MAX_VALUE); - this.setPageEndTime(Long.MIN_VALUE); - this.setExecuteRange(0); - } - - public static PageResult buildPageResult(int pageId, - List behaviorResults) { - PageResult result = new PageResult(); - result.setPageId(pageId); - if (behaviorResults == null) { - behaviorResults = new ArrayList(); - } - for (BehaviorResult behaviorResult : behaviorResults) { - if (behaviorResult.getStartDate().getTime() < result - .getPageStartTime()) { - result.setPageStartTime(behaviorResult.getStartDate().getTime()); - } - if (behaviorResult.getEndDate().getTime() > result.getPageEndTime()) { - result.setPageEndTime(behaviorResult.getEndDate().getTime()); - } - // Page excuteRange rely on the behaviors' execute way, if it's - // executed in batch, i should take the longest behavior in batch - // to calculate this One. - } - result.setExecuteRange(result.getPageEndTime() - - result.getPageStartTime()); - return result; - } -} +package org.bench4q.agent.scenario; + +import java.util.ArrayList; +import java.util.List; + +public class PageResult { + private int pageId; + private long pageStartTime; + private long pageEndTime; + private long executeRange; + + public int getPageId() { + return pageId; + } + + private void setPageId(int pageId) { + this.pageId = pageId; + } + + public long getPageStartTime() { + return pageStartTime; + } + + private void setPageStartTime(long pageStartTime) { + this.pageStartTime = pageStartTime; + } + + public long getPageEndTime() { + return pageEndTime; + } + + private void setPageEndTime(long pageEndTime) { + this.pageEndTime = pageEndTime; + } + + public long getExecuteRange() { + return executeRange; + } + + private void setExecuteRange(long executeRange) { + this.executeRange = executeRange; + } + + private PageResult() { + init(); + } + + private void init() { + this.setPageStartTime(Long.MAX_VALUE); + this.setPageEndTime(Long.MIN_VALUE); + this.setExecuteRange(0); + } + + public static PageResult buildPageResult(int pageId, + List behaviorResults) { + PageResult result = new PageResult(); + result.setPageId(pageId); + if (behaviorResults == null) { + behaviorResults = new ArrayList(); + } + for (BehaviorResult behaviorResult : behaviorResults) { + if (behaviorResult.getStartDate().getTime() < result + .getPageStartTime()) { + result.setPageStartTime(behaviorResult.getStartDate().getTime()); + } + if (behaviorResult.getEndDate().getTime() > result.getPageEndTime()) { + result.setPageEndTime(behaviorResult.getEndDate().getTime()); + } + // Page excuteRange rely on the behaviors' execute way, if it's + // executed in batch, i should take the longest behavior in batch + // to calculate this One. + } + result.setExecuteRange(result.getPageEndTime() + - result.getPageStartTime()); + return result; + } +} diff --git a/src/main/java/org/bench4q/agent/scenario/Parameter.java b/Bench4Q-Agent/src/main/java/org/bench4q/agent/scenario/Parameter.java similarity index 93% rename from src/main/java/org/bench4q/agent/scenario/Parameter.java rename to Bench4Q-Agent/src/main/java/org/bench4q/agent/scenario/Parameter.java index 325733d8..10785505 100644 --- a/src/main/java/org/bench4q/agent/scenario/Parameter.java +++ b/Bench4Q-Agent/src/main/java/org/bench4q/agent/scenario/Parameter.java @@ -1,23 +1,23 @@ -package org.bench4q.agent.scenario; - -public class Parameter { - private String key; - private String value; - - public String getKey() { - return key; - } - - public void setKey(String key) { - this.key = key; - } - - public String getValue() { - return value; - } - - public void setValue(String value) { - this.value = value; - } - -} +package org.bench4q.agent.scenario; + +public class Parameter { + private String key; + private String value; + + public String getKey() { + return key; + } + + public void setKey(String key) { + this.key = key; + } + + public String getValue() { + return value; + } + + public void setValue(String value) { + this.value = value; + } + +} diff --git a/src/main/java/org/bench4q/agent/scenario/Scenario.java b/Bench4Q-Agent/src/main/java/org/bench4q/agent/scenario/Scenario.java similarity index 100% rename from src/main/java/org/bench4q/agent/scenario/Scenario.java rename to Bench4Q-Agent/src/main/java/org/bench4q/agent/scenario/Scenario.java diff --git a/src/main/java/org/bench4q/agent/scenario/ScenarioContext.java b/Bench4Q-Agent/src/main/java/org/bench4q/agent/scenario/ScenarioContext.java similarity index 100% rename from src/main/java/org/bench4q/agent/scenario/ScenarioContext.java rename to Bench4Q-Agent/src/main/java/org/bench4q/agent/scenario/ScenarioContext.java diff --git a/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java b/Bench4Q-Agent/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java similarity index 100% rename from src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java rename to Bench4Q-Agent/src/main/java/org/bench4q/agent/scenario/ScenarioEngine.java diff --git a/src/main/java/org/bench4q/agent/scenario/SessionContext.java b/Bench4Q-Agent/src/main/java/org/bench4q/agent/scenario/SessionContext.java similarity index 100% rename from src/main/java/org/bench4q/agent/scenario/SessionContext.java rename to Bench4Q-Agent/src/main/java/org/bench4q/agent/scenario/SessionContext.java diff --git a/src/main/java/org/bench4q/agent/scenario/TestResult.java b/Bench4Q-Agent/src/main/java/org/bench4q/agent/scenario/TestResult.java similarity index 95% rename from src/main/java/org/bench4q/agent/scenario/TestResult.java rename to Bench4Q-Agent/src/main/java/org/bench4q/agent/scenario/TestResult.java index 26c000f3..6457ca30 100644 --- a/src/main/java/org/bench4q/agent/scenario/TestResult.java +++ b/Bench4Q-Agent/src/main/java/org/bench4q/agent/scenario/TestResult.java @@ -1,111 +1,111 @@ -package org.bench4q.agent.scenario; - -import java.io.Serializable; -import java.util.Date; -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 = "testResult") -public class TestResult implements Serializable { - private static final long serialVersionUID = -370091935554266546L; - private UUID runId; - private int poolSize; - private int totalCount; - private Date startDate; - private long elapsedTime; - private int successCount; - private int failCount; - private int finishedCount; - private double averageResponseTime; - private List results; - - @XmlElement - public UUID getRunId() { - return runId; - } - - public void setRunId(UUID runId) { - this.runId = runId; - } - - @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; - } - - @XmlElement - public Date getStartDate() { - return startDate; - } - - public void setStartDate(Date startDate) { - this.startDate = startDate; - } - - public long getElapsedTime() { - return elapsedTime; - } - - public void setElapsedTime(long elapsedTime) { - this.elapsedTime = elapsedTime; - } - - public int getSuccessCount() { - return successCount; - } - - public void setSuccessCount(int successCount) { - this.successCount = successCount; - } - - public int getFailCount() { - return failCount; - } - - public void setFailCount(int failCount) { - this.failCount = failCount; - } - - public int getFinishedCount() { - return finishedCount; - } - - public void setFinishedCount(int finishedCount) { - this.finishedCount = finishedCount; - } - - public double getAverageResponseTime() { - return averageResponseTime; - } - - public void setAverageResponseTime(double averageResponseTime) { - this.averageResponseTime = averageResponseTime; - } - - @XmlElementWrapper(name = "results") - @XmlElement(name = "result") - public List getResults() { - return results; - } - - public void setResults(List results) { - this.results = results; - } -} +package org.bench4q.agent.scenario; + +import java.io.Serializable; +import java.util.Date; +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 = "testResult") +public class TestResult implements Serializable { + private static final long serialVersionUID = -370091935554266546L; + private UUID runId; + private int poolSize; + private int totalCount; + private Date startDate; + private long elapsedTime; + private int successCount; + private int failCount; + private int finishedCount; + private double averageResponseTime; + private List results; + + @XmlElement + public UUID getRunId() { + return runId; + } + + public void setRunId(UUID runId) { + this.runId = runId; + } + + @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; + } + + @XmlElement + public Date getStartDate() { + return startDate; + } + + public void setStartDate(Date startDate) { + this.startDate = startDate; + } + + public long getElapsedTime() { + return elapsedTime; + } + + public void setElapsedTime(long elapsedTime) { + this.elapsedTime = elapsedTime; + } + + public int getSuccessCount() { + return successCount; + } + + public void setSuccessCount(int successCount) { + this.successCount = successCount; + } + + public int getFailCount() { + return failCount; + } + + public void setFailCount(int failCount) { + this.failCount = failCount; + } + + public int getFinishedCount() { + return finishedCount; + } + + public void setFinishedCount(int finishedCount) { + this.finishedCount = finishedCount; + } + + public double getAverageResponseTime() { + return averageResponseTime; + } + + public void setAverageResponseTime(double averageResponseTime) { + this.averageResponseTime = averageResponseTime; + } + + @XmlElementWrapper(name = "results") + @XmlElement(name = "result") + public List getResults() { + return results; + } + + public void setResults(List results) { + this.results = results; + } +} diff --git a/src/main/java/org/bench4q/agent/scenario/TestResultItem.java b/Bench4Q-Agent/src/main/java/org/bench4q/agent/scenario/TestResultItem.java similarity index 94% rename from src/main/java/org/bench4q/agent/scenario/TestResultItem.java rename to Bench4Q-Agent/src/main/java/org/bench4q/agent/scenario/TestResultItem.java index da9e9271..39481fa8 100644 --- a/src/main/java/org/bench4q/agent/scenario/TestResultItem.java +++ b/Bench4Q-Agent/src/main/java/org/bench4q/agent/scenario/TestResultItem.java @@ -1,93 +1,93 @@ -package org.bench4q.agent.scenario; - -import java.io.Serializable; -import java.util.Date; -import java.util.UUID; - -import javax.xml.bind.annotation.XmlElement; -import javax.xml.bind.annotation.XmlRootElement; - -@XmlRootElement(name = "testResultItem") -public class TestResultItem implements Serializable { - private static final long serialVersionUID = 3307951299814477213L; - private UUID id; - private String pluginId; - private String pluginName; - private String behaviorName; - private Date startDate; - private Date endDate; - private long responseTime; - private boolean success; - - @XmlElement - public UUID getId() { - return id; - } - - public void setId(UUID id) { - this.id = id; - } - - @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; - } -} +package org.bench4q.agent.scenario; + +import java.io.Serializable; +import java.util.Date; +import java.util.UUID; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; + +@XmlRootElement(name = "testResultItem") +public class TestResultItem implements Serializable { + private static final long serialVersionUID = 3307951299814477213L; + private UUID id; + private String pluginId; + private String pluginName; + private String behaviorName; + private Date startDate; + private Date endDate; + private long responseTime; + private boolean success; + + @XmlElement + public UUID getId() { + return id; + } + + public void setId(UUID id) { + this.id = id; + } + + @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; + } +} diff --git a/src/main/java/org/bench4q/agent/scenario/UsePlugin.java b/Bench4Q-Agent/src/main/java/org/bench4q/agent/scenario/UsePlugin.java similarity index 93% rename from src/main/java/org/bench4q/agent/scenario/UsePlugin.java rename to Bench4Q-Agent/src/main/java/org/bench4q/agent/scenario/UsePlugin.java index ac353a2f..3e7379dd 100644 --- a/src/main/java/org/bench4q/agent/scenario/UsePlugin.java +++ b/Bench4Q-Agent/src/main/java/org/bench4q/agent/scenario/UsePlugin.java @@ -1,32 +1,32 @@ -package org.bench4q.agent.scenario; - -public class UsePlugin { - private String id; - private String name; - private Parameter[] parameters; - - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public Parameter[] getParameters() { - return parameters; - } - - public void setParameters(Parameter[] parameters) { - this.parameters = parameters; - } - -} +package org.bench4q.agent.scenario; + +public class UsePlugin { + private String id; + private String name; + private Parameter[] parameters; + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Parameter[] getParameters() { + return parameters; + } + + public void setParameters(Parameter[] parameters) { + this.parameters = parameters; + } + +} diff --git a/src/main/java/org/bench4q/agent/scenario/Worker.java b/Bench4Q-Agent/src/main/java/org/bench4q/agent/scenario/Worker.java similarity index 100% rename from src/main/java/org/bench4q/agent/scenario/Worker.java rename to Bench4Q-Agent/src/main/java/org/bench4q/agent/scenario/Worker.java diff --git a/src/main/java/org/bench4q/agent/scenario/behavior/Behavior.java b/Bench4Q-Agent/src/main/java/org/bench4q/agent/scenario/behavior/Behavior.java similarity index 100% rename from src/main/java/org/bench4q/agent/scenario/behavior/Behavior.java rename to Bench4Q-Agent/src/main/java/org/bench4q/agent/scenario/behavior/Behavior.java diff --git a/src/main/java/org/bench4q/agent/scenario/behavior/BehaviorFactory.java b/Bench4Q-Agent/src/main/java/org/bench4q/agent/scenario/behavior/BehaviorFactory.java similarity index 96% rename from src/main/java/org/bench4q/agent/scenario/behavior/BehaviorFactory.java rename to Bench4Q-Agent/src/main/java/org/bench4q/agent/scenario/behavior/BehaviorFactory.java index 9c050110..e5761868 100644 --- a/src/main/java/org/bench4q/agent/scenario/behavior/BehaviorFactory.java +++ b/Bench4Q-Agent/src/main/java/org/bench4q/agent/scenario/behavior/BehaviorFactory.java @@ -1,14 +1,14 @@ -package org.bench4q.agent.scenario.behavior; - -import org.bench4q.share.models.agent.scriptrecord.BehaviorModel; - -public class BehaviorFactory { - public static Behavior getBuisinessObject(BehaviorModel modelInput) { - if (modelInput.getType().equalsIgnoreCase("TIMERBEHAVIOR")) { - return new TimerBehavior(); - } else if (modelInput.getType().equalsIgnoreCase("USERBEHAVIOR")) { - return new UserBehavior(); - } - return null; - } -} +package org.bench4q.agent.scenario.behavior; + +import org.bench4q.share.models.agent.scriptrecord.BehaviorModel; + +public class BehaviorFactory { + public static Behavior getBuisinessObject(BehaviorModel modelInput) { + if (modelInput.getType().equalsIgnoreCase("TIMERBEHAVIOR")) { + return new TimerBehavior(); + } else if (modelInput.getType().equalsIgnoreCase("USERBEHAVIOR")) { + return new UserBehavior(); + } + return null; + } +} diff --git a/src/main/java/org/bench4q/agent/scenario/behavior/TimerBehavior.java b/Bench4Q-Agent/src/main/java/org/bench4q/agent/scenario/behavior/TimerBehavior.java similarity index 100% rename from src/main/java/org/bench4q/agent/scenario/behavior/TimerBehavior.java rename to Bench4Q-Agent/src/main/java/org/bench4q/agent/scenario/behavior/TimerBehavior.java diff --git a/src/main/java/org/bench4q/agent/scenario/behavior/UserBehavior.java b/Bench4Q-Agent/src/main/java/org/bench4q/agent/scenario/behavior/UserBehavior.java similarity index 100% rename from src/main/java/org/bench4q/agent/scenario/behavior/UserBehavior.java rename to Bench4Q-Agent/src/main/java/org/bench4q/agent/scenario/behavior/UserBehavior.java diff --git a/src/main/java/org/bench4q/agent/scenario/util/ParameterParser.java b/Bench4Q-Agent/src/main/java/org/bench4q/agent/scenario/util/ParameterParser.java similarity index 100% rename from src/main/java/org/bench4q/agent/scenario/util/ParameterParser.java rename to Bench4Q-Agent/src/main/java/org/bench4q/agent/scenario/util/ParameterParser.java diff --git a/src/main/java/org/bench4q/agent/scenario/util/Table.java b/Bench4Q-Agent/src/main/java/org/bench4q/agent/scenario/util/Table.java similarity index 100% rename from src/main/java/org/bench4q/agent/scenario/util/Table.java rename to Bench4Q-Agent/src/main/java/org/bench4q/agent/scenario/util/Table.java diff --git a/src/main/java/org/bench4q/agent/share/DealWithLog.java b/Bench4Q-Agent/src/main/java/org/bench4q/agent/share/DealWithLog.java similarity index 96% rename from src/main/java/org/bench4q/agent/share/DealWithLog.java rename to Bench4Q-Agent/src/main/java/org/bench4q/agent/share/DealWithLog.java index d2fca2da..3c18c981 100644 --- a/src/main/java/org/bench4q/agent/share/DealWithLog.java +++ b/Bench4Q-Agent/src/main/java/org/bench4q/agent/share/DealWithLog.java @@ -1,13 +1,13 @@ -package org.bench4q.agent.share; - -import java.io.ByteArrayOutputStream; -import java.io.PrintStream; - -public class DealWithLog { - public static ByteArrayOutputStream getExceptionStackTrace(Exception e) { - ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); - PrintStream printStream = new PrintStream(outputStream); - e.printStackTrace(printStream); - return outputStream; - } -} +package org.bench4q.agent.share; + +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; + +public class DealWithLog { + public static ByteArrayOutputStream getExceptionStackTrace(Exception e) { + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + PrintStream printStream = new PrintStream(outputStream); + e.printStackTrace(printStream); + return outputStream; + } +} diff --git a/src/main/java/org/bench4q/agent/storage/Buffer.java b/Bench4Q-Agent/src/main/java/org/bench4q/agent/storage/Buffer.java similarity index 95% rename from src/main/java/org/bench4q/agent/storage/Buffer.java rename to Bench4Q-Agent/src/main/java/org/bench4q/agent/storage/Buffer.java index 516c9212..a40de8bd 100644 --- a/src/main/java/org/bench4q/agent/storage/Buffer.java +++ b/Bench4Q-Agent/src/main/java/org/bench4q/agent/storage/Buffer.java @@ -1,57 +1,57 @@ -package org.bench4q.agent.storage; - -public class Buffer { - private byte[] content; - private int currentPos; - private int totalSize; - - public byte[] getContent() { - return content; - } - - public void setContent(byte[] content) { - this.content = content; - } - - public int getCurrentPos() { - return currentPos; - } - - public void setCurrentPos(int currentPos) { - this.currentPos = currentPos; - } - - public int getTotalSize() { - return totalSize; - } - - public void setTotalSize(int totalSize) { - this.totalSize = totalSize; - } - - public static Buffer createBuffer(int totalSize) { - Buffer buffer = new Buffer(); - buffer.setContent(new byte[totalSize]); - buffer.setCurrentPos(0); - buffer.setTotalSize(totalSize); - return buffer; - } - - public int getRemainSize() { - return this.totalSize - this.currentPos; - } - - public void reset() { - this.setCurrentPos(0); - } - - public void setFull() { - this.setCurrentPos(this.getTotalSize()); - } - - void writeToCurrentBuffer(int size, byte[] cache) { - System.arraycopy(cache, 0, this.getContent(), this.getCurrentPos(), - size); - this.setCurrentPos(this.getCurrentPos() + size); - } -} +package org.bench4q.agent.storage; + +public class Buffer { + private byte[] content; + private int currentPos; + private int totalSize; + + public byte[] getContent() { + return content; + } + + public void setContent(byte[] content) { + this.content = content; + } + + public int getCurrentPos() { + return currentPos; + } + + public void setCurrentPos(int currentPos) { + this.currentPos = currentPos; + } + + public int getTotalSize() { + return totalSize; + } + + public void setTotalSize(int totalSize) { + this.totalSize = totalSize; + } + + public static Buffer createBuffer(int totalSize) { + Buffer buffer = new Buffer(); + buffer.setContent(new byte[totalSize]); + buffer.setCurrentPos(0); + buffer.setTotalSize(totalSize); + return buffer; + } + + public int getRemainSize() { + return this.totalSize - this.currentPos; + } + + public void reset() { + this.setCurrentPos(0); + } + + public void setFull() { + this.setCurrentPos(this.getTotalSize()); + } + + void writeToCurrentBuffer(int size, byte[] cache) { + System.arraycopy(cache, 0, this.getContent(), this.getCurrentPos(), + size); + this.setCurrentPos(this.getCurrentPos() + size); + } +} diff --git a/src/main/java/org/bench4q/agent/storage/DoubleBufferStorage.java b/Bench4Q-Agent/src/main/java/org/bench4q/agent/storage/DoubleBufferStorage.java similarity index 96% rename from src/main/java/org/bench4q/agent/storage/DoubleBufferStorage.java rename to Bench4Q-Agent/src/main/java/org/bench4q/agent/storage/DoubleBufferStorage.java index b59ff924..f92f050e 100644 --- a/src/main/java/org/bench4q/agent/storage/DoubleBufferStorage.java +++ b/Bench4Q-Agent/src/main/java/org/bench4q/agent/storage/DoubleBufferStorage.java @@ -1,157 +1,157 @@ -package org.bench4q.agent.storage; - -import java.io.ByteArrayInputStream; -import java.io.File; -import java.io.FilenameFilter; -import java.nio.charset.Charset; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; - -import org.bench4q.share.models.agent.CleanTestResultModel; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; - -@Component -public class DoubleBufferStorage { - private static final int THRESHOLD = 1024; - private static Charset charset = Charset.forName("utf-8"); - private static int BUFFER_SIZE = 48 * 1024; - private List bufferList; - private int currentBufferIndex; - private LocalStorage localStorage; - public CleanTestResultModel forTest = new CleanTestResultModel(); - - private int getCurrentBufferIndex() { - return currentBufferIndex; - } - - private void setCurrentBufferIndex(int currentBuffer) { - this.currentBufferIndex = currentBuffer; - } - - private List getBufferList() { - return bufferList; - } - - private void setBufferList(List bufferList) { - this.bufferList = bufferList; - } - - private LocalStorage getLocalStorage() { - return localStorage; - } - - @Autowired - private void setLocalStorage(LocalStorage localStorage) { - this.localStorage = localStorage; - } - - public DoubleBufferStorage() { - this.setBufferList(new ArrayList()); - this.getBufferList().add(Buffer.createBuffer(BUFFER_SIZE)); - this.getBufferList().add(Buffer.createBuffer(BUFFER_SIZE)); - this.setCurrentBufferIndex(0); - } - - public String readFiles(String pathPrefix) { - int pos = pathPrefix.lastIndexOf(System.getProperty("file.separator")); - String dirPath = pathPrefix.substring(0, pos); - final String prefix = pathPrefix.substring(pos + 1); - String result = new String(); - - File dirFile = new File(dirPath); - if (!dirFile.exists()) { - return ""; - } - File[] files = dirFile.listFiles(new FilenameFilter() { - public boolean accept(File dir, String name) { - return name.contains(prefix); - } - }); - for (File file : files) { - if (!file.exists()) { - continue; - } - result += this.getLocalStorage().readFile(file.getAbsolutePath()); - } - return result; - } - - public boolean writeFile(String content, String path) { - ByteArrayInputStream inputStream = new ByteArrayInputStream( - content.getBytes(charset)); - int size = -1; - byte[] cache = new byte[THRESHOLD]; - while ((size = inputStream.read(cache, 0, THRESHOLD)) != -1) { - if (isCurrentBufferFull(size)) { - doSave(calculateSavePath(path)); - changeToTheMaxRemainBuffer(); - } - this.getCurrentBuffer().writeToCurrentBuffer(size, cache); - } - return true; - } - - private boolean isCurrentBufferFull(int size) { - return getCurrentBuffer().getRemainSize() <= THRESHOLD + size; - } - - public String calculateSavePath(String path, int index) { - return path.substring(0, path.lastIndexOf(".")) + "_" + index + ".xml"; - } - - private String calculateSavePath(String path) { - return calculateSavePath(path, this.getCurrentBufferIndex()); - } - - private void doSave(final String path) { - final Buffer bufferUnderSave = this.getCurrentBuffer(); - final String writeContent = this.getMeaningfulContent(); - Runnable runnable = new Runnable() { - public void run() { - getLocalStorage().writeFile(writeContent, path); - bufferUnderSave.reset(); - forTest.setSuccess(true); - } - }; - ExecutorService service = Executors.newFixedThreadPool(1); - service.execute(runnable); - service.shutdown(); - - } - - private String getMeaningfulContent() { - byte[] meaningfulContent = new byte[getCurrentBuffer().getCurrentPos()]; - System.arraycopy(getCurrentBuffer().getContent(), 0, meaningfulContent, - 0, getCurrentBuffer().getCurrentPos()); - return new String(meaningfulContent); - } - - private void changeToTheMaxRemainBuffer() { - int maxRemainSize = 2 * THRESHOLD; - int maxRemainSizeBufferIndex = -1; - for (int i = 0; i < this.getBufferList().size(); ++i) { - System.out.println(i + " remain : " - + this.getBufferList().get(i).getRemainSize()); - if (this.getBufferList().get(i).getRemainSize() > maxRemainSize) { - maxRemainSize = this.getBufferList().get(i).getRemainSize(); - maxRemainSizeBufferIndex = i; - } - } - if (maxRemainSizeBufferIndex == -1) { - this.getBufferList().add(Buffer.createBuffer(BUFFER_SIZE)); - maxRemainSizeBufferIndex = this.getBufferList().size() - 1; - } - this.setCurrentBufferIndex(maxRemainSizeBufferIndex); - } - - private Buffer getCurrentBuffer() { - return this.getBufferList().get(this.getCurrentBufferIndex()); - } - - public void flush() { - - } -} +package org.bench4q.agent.storage; + +import java.io.ByteArrayInputStream; +import java.io.File; +import java.io.FilenameFilter; +import java.nio.charset.Charset; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; + +import org.bench4q.share.models.agent.CleanTestResultModel; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +@Component +public class DoubleBufferStorage { + private static final int THRESHOLD = 1024; + private static Charset charset = Charset.forName("utf-8"); + private static int BUFFER_SIZE = 48 * 1024; + private List bufferList; + private int currentBufferIndex; + private LocalStorage localStorage; + public CleanTestResultModel forTest = new CleanTestResultModel(); + + private int getCurrentBufferIndex() { + return currentBufferIndex; + } + + private void setCurrentBufferIndex(int currentBuffer) { + this.currentBufferIndex = currentBuffer; + } + + private List getBufferList() { + return bufferList; + } + + private void setBufferList(List bufferList) { + this.bufferList = bufferList; + } + + private LocalStorage getLocalStorage() { + return localStorage; + } + + @Autowired + private void setLocalStorage(LocalStorage localStorage) { + this.localStorage = localStorage; + } + + public DoubleBufferStorage() { + this.setBufferList(new ArrayList()); + this.getBufferList().add(Buffer.createBuffer(BUFFER_SIZE)); + this.getBufferList().add(Buffer.createBuffer(BUFFER_SIZE)); + this.setCurrentBufferIndex(0); + } + + public String readFiles(String pathPrefix) { + int pos = pathPrefix.lastIndexOf(System.getProperty("file.separator")); + String dirPath = pathPrefix.substring(0, pos); + final String prefix = pathPrefix.substring(pos + 1); + String result = new String(); + + File dirFile = new File(dirPath); + if (!dirFile.exists()) { + return ""; + } + File[] files = dirFile.listFiles(new FilenameFilter() { + public boolean accept(File dir, String name) { + return name.contains(prefix); + } + }); + for (File file : files) { + if (!file.exists()) { + continue; + } + result += this.getLocalStorage().readFile(file.getAbsolutePath()); + } + return result; + } + + public boolean writeFile(String content, String path) { + ByteArrayInputStream inputStream = new ByteArrayInputStream( + content.getBytes(charset)); + int size = -1; + byte[] cache = new byte[THRESHOLD]; + while ((size = inputStream.read(cache, 0, THRESHOLD)) != -1) { + if (isCurrentBufferFull(size)) { + doSave(calculateSavePath(path)); + changeToTheMaxRemainBuffer(); + } + this.getCurrentBuffer().writeToCurrentBuffer(size, cache); + } + return true; + } + + private boolean isCurrentBufferFull(int size) { + return getCurrentBuffer().getRemainSize() <= THRESHOLD + size; + } + + public String calculateSavePath(String path, int index) { + return path.substring(0, path.lastIndexOf(".")) + "_" + index + ".xml"; + } + + private String calculateSavePath(String path) { + return calculateSavePath(path, this.getCurrentBufferIndex()); + } + + private void doSave(final String path) { + final Buffer bufferUnderSave = this.getCurrentBuffer(); + final String writeContent = this.getMeaningfulContent(); + Runnable runnable = new Runnable() { + public void run() { + getLocalStorage().writeFile(writeContent, path); + bufferUnderSave.reset(); + forTest.setSuccess(true); + } + }; + ExecutorService service = Executors.newFixedThreadPool(1); + service.execute(runnable); + service.shutdown(); + + } + + private String getMeaningfulContent() { + byte[] meaningfulContent = new byte[getCurrentBuffer().getCurrentPos()]; + System.arraycopy(getCurrentBuffer().getContent(), 0, meaningfulContent, + 0, getCurrentBuffer().getCurrentPos()); + return new String(meaningfulContent); + } + + private void changeToTheMaxRemainBuffer() { + int maxRemainSize = 2 * THRESHOLD; + int maxRemainSizeBufferIndex = -1; + for (int i = 0; i < this.getBufferList().size(); ++i) { + System.out.println(i + " remain : " + + this.getBufferList().get(i).getRemainSize()); + if (this.getBufferList().get(i).getRemainSize() > maxRemainSize) { + maxRemainSize = this.getBufferList().get(i).getRemainSize(); + maxRemainSizeBufferIndex = i; + } + } + if (maxRemainSizeBufferIndex == -1) { + this.getBufferList().add(Buffer.createBuffer(BUFFER_SIZE)); + maxRemainSizeBufferIndex = this.getBufferList().size() - 1; + } + this.setCurrentBufferIndex(maxRemainSizeBufferIndex); + } + + private Buffer getCurrentBuffer() { + return this.getBufferList().get(this.getCurrentBufferIndex()); + } + + public void flush() { + + } +} diff --git a/src/main/java/org/bench4q/agent/storage/HdfsStorage.java b/Bench4Q-Agent/src/main/java/org/bench4q/agent/storage/HdfsStorage.java similarity index 96% rename from src/main/java/org/bench4q/agent/storage/HdfsStorage.java rename to Bench4Q-Agent/src/main/java/org/bench4q/agent/storage/HdfsStorage.java index 8738ef3b..9d9e0694 100644 --- a/src/main/java/org/bench4q/agent/storage/HdfsStorage.java +++ b/Bench4Q-Agent/src/main/java/org/bench4q/agent/storage/HdfsStorage.java @@ -1,140 +1,140 @@ -package org.bench4q.agent.storage; - -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; - -import org.apache.hadoop.conf.Configuration; -import org.apache.hadoop.fs.FSDataInputStream; -import org.apache.hadoop.fs.FSDataOutputStream; -import org.apache.hadoop.fs.FileStatus; -import org.apache.hadoop.fs.FileSystem; -import org.apache.hadoop.fs.Path; -import org.apache.hadoop.io.IOUtils; -import org.springframework.stereotype.Component; - -@Component -public class HdfsStorage implements Storage { - private FileSystem getFileSystem() throws IOException { - Configuration conf = new Configuration(); - conf.set("mapred.jop.tracker", "hdfs://133.133.12.21:9001"); - conf.set("fs.default.name", "hdfs://133.133.12.21:9000"); - return FileSystem.get(conf); - } - - public boolean uploadFile(String localPath, String remotePath) { - try { - FileSystem fs = this.getFileSystem(); - fs.copyFromLocalFile(new Path(localPath), new Path(remotePath)); - return true; - } catch (Exception e) { - e.printStackTrace(); - return false; - } - } - - public boolean writeFile(String content, String remotePath) { - try { - InputStream in = new ByteArrayInputStream(content.getBytes()); - FileSystem fs = this.getFileSystem(); - OutputStream out = fs.create(new Path(remotePath)); - IOUtils.copyBytes(in, out, 4096, true); - return true; - } catch (Exception e) { - e.printStackTrace(); - return false; - } - } - - public boolean downloadFile(String localPath, String remotePath) { - try { - FileSystem fs = this.getFileSystem(); - fs.copyToLocalFile(new Path(remotePath), new Path(localPath)); - return true; - } catch (Exception e) { - e.printStackTrace(); - return false; - } - } - - public String readFile(String remotePath) { - try { - FileSystem fs = this.getFileSystem(); - FSDataInputStream hdfsInStream = fs.open(new Path(remotePath)); - OutputStream out = new ByteArrayOutputStream(); - byte[] ioBuffer = new byte[1024]; - int readLen = hdfsInStream.read(ioBuffer); - while (-1 != readLen) { - out.write(ioBuffer, 0, readLen); - readLen = hdfsInStream.read(ioBuffer); - } - out.close(); - String ret = out.toString(); - hdfsInStream.close(); - return ret; - } catch (Exception e) { - e.printStackTrace(); - return null; - } - } - - public boolean appendFile(String content, String remotePath) { - try { - FileSystem fs = this.getFileSystem(); - FSDataOutputStream out = fs.append(new Path(remotePath)); - int readLen = content.getBytes().length; - while (-1 != readLen) { - out.write(content.getBytes(), 0, readLen); - } - out.close(); - return true; - } catch (Exception e) { - e.printStackTrace(); - return false; - } - } - - public boolean deleteFile(String remotePath) { - try { - FileSystem fs = this.getFileSystem(); - return fs.delete(new Path(remotePath), false); - } catch (Exception e) { - e.printStackTrace(); - return false; - } - } - - public boolean deleteDirectory(String remotePath) { - try { - FileSystem fs = this.getFileSystem(); - return fs.delete(new Path(remotePath), true); - } catch (Exception e) { - e.printStackTrace(); - return false; - } - } - - public boolean renameFile(String fromPath, String toPath) { - try { - FileSystem fs = this.getFileSystem(); - return fs.rename(new Path(fromPath), new Path(toPath)); - } catch (Exception e) { - e.printStackTrace(); - return false; - } - } - - public FileStatus[] listFile(String remotePath) { - try { - FileSystem fs = this.getFileSystem(); - FileStatus[] fileList = fs.listStatus(new Path(remotePath)); - return fileList; - } catch (Exception e) { - e.printStackTrace(); - return null; - } - } - -} +package org.bench4q.agent.storage; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; + +import org.apache.hadoop.conf.Configuration; +import org.apache.hadoop.fs.FSDataInputStream; +import org.apache.hadoop.fs.FSDataOutputStream; +import org.apache.hadoop.fs.FileStatus; +import org.apache.hadoop.fs.FileSystem; +import org.apache.hadoop.fs.Path; +import org.apache.hadoop.io.IOUtils; +import org.springframework.stereotype.Component; + +@Component +public class HdfsStorage implements Storage { + private FileSystem getFileSystem() throws IOException { + Configuration conf = new Configuration(); + conf.set("mapred.jop.tracker", "hdfs://133.133.12.21:9001"); + conf.set("fs.default.name", "hdfs://133.133.12.21:9000"); + return FileSystem.get(conf); + } + + public boolean uploadFile(String localPath, String remotePath) { + try { + FileSystem fs = this.getFileSystem(); + fs.copyFromLocalFile(new Path(localPath), new Path(remotePath)); + return true; + } catch (Exception e) { + e.printStackTrace(); + return false; + } + } + + public boolean writeFile(String content, String remotePath) { + try { + InputStream in = new ByteArrayInputStream(content.getBytes()); + FileSystem fs = this.getFileSystem(); + OutputStream out = fs.create(new Path(remotePath)); + IOUtils.copyBytes(in, out, 4096, true); + return true; + } catch (Exception e) { + e.printStackTrace(); + return false; + } + } + + public boolean downloadFile(String localPath, String remotePath) { + try { + FileSystem fs = this.getFileSystem(); + fs.copyToLocalFile(new Path(remotePath), new Path(localPath)); + return true; + } catch (Exception e) { + e.printStackTrace(); + return false; + } + } + + public String readFile(String remotePath) { + try { + FileSystem fs = this.getFileSystem(); + FSDataInputStream hdfsInStream = fs.open(new Path(remotePath)); + OutputStream out = new ByteArrayOutputStream(); + byte[] ioBuffer = new byte[1024]; + int readLen = hdfsInStream.read(ioBuffer); + while (-1 != readLen) { + out.write(ioBuffer, 0, readLen); + readLen = hdfsInStream.read(ioBuffer); + } + out.close(); + String ret = out.toString(); + hdfsInStream.close(); + return ret; + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } + + public boolean appendFile(String content, String remotePath) { + try { + FileSystem fs = this.getFileSystem(); + FSDataOutputStream out = fs.append(new Path(remotePath)); + int readLen = content.getBytes().length; + while (-1 != readLen) { + out.write(content.getBytes(), 0, readLen); + } + out.close(); + return true; + } catch (Exception e) { + e.printStackTrace(); + return false; + } + } + + public boolean deleteFile(String remotePath) { + try { + FileSystem fs = this.getFileSystem(); + return fs.delete(new Path(remotePath), false); + } catch (Exception e) { + e.printStackTrace(); + return false; + } + } + + public boolean deleteDirectory(String remotePath) { + try { + FileSystem fs = this.getFileSystem(); + return fs.delete(new Path(remotePath), true); + } catch (Exception e) { + e.printStackTrace(); + return false; + } + } + + public boolean renameFile(String fromPath, String toPath) { + try { + FileSystem fs = this.getFileSystem(); + return fs.rename(new Path(fromPath), new Path(toPath)); + } catch (Exception e) { + e.printStackTrace(); + return false; + } + } + + public FileStatus[] listFile(String remotePath) { + try { + FileSystem fs = this.getFileSystem(); + FileStatus[] fileList = fs.listStatus(new Path(remotePath)); + return fileList; + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } + +} diff --git a/src/main/java/org/bench4q/agent/storage/LocalStorage.java b/Bench4Q-Agent/src/main/java/org/bench4q/agent/storage/LocalStorage.java similarity index 100% rename from src/main/java/org/bench4q/agent/storage/LocalStorage.java rename to Bench4Q-Agent/src/main/java/org/bench4q/agent/storage/LocalStorage.java diff --git a/src/main/java/org/bench4q/agent/storage/MooseStorage.java b/Bench4Q-Agent/src/main/java/org/bench4q/agent/storage/MooseStorage.java similarity index 94% rename from src/main/java/org/bench4q/agent/storage/MooseStorage.java rename to Bench4Q-Agent/src/main/java/org/bench4q/agent/storage/MooseStorage.java index 729e8520..ec8eabfb 100644 --- a/src/main/java/org/bench4q/agent/storage/MooseStorage.java +++ b/Bench4Q-Agent/src/main/java/org/bench4q/agent/storage/MooseStorage.java @@ -1,17 +1,17 @@ -package org.bench4q.agent.storage; - -import org.springframework.stereotype.Component; - -@Component -public class MooseStorage implements Storage { - - public String readFile(String path) { - - return null; - } - - public boolean writeFile(String content, String path) { - return false; - } - -} +package org.bench4q.agent.storage; + +import org.springframework.stereotype.Component; + +@Component +public class MooseStorage implements Storage { + + public String readFile(String path) { + + return null; + } + + public boolean writeFile(String content, String path) { + return false; + } + +} diff --git a/src/main/java/org/bench4q/agent/storage/Storage.java b/Bench4Q-Agent/src/main/java/org/bench4q/agent/storage/Storage.java similarity index 100% rename from src/main/java/org/bench4q/agent/storage/Storage.java rename to Bench4Q-Agent/src/main/java/org/bench4q/agent/storage/Storage.java diff --git a/src/main/java/org/bench4q/agent/storage/StorageHelper.java b/Bench4Q-Agent/src/main/java/org/bench4q/agent/storage/StorageHelper.java similarity index 100% rename from src/main/java/org/bench4q/agent/storage/StorageHelper.java rename to Bench4Q-Agent/src/main/java/org/bench4q/agent/storage/StorageHelper.java diff --git a/src/main/resources/log4j.properties b/Bench4Q-Agent/src/main/resources/log4j.properties similarity index 97% rename from src/main/resources/log4j.properties rename to Bench4Q-Agent/src/main/resources/log4j.properties index 92df3136..0fa2c1c5 100644 --- a/src/main/resources/log4j.properties +++ b/Bench4Q-Agent/src/main/resources/log4j.properties @@ -1,31 +1,31 @@ -log4j.rootLogger = INFO,WARN,ERROR,FALTAL,D - -log4j.appender.WARN = org.apache.log4j.DailyRollingFileAppender -log4j.appender.WARN.File = logs/log.log -log4j.appender.WARN.Append = true -log4j.appender.WARN.Threshold = WARN -log4j.appender.WARN.layout = org.apache.log4j.PatternLayout -log4j.appender.WARN.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n - -log4j.appender.ERROR = org.apache.log4j.DailyRollingFileAppender -log4j.appender.ERROR.File = logs/log.log -log4j.appender.ERROR.Append = true -log4j.appender.ERROR.Threshold = ERROR -log4j.appender.ERROR.layout = org.apache.log4j.PatternLayout -log4j.appender.ERROR.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n - -log4j.appender.FALTAL = org.apache.log4j.DailyRollingFileAppender -log4j.appender.FALTAL.File = logs/log.log -log4j.appender.FALTAL.Append = true -log4j.appender.FALTAL.Threshold = ERROR -log4j.appender.FALTAL.layout = org.apache.log4j.PatternLayout -log4j.appender.FALTAL.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n - - -log4j.appender.D = org.apache.log4j.DailyRollingFileAppender -log4j.appender.D.File = logs/log.log -log4j.appender.D.Append = true -log4j.appender.D.Threshold = INFO -log4j.appender.D.layout = org.apache.log4j.PatternLayout -log4j.appender.D.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n - +log4j.rootLogger = INFO,WARN,ERROR,FALTAL,D + +log4j.appender.WARN = org.apache.log4j.DailyRollingFileAppender +log4j.appender.WARN.File = logs/log.log +log4j.appender.WARN.Append = true +log4j.appender.WARN.Threshold = WARN +log4j.appender.WARN.layout = org.apache.log4j.PatternLayout +log4j.appender.WARN.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n + +log4j.appender.ERROR = org.apache.log4j.DailyRollingFileAppender +log4j.appender.ERROR.File = logs/log.log +log4j.appender.ERROR.Append = true +log4j.appender.ERROR.Threshold = ERROR +log4j.appender.ERROR.layout = org.apache.log4j.PatternLayout +log4j.appender.ERROR.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n + +log4j.appender.FALTAL = org.apache.log4j.DailyRollingFileAppender +log4j.appender.FALTAL.File = logs/log.log +log4j.appender.FALTAL.Append = true +log4j.appender.FALTAL.Threshold = ERROR +log4j.appender.FALTAL.layout = org.apache.log4j.PatternLayout +log4j.appender.FALTAL.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n + + +log4j.appender.D = org.apache.log4j.DailyRollingFileAppender +log4j.appender.D.File = logs/log.log +log4j.appender.D.Append = true +log4j.appender.D.Threshold = INFO +log4j.appender.D.layout = org.apache.log4j.PatternLayout +log4j.appender.D.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n + diff --git a/src/main/resources/org/bench4q/agent/config/application-context.xml b/Bench4Q-Agent/src/main/resources/org/bench4q/agent/config/application-context.xml similarity index 100% rename from src/main/resources/org/bench4q/agent/config/application-context.xml rename to Bench4Q-Agent/src/main/resources/org/bench4q/agent/config/application-context.xml diff --git a/src/test/java/org/bench4q/agent/test/ExtractScenarioTest.java b/Bench4Q-Agent/src/test/java/org/bench4q/agent/test/ExtractScenarioTest.java similarity index 96% rename from src/test/java/org/bench4q/agent/test/ExtractScenarioTest.java rename to Bench4Q-Agent/src/test/java/org/bench4q/agent/test/ExtractScenarioTest.java index f6e137e8..8912eea5 100644 --- a/src/test/java/org/bench4q/agent/test/ExtractScenarioTest.java +++ b/Bench4Q-Agent/src/test/java/org/bench4q/agent/test/ExtractScenarioTest.java @@ -1,27 +1,27 @@ -package org.bench4q.agent.test; - -import static org.junit.Assert.*; - -import java.io.File; -import java.io.IOException; - -import javax.xml.bind.JAXBException; - -import org.apache.commons.io.FileUtils; -import org.bench4q.agent.scenario.Scenario; -import org.bench4q.share.helper.MarshalHelper; -import org.bench4q.share.models.agent.RunScenarioModel; -import org.junit.Test; - -public class ExtractScenarioTest { - - @Test - public void test() throws JAXBException, IOException { - RunScenarioModel runScenarioModel = (RunScenarioModel) MarshalHelper - .unmarshal(RunScenarioModel.class, FileUtils - .readFileToString(new File("Scripts/goodForPage.xml"))); - Scenario scenario = Scenario.scenarioBuilder(runScenarioModel); - - assertTrue(scenario.getPages().length > 0); - } -} +package org.bench4q.agent.test; + +import static org.junit.Assert.*; + +import java.io.File; +import java.io.IOException; + +import javax.xml.bind.JAXBException; + +import org.apache.commons.io.FileUtils; +import org.bench4q.agent.scenario.Scenario; +import org.bench4q.share.helper.MarshalHelper; +import org.bench4q.share.models.agent.RunScenarioModel; +import org.junit.Test; + +public class ExtractScenarioTest { + + @Test + public void test() throws JAXBException, IOException { + RunScenarioModel runScenarioModel = (RunScenarioModel) MarshalHelper + .unmarshal(RunScenarioModel.class, FileUtils + .readFileToString(new File("Scripts/goodForPage.xml"))); + Scenario scenario = Scenario.scenarioBuilder(runScenarioModel); + + assertTrue(scenario.getPages().length > 0); + } +} diff --git a/src/test/java/org/bench4q/agent/test/HomeControllerTest.java b/Bench4Q-Agent/src/test/java/org/bench4q/agent/test/HomeControllerTest.java similarity index 93% rename from src/test/java/org/bench4q/agent/test/HomeControllerTest.java rename to Bench4Q-Agent/src/test/java/org/bench4q/agent/test/HomeControllerTest.java index b71431f8..6902b437 100644 --- a/src/test/java/org/bench4q/agent/test/HomeControllerTest.java +++ b/Bench4Q-Agent/src/test/java/org/bench4q/agent/test/HomeControllerTest.java @@ -1,5 +1,5 @@ -package org.bench4q.agent.test; - -public class HomeControllerTest { - -} +package org.bench4q.agent.test; + +public class HomeControllerTest { + +} diff --git a/src/test/java/org/bench4q/agent/test/MainTest.java b/Bench4Q-Agent/src/test/java/org/bench4q/agent/test/MainTest.java similarity index 100% rename from src/test/java/org/bench4q/agent/test/MainTest.java rename to Bench4Q-Agent/src/test/java/org/bench4q/agent/test/MainTest.java diff --git a/src/test/java/org/bench4q/agent/test/PluginControllerTest.java b/Bench4Q-Agent/src/test/java/org/bench4q/agent/test/PluginControllerTest.java similarity index 93% rename from src/test/java/org/bench4q/agent/test/PluginControllerTest.java rename to Bench4Q-Agent/src/test/java/org/bench4q/agent/test/PluginControllerTest.java index f800f1b5..ca35983c 100644 --- a/src/test/java/org/bench4q/agent/test/PluginControllerTest.java +++ b/Bench4Q-Agent/src/test/java/org/bench4q/agent/test/PluginControllerTest.java @@ -1,5 +1,5 @@ -package org.bench4q.agent.test; - -public class PluginControllerTest { - -} +package org.bench4q.agent.test; + +public class PluginControllerTest { + +} diff --git a/src/test/java/org/bench4q/agent/test/TestWithScriptFile.java b/Bench4Q-Agent/src/test/java/org/bench4q/agent/test/TestWithScriptFile.java similarity index 100% rename from src/test/java/org/bench4q/agent/test/TestWithScriptFile.java rename to Bench4Q-Agent/src/test/java/org/bench4q/agent/test/TestWithScriptFile.java diff --git a/src/test/java/org/bench4q/agent/test/datastatistics/DetailStatisticsTest.java b/Bench4Q-Agent/src/test/java/org/bench4q/agent/test/datastatistics/DetailStatisticsTest.java similarity index 100% rename from src/test/java/org/bench4q/agent/test/datastatistics/DetailStatisticsTest.java rename to Bench4Q-Agent/src/test/java/org/bench4q/agent/test/datastatistics/DetailStatisticsTest.java diff --git a/src/test/java/org/bench4q/agent/test/datastatistics/PageResultStatisticsTest.java b/Bench4Q-Agent/src/test/java/org/bench4q/agent/test/datastatistics/PageResultStatisticsTest.java similarity index 100% rename from src/test/java/org/bench4q/agent/test/datastatistics/PageResultStatisticsTest.java rename to Bench4Q-Agent/src/test/java/org/bench4q/agent/test/datastatistics/PageResultStatisticsTest.java diff --git a/src/test/java/org/bench4q/agent/test/datastatistics/ScenarioStatisticsTest.java b/Bench4Q-Agent/src/test/java/org/bench4q/agent/test/datastatistics/ScenarioStatisticsTest.java similarity index 100% rename from src/test/java/org/bench4q/agent/test/datastatistics/ScenarioStatisticsTest.java rename to Bench4Q-Agent/src/test/java/org/bench4q/agent/test/datastatistics/ScenarioStatisticsTest.java diff --git a/src/test/java/org/bench4q/agent/test/model/ModelTest.java b/Bench4Q-Agent/src/test/java/org/bench4q/agent/test/model/ModelTest.java similarity index 96% rename from src/test/java/org/bench4q/agent/test/model/ModelTest.java rename to Bench4Q-Agent/src/test/java/org/bench4q/agent/test/model/ModelTest.java index 698d2df9..b11ce4b3 100644 --- a/src/test/java/org/bench4q/agent/test/model/ModelTest.java +++ b/Bench4Q-Agent/src/test/java/org/bench4q/agent/test/model/ModelTest.java @@ -1,30 +1,30 @@ -package org.bench4q.agent.test.model; - -import java.io.File; -import java.io.IOException; - -import javax.xml.bind.JAXBContext; -import javax.xml.bind.JAXBException; -import javax.xml.bind.annotation.XmlRootElement; - -import org.bench4q.share.models.agent.scriptrecord.BehaviorModel; -import org.junit.Test; - -import static org.junit.Assert.*; - -@XmlRootElement(name = "modelTest") -public class ModelTest { - - @Test - public void unmarshalVerify() throws IOException, JAXBException { - Object object = JAXBContext - .newInstance(BehaviorModel.class) - .createUnmarshaller() - .unmarshal( - new File("Scripts" - + System.getProperty("file.separator") - + "behaviorModel.xml")); - assertTrue(object instanceof BehaviorModel); - } - -} +package org.bench4q.agent.test.model; + +import java.io.File; +import java.io.IOException; + +import javax.xml.bind.JAXBContext; +import javax.xml.bind.JAXBException; +import javax.xml.bind.annotation.XmlRootElement; + +import org.bench4q.share.models.agent.scriptrecord.BehaviorModel; +import org.junit.Test; + +import static org.junit.Assert.*; + +@XmlRootElement(name = "modelTest") +public class ModelTest { + + @Test + public void unmarshalVerify() throws IOException, JAXBException { + Object object = JAXBContext + .newInstance(BehaviorModel.class) + .createUnmarshaller() + .unmarshal( + new File("Scripts" + + System.getProperty("file.separator") + + "behaviorModel.xml")); + assertTrue(object instanceof BehaviorModel); + } + +} diff --git a/src/test/java/org/bench4q/agent/test/model/UserBehaviorModelTest.java b/Bench4Q-Agent/src/test/java/org/bench4q/agent/test/model/UserBehaviorModelTest.java similarity index 96% rename from src/test/java/org/bench4q/agent/test/model/UserBehaviorModelTest.java rename to Bench4Q-Agent/src/test/java/org/bench4q/agent/test/model/UserBehaviorModelTest.java index 6be857b2..c74138d7 100644 --- a/src/test/java/org/bench4q/agent/test/model/UserBehaviorModelTest.java +++ b/Bench4Q-Agent/src/test/java/org/bench4q/agent/test/model/UserBehaviorModelTest.java @@ -1,26 +1,26 @@ -package org.bench4q.agent.test.model; - -import static org.junit.Assert.*; - -import java.io.File; - -import javax.xml.bind.JAXBContext; -import javax.xml.bind.JAXBException; -import javax.xml.bind.Unmarshaller; - -import org.bench4q.share.models.agent.scriptrecord.BehaviorModel; -import org.junit.Test; - -public class UserBehaviorModelTest { - - @Test - public void testUnmarshal() throws JAXBException { - Unmarshaller unmarshaller = JAXBContext.newInstance( - BehaviorModel.class).createUnmarshaller(); - Object object = unmarshaller.unmarshal(new File("Scripts" - + System.getProperty("file.separator") + "behaviorModel.xml")); - BehaviorModel userBehaviorModel = (BehaviorModel) object; - System.out.println(userBehaviorModel.getUse()); - assertTrue(object instanceof BehaviorModel); - } -} +package org.bench4q.agent.test.model; + +import static org.junit.Assert.*; + +import java.io.File; + +import javax.xml.bind.JAXBContext; +import javax.xml.bind.JAXBException; +import javax.xml.bind.Unmarshaller; + +import org.bench4q.share.models.agent.scriptrecord.BehaviorModel; +import org.junit.Test; + +public class UserBehaviorModelTest { + + @Test + public void testUnmarshal() throws JAXBException { + Unmarshaller unmarshaller = JAXBContext.newInstance( + BehaviorModel.class).createUnmarshaller(); + Object object = unmarshaller.unmarshal(new File("Scripts" + + System.getProperty("file.separator") + "behaviorModel.xml")); + BehaviorModel userBehaviorModel = (BehaviorModel) object; + System.out.println(userBehaviorModel.getUse()); + assertTrue(object instanceof BehaviorModel); + } +} diff --git a/src/test/java/org/bench4q/agent/test/parameterization/TEST_HelloThread.java b/Bench4Q-Agent/src/test/java/org/bench4q/agent/test/parameterization/TEST_HelloThread.java similarity index 100% rename from src/test/java/org/bench4q/agent/test/parameterization/TEST_HelloThread.java rename to Bench4Q-Agent/src/test/java/org/bench4q/agent/test/parameterization/TEST_HelloThread.java diff --git a/src/test/java/org/bench4q/agent/test/parameterization/TEST_UserName.java b/Bench4Q-Agent/src/test/java/org/bench4q/agent/test/parameterization/TEST_UserName.java similarity index 100% rename from src/test/java/org/bench4q/agent/test/parameterization/TEST_UserName.java rename to Bench4Q-Agent/src/test/java/org/bench4q/agent/test/parameterization/TEST_UserName.java diff --git a/src/test/java/org/bench4q/agent/test/parameterization/Test_ParameterizationParser.java b/Bench4Q-Agent/src/test/java/org/bench4q/agent/test/parameterization/Test_ParameterizationParser.java similarity index 100% rename from src/test/java/org/bench4q/agent/test/parameterization/Test_ParameterizationParser.java rename to Bench4Q-Agent/src/test/java/org/bench4q/agent/test/parameterization/Test_ParameterizationParser.java diff --git a/src/test/java/org/bench4q/agent/test/plugin/Test_HttpPlugin.java b/Bench4Q-Agent/src/test/java/org/bench4q/agent/test/plugin/Test_HttpPlugin.java similarity index 100% rename from src/test/java/org/bench4q/agent/test/plugin/Test_HttpPlugin.java rename to Bench4Q-Agent/src/test/java/org/bench4q/agent/test/plugin/Test_HttpPlugin.java diff --git a/src/test/java/org/bench4q/agent/test/scenario/Test_ScenarioContext.java b/Bench4Q-Agent/src/test/java/org/bench4q/agent/test/scenario/Test_ScenarioContext.java similarity index 100% rename from src/test/java/org/bench4q/agent/test/scenario/Test_ScenarioContext.java rename to Bench4Q-Agent/src/test/java/org/bench4q/agent/test/scenario/Test_ScenarioContext.java diff --git a/src/test/java/org/bench4q/agent/test/scenario/utils/Test_ParameterParser.java b/Bench4Q-Agent/src/test/java/org/bench4q/agent/test/scenario/utils/Test_ParameterParser.java similarity index 100% rename from src/test/java/org/bench4q/agent/test/scenario/utils/Test_ParameterParser.java rename to Bench4Q-Agent/src/test/java/org/bench4q/agent/test/scenario/utils/Test_ParameterParser.java diff --git a/src/test/java/org/bench4q/agent/test/scenario/utils/Test_RegularExpression.java b/Bench4Q-Agent/src/test/java/org/bench4q/agent/test/scenario/utils/Test_RegularExpression.java similarity index 100% rename from src/test/java/org/bench4q/agent/test/scenario/utils/Test_RegularExpression.java rename to Bench4Q-Agent/src/test/java/org/bench4q/agent/test/scenario/utils/Test_RegularExpression.java diff --git a/src/test/java/org/bench4q/agent/test/storage/TestDoubleBufferStorage.java b/Bench4Q-Agent/src/test/java/org/bench4q/agent/test/storage/TestDoubleBufferStorage.java similarity index 100% rename from src/test/java/org/bench4q/agent/test/storage/TestDoubleBufferStorage.java rename to Bench4Q-Agent/src/test/java/org/bench4q/agent/test/storage/TestDoubleBufferStorage.java diff --git a/src/test/resources/test-storage-context.xml b/Bench4Q-Agent/src/test/resources/test-storage-context.xml similarity index 98% rename from src/test/resources/test-storage-context.xml rename to Bench4Q-Agent/src/test/resources/test-storage-context.xml index a9e939f0..dcef0042 100644 --- a/src/test/resources/test-storage-context.xml +++ b/Bench4Q-Agent/src/test/resources/test-storage-context.xml @@ -1,11 +1,11 @@ - - - - - + + + + + diff --git a/license.txt b/license.txt deleted file mode 100644 index ed5165d8..00000000 --- a/license.txt +++ /dev/null @@ -1,339 +0,0 @@ -GNU GENERAL PUBLIC LICENSE - Version 2, June 1991 - - Copyright (C) 1989, 1991 Free Software Foundation, Inc., [http://fsf.org/] - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - Preamble - - The licenses for most software are designed to take away your -freedom to share and change it. By contrast, the GNU General Public -License is intended to guarantee your freedom to share and change free -software--to make sure the software is free for all its users. This -General Public License applies to most of the Free Software -Foundation's software and to any other program whose authors commit to -using it. (Some other Free Software Foundation software is covered by -the GNU Lesser General Public License instead.) You can apply it to -your programs, too. - - When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for -this service if you wish), that you receive source code or can get it -if you want it, that you can change the software or use pieces of it -in new free programs; and that you know you can do these things. - - To protect your rights, we need to make restrictions that forbid -anyone to deny you these rights or to ask you to surrender the rights. -These restrictions translate to certain responsibilities for you if you -distribute copies of the software, or if you modify it. - - For example, if you distribute copies of such a program, whether -gratis or for a fee, you must give the recipients all the rights that -you have. You must make sure that they, too, receive or can get the -source code. And you must show them these terms so they know their -rights. - - We protect your rights with two steps: (1) copyright the software, and -(2) offer you this license which gives you legal permission to copy, -distribute and/or modify the software. - - Also, for each author's protection and ours, we want to make certain -that everyone understands that there is no warranty for this free -software. If the software is modified by someone else and passed on, we -want its recipients to know that what they have is not the original, so -that any problems introduced by others will not reflect on the original -authors' reputations. - - Finally, any free program is threatened constantly by software -patents. We wish to avoid the danger that redistributors of a free -program will individually obtain patent licenses, in effect making the -program proprietary. To prevent this, we have made it clear that any -patent must be licensed for everyone's free use or not licensed at all. - - The precise terms and conditions for copying, distribution and -modification follow. - - GNU GENERAL PUBLIC LICENSE - TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION - - 0. This License applies to any program or other work which contains -a notice placed by the copyright holder saying it may be distributed -under the terms of this General Public License. The "Program", below, -refers to any such program or work, and a "work based on the Program" -means either the Program or any derivative work under copyright law: -that is to say, a work containing the Program or a portion of it, -either verbatim or with modifications and/or translated into another -language. (Hereinafter, translation is included without limitation in -the term "modification".) Each licensee is addressed as "you". - -Activities other than copying, distribution and modification are not -covered by this License; they are outside its scope. The act of -running the Program is not restricted, and the output from the Program -is covered only if its contents constitute a work based on the -Program (independent of having been made by running the Program). -Whether that is true depends on what the Program does. - - 1. You may copy and distribute verbatim copies of the Program's -source code as you receive it, in any medium, provided that you -conspicuously and appropriately publish on each copy an appropriate -copyright notice and disclaimer of warranty; keep intact all the -notices that refer to this License and to the absence of any warranty; -and give any other recipients of the Program a copy of this License -along with the Program. - -You may charge a fee for the physical act of transferring a copy, and -you may at your option offer warranty protection in exchange for a fee. - - 2. You may modify your copy or copies of the Program or any portion -of it, thus forming a work based on the Program, and copy and -distribute such modifications or work under the terms of Section 1 -above, provided that you also meet all of these conditions: - - a) You must cause the modified files to carry prominent notices - stating that you changed the files and the date of any change. - - b) You must cause any work that you distribute or publish, that in - whole or in part contains or is derived from the Program or any - part thereof, to be licensed as a whole at no charge to all third - parties under the terms of this License. - - c) If the modified program normally reads commands interactively - when run, you must cause it, when started running for such - interactive use in the most ordinary way, to print or display an - announcement including an appropriate copyright notice and a - notice that there is no warranty (or else, saying that you provide - a warranty) and that users may redistribute the program under - these conditions, and telling the user how to view a copy of this - License. (Exception: if the Program itself is interactive but - does not normally print such an announcement, your work based on - the Program is not required to print an announcement.) - -These requirements apply to the modified work as a whole. If -identifiable sections of that work are not derived from the Program, -and can be reasonably considered independent and separate works in -themselves, then this License, and its terms, do not apply to those -sections when you distribute them as separate works. But when you -distribute the same sections as part of a whole which is a work based -on the Program, the distribution of the whole must be on the terms of -this License, whose permissions for other licensees extend to the -entire whole, and thus to each and every part regardless of who wrote it. - -Thus, it is not the intent of this section to claim rights or contest -your rights to work written entirely by you; rather, the intent is to -exercise the right to control the distribution of derivative or -collective works based on the Program. - -In addition, mere aggregation of another work not based on the Program -with the Program (or with a work based on the Program) on a volume of -a storage or distribution medium does not bring the other work under -the scope of this License. - - 3. You may copy and distribute the Program (or a work based on it, -under Section 2) in object code or executable form under the terms of -Sections 1 and 2 above provided that you also do one of the following: - - a) Accompany it with the complete corresponding machine-readable - source code, which must be distributed under the terms of Sections - 1 and 2 above on a medium customarily used for software interchange; or, - - b) Accompany it with a written offer, valid for at least three - years, to give any third party, for a charge no more than your - cost of physically performing source distribution, a complete - machine-readable copy of the corresponding source code, to be - distributed under the terms of Sections 1 and 2 above on a medium - customarily used for software interchange; or, - - c) Accompany it with the information you received as to the offer - to distribute corresponding source code. (This alternative is - allowed only for noncommercial distribution and only if you - received the program in object code or executable form with such - an offer, in accord with Subsection b above.) - -The source code for a work means the preferred form of the work for -making modifications to it. For an executable work, complete source -code means all the source code for all modules it contains, plus any -associated interface definition files, plus the scripts used to -control compilation and installation of the executable. However, as a -special exception, the source code distributed need not include -anything that is normally distributed (in either source or binary -form) with the major components (compiler, kernel, and so on) of the -operating system on which the executable runs, unless that component -itself accompanies the executable. - -If distribution of executable or object code is made by offering -access to copy from a designated place, then offering equivalent -access to copy the source code from the same place counts as -distribution of the source code, even though third parties are not -compelled to copy the source along with the object code. - - 4. You may not copy, modify, sublicense, or distribute the Program -except as expressly provided under this License. Any attempt -otherwise to copy, modify, sublicense or distribute the Program is -void, and will automatically terminate your rights under this License. -However, parties who have received copies, or rights, from you under -this License will not have their licenses terminated so long as such -parties remain in full compliance. - - 5. You are not required to accept this License, since you have not -signed it. However, nothing else grants you permission to modify or -distribute the Program or its derivative works. These actions are -prohibited by law if you do not accept this License. Therefore, by -modifying or distributing the Program (or any work based on the -Program), you indicate your acceptance of this License to do so, and -all its terms and conditions for copying, distributing or modifying -the Program or works based on it. - - 6. Each time you redistribute the Program (or any work based on the -Program), the recipient automatically receives a license from the -original licensor to copy, distribute or modify the Program subject to -these terms and conditions. You may not impose any further -restrictions on the recipients' exercise of the rights granted herein. -You are not responsible for enforcing compliance by third parties to -this License. - - 7. If, as a consequence of a court judgment or allegation of patent -infringement or for any other reason (not limited to patent issues), -conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot -distribute so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you -may not distribute the Program at all. For example, if a patent -license would not permit royalty-free redistribution of the Program by -all those who receive copies directly or indirectly through you, then -the only way you could satisfy both it and this License would be to -refrain entirely from distribution of the Program. - -If any portion of this section is held invalid or unenforceable under -any particular circumstance, the balance of the section is intended to -apply and the section as a whole is intended to apply in other -circumstances. - -It is not the purpose of this section to induce you to infringe any -patents or other property right claims or to contest validity of any -such claims; this section has the sole purpose of protecting the -integrity of the free software distribution system, which is -implemented by public license practices. Many people have made -generous contributions to the wide range of software distributed -through that system in reliance on consistent application of that -system; it is up to the author/donor to decide if he or she is willing -to distribute software through any other system and a licensee cannot -impose that choice. - -This section is intended to make thoroughly clear what is believed to -be a consequence of the rest of this License. - - 8. If the distribution and/or use of the Program is restricted in -certain countries either by patents or by copyrighted interfaces, the -original copyright holder who places the Program under this License -may add an explicit geographical distribution limitation excluding -those countries, so that distribution is permitted only in or among -countries not thus excluded. In such case, this License incorporates -the limitation as if written in the body of this License. - - 9. The Free Software Foundation may publish revised and/or new versions -of the General Public License from time to time. Such new versions will -be similar in spirit to the present version, but may differ in detail to -address new problems or concerns. - -Each version is given a distinguishing version number. If the Program -specifies a version number of this License which applies to it and "any -later version", you have the option of following the terms and conditions -either of that version or of any later version published by the Free -Software Foundation. If the Program does not specify a version number of -this License, you may choose any version ever published by the Free Software -Foundation. - - 10. If you wish to incorporate parts of the Program into other free -programs whose distribution conditions are different, write to the author -to ask for permission. For software which is copyrighted by the Free -Software Foundation, write to the Free Software Foundation; we sometimes -make exceptions for this. Our decision will be guided by the two goals -of preserving the free status of all derivatives of our free software and -of promoting the sharing and reuse of software generally. - - NO WARRANTY - - 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY -FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN -OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES -PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED -OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS -TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE -PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, -REPAIR OR CORRECTION. - - 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR -REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, -INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING -OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED -TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY -YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER -PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE -POSSIBILITY OF SUCH DAMAGES. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Programs - - If you develop a new program, and you want it to be of the greatest -possible use to the public, the best way to achieve this is to make it -free software which everyone can redistribute and change under these terms. - - To do so, attach the following notices to the program. It is safest -to attach them to the start of each source file to most effectively -convey the exclusion of warranty; and each file should have at least -the "copyright" line and a pointer to where the full notice is found. - - {description} - Copyright (C) {year} {fullname} - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License along - with this program; if not, write to the Free Software Foundation, Inc., - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. - -Also add information on how to contact you by electronic and paper mail. - -If the program is interactive, make it output a short notice like this -when it starts in an interactive mode: - - Gnomovision version 69, Copyright (C) year name of author - Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. - This is free software, and you are welcome to redistribute it - under certain conditions; type `show c' for details. - -The hypothetical commands `show w' and `show c' should show the appropriate -parts of the General Public License. Of course, the commands you use may -be called something other than `show w' and `show c'; they could even be -mouse-clicks or menu items--whatever suits your program. - -You should also get your employer (if you work as a programmer) or your -school, if any, to sign a "copyright disclaimer" for the program, if -necessary. Here is a sample; alter the names: - - Yoyodyne, Inc., hereby disclaims all copyright interest in the program - `Gnomovision' (which makes passes at compilers) written by James Hacker. - - {signature of Ty Coon}, 1 April 1989 - Ty Coon, President of Vice - -This General Public License does not permit incorporating your program into -proprietary programs. If your program is a subroutine library, you may -consider it more useful to permit linking proprietary applications with the -library. If this is what you want to do, use the GNU Lesser General -Public License instead of this License. \ No newline at end of file