From cc2a06a677ee63e4445da36a710467f7a4e8fc7f Mon Sep 17 00:00:00 2001 From: Zhen Tang Date: Sun, 23 Jun 2013 08:07:45 -0700 Subject: [PATCH 001/684] 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..5371b52e --- /dev/null +++ b/README.md @@ -0,0 +1,4 @@ +Bench4Q-Master +============== + +Master Node of Bench4Q From f2e404a5afb051097c35c5b405ccd6a09a85eea7 Mon Sep 17 00:00:00 2001 From: Zhen Tang Date: Sun, 23 Jun 2013 23:34:13 +0800 Subject: [PATCH 002/684] Use jetty as http server. A simple service added. --- pom.xml | 44 ++++++++++++ src/main/java/org/bench4q/master/Main.java | 9 +++ .../java/org/bench4q/master/MasterServer.java | 67 +++++++++++++++++++ .../bench4q/master/api/HomeController.java | 16 +++++ src/main/resources/application-context.xml | 10 +++ 5 files changed, 146 insertions(+) create mode 100644 pom.xml create mode 100644 src/main/java/org/bench4q/master/Main.java create mode 100644 src/main/java/org/bench4q/master/MasterServer.java create mode 100644 src/main/java/org/bench4q/master/api/HomeController.java create mode 100644 src/main/resources/application-context.xml diff --git a/pom.xml b/pom.xml new file mode 100644 index 00000000..a2631630 --- /dev/null +++ b/pom.xml @@ -0,0 +1,44 @@ + + 4.0.0 + org.bench4q + bench4q-master + jar + 0.0.1-SNAPSHOT + Bench4Q Master + Bench4Q Master + + 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-master + + \ No newline at end of file diff --git a/src/main/java/org/bench4q/master/Main.java b/src/main/java/org/bench4q/master/Main.java new file mode 100644 index 00000000..45aede99 --- /dev/null +++ b/src/main/java/org/bench4q/master/Main.java @@ -0,0 +1,9 @@ +package org.bench4q.master; + + +public class Main { + public static void main(String[] args) { + MasterServer masterServer = new MasterServer(8080); + masterServer.start(); + } +} diff --git a/src/main/java/org/bench4q/master/MasterServer.java b/src/main/java/org/bench4q/master/MasterServer.java new file mode 100644 index 00000000..3040913a --- /dev/null +++ b/src/main/java/org/bench4q/master/MasterServer.java @@ -0,0 +1,67 @@ +package org.bench4q.master; + +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 MasterServer { + private Server server; + private int port; + + private Server getServer() { + return server; + } + + private void setServer(Server server) { + this.server = server; + } + + private int getPort() { + return port; + } + + private void setPort(int port) { + this.port = port; + } + + public MasterServer(int port) { + this.setPort(port); + } + + public boolean start() { + try { + this.setServer(new Server()); + 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/master/api/HomeController.java b/src/main/java/org/bench4q/master/api/HomeController.java new file mode 100644 index 00000000..bbf764f7 --- /dev/null +++ b/src/main/java/org/bench4q/master/api/HomeController.java @@ -0,0 +1,16 @@ +package org.bench4q.master.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 b63ada6816f607fb295dc75e30b478f1afbf5dfc Mon Sep 17 00:00:00 2001 From: Zhen Tang Date: Sun, 23 Jun 2013 08:37:12 -0700 Subject: [PATCH 003/684] 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 004/684] 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 8e29051975ba351c778c143975e1d2d140d75a71 Mon Sep 17 00:00:00 2001 From: Zhen Tang Date: Mon, 24 Jun 2013 00:11:56 +0800 Subject: [PATCH 005/684] User service added. --- pom.xml | 101 ++++++++++-------- .../java/org/bench4q/master/entity/User.java | 46 ++++++++ .../org/bench4q/master/helper/HashHelper.java | 33 ++++++ .../bench4q/master/helper/SessionHelper.java | 36 +++++++ .../bench4q/master/helper/StringHelper.java | 38 +++++++ .../bench4q/master/service/UserService.java | 101 ++++++++++++++++++ src/main/resources/hibernate.cfg.xml | 20 ++++ 7 files changed, 332 insertions(+), 43 deletions(-) create mode 100644 src/main/java/org/bench4q/master/entity/User.java create mode 100644 src/main/java/org/bench4q/master/helper/HashHelper.java create mode 100644 src/main/java/org/bench4q/master/helper/SessionHelper.java create mode 100644 src/main/java/org/bench4q/master/helper/StringHelper.java create mode 100644 src/main/java/org/bench4q/master/service/UserService.java create mode 100644 src/main/resources/hibernate.cfg.xml diff --git a/pom.xml b/pom.xml index a2631630..b6756476 100644 --- a/pom.xml +++ b/pom.xml @@ -1,44 +1,59 @@ - - 4.0.0 - org.bench4q - bench4q-master - jar - 0.0.1-SNAPSHOT - Bench4Q Master - Bench4Q Master - - 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-master - + + 4.0.0 + org.bench4q + bench4q-master + jar + 0.0.1-SNAPSHOT + Bench4Q Master + Bench4Q Master + + 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.hibernate + hibernate-core + 4.3.0.Beta3 + + + org.hibernate.javax.persistence + hibernate-jpa-2.1-api + 1.0.0.Draft-16 + + + mysql + mysql-connector-java + 5.1.25 + + + + bench4q-master + \ No newline at end of file diff --git a/src/main/java/org/bench4q/master/entity/User.java b/src/main/java/org/bench4q/master/entity/User.java new file mode 100644 index 00000000..e33f404a --- /dev/null +++ b/src/main/java/org/bench4q/master/entity/User.java @@ -0,0 +1,46 @@ +package org.bench4q.master.entity; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Table; + +@Entity +@Table(name = "user") +public class User { + private int id; + private String userName; + private String password; + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id", nullable = false) + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + @Column(name = "userName", nullable = false) + public String getUserName() { + return userName; + } + + public void setUserName(String userName) { + this.userName = userName; + } + + @Column(name = "password", nullable = false) + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + +} diff --git a/src/main/java/org/bench4q/master/helper/HashHelper.java b/src/main/java/org/bench4q/master/helper/HashHelper.java new file mode 100644 index 00000000..0d267e2e --- /dev/null +++ b/src/main/java/org/bench4q/master/helper/HashHelper.java @@ -0,0 +1,33 @@ +package org.bench4q.master.helper; + +import java.security.MessageDigest; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +@Component +public class HashHelper { + private StringHelper stringHelper; + + private StringHelper getStringHelper() { + return stringHelper; + } + + @Autowired + private void setStringHelper(StringHelper stringHelper) { + this.stringHelper = stringHelper; + } + + public String sha1Hash(String source) { + try { + String ret = new String(source); + MessageDigest md = MessageDigest.getInstance("SHA-1"); + ret = this.getStringHelper().convertToHexString( + md.digest(ret.getBytes())); + return ret; + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } +} diff --git a/src/main/java/org/bench4q/master/helper/SessionHelper.java b/src/main/java/org/bench4q/master/helper/SessionHelper.java new file mode 100644 index 00000000..2bdc7826 --- /dev/null +++ b/src/main/java/org/bench4q/master/helper/SessionHelper.java @@ -0,0 +1,36 @@ +package org.bench4q.master.helper; + +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.boot.registry.StandardServiceRegistryBuilder; +import org.hibernate.cfg.Configuration; +import org.hibernate.service.ServiceRegistry; +import org.springframework.stereotype.Component; + +@Component +public final class SessionHelper { + private SessionFactory sessionFactory; + + public SessionFactory getSessionFactory() { + return sessionFactory; + } + + public void setSessionFactory(SessionFactory sessionFactory) { + this.sessionFactory = sessionFactory; + } + + public SessionHelper() { + try { + Configuration cfg = new Configuration().configure(); + ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder() + .applySettings(cfg.getProperties()).build(); + this.setSessionFactory(cfg.buildSessionFactory(serviceRegistry)); + } catch (Exception e) { + e.printStackTrace(); + } + } + + public Session openSession() { + return this.getSessionFactory().openSession(); + } +} diff --git a/src/main/java/org/bench4q/master/helper/StringHelper.java b/src/main/java/org/bench4q/master/helper/StringHelper.java new file mode 100644 index 00000000..0b894c5d --- /dev/null +++ b/src/main/java/org/bench4q/master/helper/StringHelper.java @@ -0,0 +1,38 @@ +package org.bench4q.master.helper; + +import org.springframework.stereotype.Component; + +@Component +public final class StringHelper { + + public String convertToHexString(byte[] b) { + String ret = ""; + for (int i = 0; i < b.length; i++) { + String hex = Integer.toHexString(b[i] & 0xFF); + if (hex.length() == 1) { + hex = '0' + hex; + } + ret += hex; + } + return ret; + } + + private byte uniteBytes(byte src0, byte src1) { + byte _b0 = Byte.decode("0x" + new String(new byte[] { src0 })) + .byteValue(); + _b0 = (byte) (_b0 << 4); + byte _b1 = Byte.decode("0x" + new String(new byte[] { src1 })) + .byteValue(); + byte ret = (byte) (_b0 ^ _b1); + return ret; + } + + public byte[] convertToBytes(String src) { + byte[] ret = new byte[src.getBytes().length / 2]; + byte[] tmp = src.getBytes(); + for (int i = 0; i < ret.length; i++) { + ret[i] = this.uniteBytes(tmp[i * 2], tmp[i * 2 + 1]); + } + return ret; + } +} diff --git a/src/main/java/org/bench4q/master/service/UserService.java b/src/main/java/org/bench4q/master/service/UserService.java new file mode 100644 index 00000000..7f0b423e --- /dev/null +++ b/src/main/java/org/bench4q/master/service/UserService.java @@ -0,0 +1,101 @@ +package org.bench4q.master.service; + +import org.bench4q.master.entity.User; +import org.bench4q.master.helper.HashHelper; +import org.bench4q.master.helper.SessionHelper; +import org.hibernate.Session; +import org.hibernate.Transaction; +import org.hibernate.criterion.Restrictions; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +@Component +public class UserService { + private SessionHelper sessionHelper; + private HashHelper hashHelper; + + private SessionHelper getSessionHelper() { + return sessionHelper; + } + + @Autowired + private void setSessionHelper(SessionHelper sessionHelper) { + this.sessionHelper = sessionHelper; + } + + private HashHelper getHashHelper() { + return hashHelper; + } + + @Autowired + private void setHashHelper(HashHelper hashHelper) { + this.hashHelper = hashHelper; + } + + public boolean register(String userName, String password) { + Session session = this.getSessionHelper().openSession(); + Transaction transaction = session.beginTransaction(); + try { + User user = (User) session.createCriteria(User.class) + .add(Restrictions.eq("userName", userName)).uniqueResult(); + if (user != null) { + return false; + } + user = new User(); + user.setUserName(userName); + user.setPassword(this.hashPassword(password)); + session.merge(user); + transaction.commit(); + return true; + } catch (Exception e) { + e.printStackTrace(); + transaction.rollback(); + return false; + } finally { + if (session != null) { + session.close(); + } + } + } + + public boolean validateUser(String userName, String password) { + Session session = this.getSessionHelper().openSession(); + try { + User user = (User) session.createCriteria(User.class) + .add(Restrictions.eq("userName", userName)).uniqueResult(); + if (user == null) { + return false; + } + if (user.getPassword().equals(this.hashPassword(password))) { + return true; + } + return false; + } catch (Exception e) { + e.printStackTrace(); + return false; + } finally { + if (session != null) { + session.close(); + } + } + } + + public String hashPassword(String password) { + return this.getHashHelper().sha1Hash(password); + } + + public User getUserByName(String userName) { + Session session = this.getSessionHelper().openSession(); + try { + return (User) session.createCriteria(User.class) + .add(Restrictions.eq("userName", userName)).uniqueResult(); + } catch (Exception e) { + e.printStackTrace(); + return null; + } finally { + if (session != null) { + session.close(); + } + } + } +} diff --git a/src/main/resources/hibernate.cfg.xml b/src/main/resources/hibernate.cfg.xml new file mode 100644 index 00000000..5911c827 --- /dev/null +++ b/src/main/resources/hibernate.cfg.xml @@ -0,0 +1,20 @@ + + + + + com.mysql.jdbc.Driver + jdbc:mysql://localhost:3306/bench4q_master + + root + 123456 + 20 + false + false + true + utf-8 + org.hibernate.dialect.MySQLDialect + update + + + + \ No newline at end of file From 4ffdbca8353b0889ab045504996e689a8f6264e1 Mon Sep 17 00:00:00 2001 From: Zhen Tang Date: Mon, 24 Jun 2013 12:19:17 +0800 Subject: [PATCH 006/684] Authentication manager added. --- .../bench4q/master/api/BaseController.java | 40 +++++ .../bench4q/master/api/HomeController.java | 38 +++-- .../bench4q/master/api/UserController.java | 75 ++++++++++ .../api/model/AuthorizeResponseModel.java | 40 +++++ .../api/model/RegisterResponseModel.java | 20 +++ .../org/bench4q/master/auth/AccessToken.java | 55 +++++++ .../master/auth/AuthenticationManager.java | 138 ++++++++++++++++++ .../bench4q/master/auth/CryptoManager.java | 122 ++++++++++++++++ .../org/bench4q/master/helper/HttpHelper.java | 40 +++++ src/main/resources/key.pfx | Bin 0 -> 2542 bytes .../master/test/AuthenticationTest.java | 21 +++ 11 files changed, 574 insertions(+), 15 deletions(-) create mode 100644 src/main/java/org/bench4q/master/api/BaseController.java create mode 100644 src/main/java/org/bench4q/master/api/UserController.java create mode 100644 src/main/java/org/bench4q/master/api/model/AuthorizeResponseModel.java create mode 100644 src/main/java/org/bench4q/master/api/model/RegisterResponseModel.java create mode 100644 src/main/java/org/bench4q/master/auth/AccessToken.java create mode 100644 src/main/java/org/bench4q/master/auth/AuthenticationManager.java create mode 100644 src/main/java/org/bench4q/master/auth/CryptoManager.java create mode 100644 src/main/java/org/bench4q/master/helper/HttpHelper.java create mode 100644 src/main/resources/key.pfx create mode 100644 src/test/java/org/bench4q/master/test/AuthenticationTest.java diff --git a/src/main/java/org/bench4q/master/api/BaseController.java b/src/main/java/org/bench4q/master/api/BaseController.java new file mode 100644 index 00000000..abb24a55 --- /dev/null +++ b/src/main/java/org/bench4q/master/api/BaseController.java @@ -0,0 +1,40 @@ +package org.bench4q.master.api; + +import javax.servlet.http.HttpServletRequest; + +import org.bench4q.master.auth.AuthenticationManager; +import org.bench4q.master.entity.User; +import org.springframework.beans.factory.annotation.Autowired; + +public abstract class BaseController { + private HttpServletRequest request; + private AuthenticationManager authenticationManager; + + protected HttpServletRequest getRequest() { + return request; + } + + @Autowired + protected void setRequest(HttpServletRequest request) { + this.request = request; + } + + protected AuthenticationManager getAuthenticationManager() { + return authenticationManager; + } + + @Autowired + protected void setAuthenticationManager( + AuthenticationManager authenticationManager) { + this.authenticationManager = authenticationManager; + } + + protected User getPrincipal() { + return this.getAuthenticationManager().getPrincipal(this.getRequest()); + } + + protected boolean checkScope(String scope) { + return this.getAuthenticationManager().checkScope(this.getRequest(), + scope); + } +} diff --git a/src/main/java/org/bench4q/master/api/HomeController.java b/src/main/java/org/bench4q/master/api/HomeController.java index bbf764f7..5fdb7fe1 100644 --- a/src/main/java/org/bench4q/master/api/HomeController.java +++ b/src/main/java/org/bench4q/master/api/HomeController.java @@ -1,16 +1,24 @@ -package org.bench4q.master.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.master.api; + +import org.bench4q.master.entity.User; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.ResponseBody; + +@Controller +@RequestMapping("/") +public class HomeController extends BaseController { + @RequestMapping(value = { "/" }, method = RequestMethod.GET) + @ResponseBody + public String index() { + User principal = this.getPrincipal(); + String userName; + if (principal == null) { + userName = "Anonymous User"; + } else { + userName = principal.getUserName(); + } + return "Hello [" + userName + "]"; + } } \ No newline at end of file diff --git a/src/main/java/org/bench4q/master/api/UserController.java b/src/main/java/org/bench4q/master/api/UserController.java new file mode 100644 index 00000000..cc1b981c --- /dev/null +++ b/src/main/java/org/bench4q/master/api/UserController.java @@ -0,0 +1,75 @@ +package org.bench4q.master.api; + +import org.bench4q.master.api.model.AuthorizeResponseModel; +import org.bench4q.master.api.model.RegisterResponseModel; +import org.bench4q.master.auth.AccessToken; +import org.bench4q.master.auth.AuthenticationManager; +import org.bench4q.master.entity.User; +import org.bench4q.master.service.UserService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.ResponseBody; + +@Controller +@RequestMapping("/user") +public class UserController { + private UserService userService; + private AuthenticationManager authenticationManager; + + private UserService getUserService() { + return userService; + } + + @Autowired + private void setUserService(UserService userService) { + this.userService = userService; + } + + public AuthenticationManager getAuthenticationManager() { + return authenticationManager; + } + + @Autowired + public void setAuthenticationManager( + AuthenticationManager authenticationManager) { + this.authenticationManager = authenticationManager; + } + + @RequestMapping(value = "/register", method = RequestMethod.GET) + @ResponseBody + public RegisterResponseModel register(@RequestParam String userName, + @RequestParam String password) { + boolean success = this.getUserService().register(userName, password); + RegisterResponseModel registerUserResponseModel = new RegisterResponseModel(); + registerUserResponseModel.setSuccess(success); + return registerUserResponseModel; + } + + @RequestMapping(value = "/authorize", method = RequestMethod.GET) + @ResponseBody + public AuthorizeResponseModel authorize(@RequestParam String userName, + @RequestParam String password) { + boolean authorized = this.getUserService().validateUser(userName, + password); + if (!authorized) { + AuthorizeResponseModel responseModel = new AuthorizeResponseModel(); + responseModel.setAccessToken(null); + responseModel.setExpiresIn(-1); + responseModel.setSuccess(false); + return responseModel; + } + User user = this.getUserService().getUserByName(userName); + AccessToken accessToken = this.getAuthenticationManager() + .generateAccessToken(user); + String credential = this.getAuthenticationManager().generateCredential( + user); + AuthorizeResponseModel responseModel = new AuthorizeResponseModel(); + responseModel.setAccessToken(credential); + responseModel.setExpiresIn(accessToken.getExpiresIn()); + responseModel.setSuccess(true); + return responseModel; + } +} diff --git a/src/main/java/org/bench4q/master/api/model/AuthorizeResponseModel.java b/src/main/java/org/bench4q/master/api/model/AuthorizeResponseModel.java new file mode 100644 index 00000000..a030fd0a --- /dev/null +++ b/src/main/java/org/bench4q/master/api/model/AuthorizeResponseModel.java @@ -0,0 +1,40 @@ +package org.bench4q.master.api.model; + +import javax.xml.bind.annotation.XmlRootElement; + +import com.sun.xml.internal.txw2.annotation.XmlElement; + +@XmlRootElement(name = "authorizeResponse") +public class AuthorizeResponseModel { + private boolean success; + private String accessToken; + private int expiresIn; + + @XmlElement + public boolean isSuccess() { + return success; + } + + public void setSuccess(boolean success) { + this.success = success; + } + + @XmlElement + public String getAccessToken() { + return accessToken; + } + + public void setAccessToken(String accessToken) { + this.accessToken = accessToken; + } + + @XmlElement + public int getExpiresIn() { + return expiresIn; + } + + public void setExpiresIn(int expiresIn) { + this.expiresIn = expiresIn; + } + +} diff --git a/src/main/java/org/bench4q/master/api/model/RegisterResponseModel.java b/src/main/java/org/bench4q/master/api/model/RegisterResponseModel.java new file mode 100644 index 00000000..538884f5 --- /dev/null +++ b/src/main/java/org/bench4q/master/api/model/RegisterResponseModel.java @@ -0,0 +1,20 @@ +package org.bench4q.master.api.model; + +import javax.xml.bind.annotation.XmlRootElement; + +import com.sun.xml.internal.txw2.annotation.XmlElement; + +@XmlRootElement(name = "registerResponse") +public class RegisterResponseModel { + 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/master/auth/AccessToken.java b/src/main/java/org/bench4q/master/auth/AccessToken.java new file mode 100644 index 00000000..4668d574 --- /dev/null +++ b/src/main/java/org/bench4q/master/auth/AccessToken.java @@ -0,0 +1,55 @@ +package org.bench4q.master.auth; + +import java.io.Serializable; +import java.util.Date; +import java.util.List; + +public class AccessToken implements Serializable { + private static final long serialVersionUID = 4134631390384650898L; + private String userName; + private String password; + private Date generateTime; + private int expiresIn; + private List scope; + + public String getUserName() { + return userName; + } + + public void setUserName(String userName) { + this.userName = userName; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + public Date getGenerateTime() { + return generateTime; + } + + public void setGenerateTime(Date generateTime) { + this.generateTime = generateTime; + } + + public int getExpiresIn() { + return expiresIn; + } + + public void setExpiresIn(int expiresIn) { + this.expiresIn = expiresIn; + } + + public List getScope() { + return scope; + } + + public void setScope(List scope) { + this.scope = scope; + } + +} diff --git a/src/main/java/org/bench4q/master/auth/AuthenticationManager.java b/src/main/java/org/bench4q/master/auth/AuthenticationManager.java new file mode 100644 index 00000000..99be4f06 --- /dev/null +++ b/src/main/java/org/bench4q/master/auth/AuthenticationManager.java @@ -0,0 +1,138 @@ +package org.bench4q.master.auth; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.Date; + +import javax.servlet.http.HttpServletRequest; + +import org.bench4q.master.entity.User; +import org.bench4q.master.helper.StringHelper; +import org.bench4q.master.service.UserService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +@Component +public class AuthenticationManager { + private final int defaultExpiresTime = 3600; + private CryptoManager cryptoManager; + private UserService userService; + private StringHelper stringHelper; + + private CryptoManager getCryptoManager() { + return cryptoManager; + } + + @Autowired + private void setCryptoManager(CryptoManager cryptoManager) { + this.cryptoManager = cryptoManager; + } + + private UserService getUserService() { + return userService; + } + + @Autowired + private void setUserService(UserService userService) { + this.userService = userService; + } + + private StringHelper getStringHelper() { + return stringHelper; + } + + @Autowired + private void setStringHelper(StringHelper stringHelper) { + this.stringHelper = stringHelper; + } + + public User getPrincipal(HttpServletRequest request) { + AccessToken accessToken = this.getAccessToken(request); + if (accessToken == null) { + return null; + } + return this.extractUser(accessToken); + } + + public boolean checkScope(HttpServletRequest request, String scope) { + AccessToken accessToken = this.getAccessToken(request); + if (accessToken == null) { + return false; + } + return accessToken.getScope().contains(scope); + } + + public String generateCredential(User user) { + AccessToken accessToken = this.generateAccessToken(user); + return this.generateCredentialFromAccessToken(accessToken); + } + + private AccessToken getAccessToken(HttpServletRequest request) { + if (request.getHeader("Authorization") == null) { + return null; + } + if (!request.getHeader("Authorization").startsWith("Bearer ")) { + return null; + } + String hex = request.getHeader("Authorization").substring( + "Bearer ".length()); + byte[] bytes = this.getStringHelper().convertToBytes(hex); + return this.extractAccessToken(bytes); + } + + private User extractUser(AccessToken accessToken) { + if (accessToken == null) { + return null; + } + Calendar calendar = Calendar.getInstance(); + calendar.setTime(accessToken.getGenerateTime()); + calendar.add(Calendar.SECOND, accessToken.getExpiresIn()); + Date expireTime = calendar.getTime(); + if (expireTime.before(new Date(System.currentTimeMillis()))) { + return null; + } + return this.getUserService().getUserByName(accessToken.getUserName()); + } + + public AccessToken generateAccessToken(User user) { + AccessToken accessToken = new AccessToken(); + accessToken.setExpiresIn(this.defaultExpiresTime); + accessToken.setGenerateTime(new Date(System.currentTimeMillis())); + accessToken.setPassword(user.getPassword()); + accessToken.setUserName(user.getUserName()); + // TODO: scope + accessToken.setScope(new ArrayList()); + accessToken.getScope().add("all"); + return accessToken; + } + + private AccessToken extractAccessToken(byte[] bytes) { + try { + byte[] decrypted = this.getCryptoManager().decrypt(bytes); + ObjectInputStream inputStream = new ObjectInputStream( + new ByteArrayInputStream(decrypted)); + return (AccessToken) inputStream.readObject(); + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } + + private String generateCredentialFromAccessToken(AccessToken accessToken) { + try { + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + ObjectOutputStream stream = new ObjectOutputStream(outputStream); + stream.writeObject(accessToken); + byte[] data = outputStream.toByteArray(); + byte[] encryptedData = this.getCryptoManager().encrypt(data); + return this.getStringHelper().convertToHexString(encryptedData); + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } +} diff --git a/src/main/java/org/bench4q/master/auth/CryptoManager.java b/src/main/java/org/bench4q/master/auth/CryptoManager.java new file mode 100644 index 00000000..9bf06a23 --- /dev/null +++ b/src/main/java/org/bench4q/master/auth/CryptoManager.java @@ -0,0 +1,122 @@ +package org.bench4q.master.auth; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.security.KeyStore.PrivateKeyEntry; +import java.security.KeyStore; +import java.security.PrivateKey; +import java.security.PublicKey; +import java.util.Enumeration; + +import javax.crypto.Cipher; + +import org.springframework.stereotype.Component; + +@Component +public class CryptoManager { + private static final int MAX_ENCRYPT_BLOCK = 245; + private static final int MAX_DECRYPT_BLOCK = 256; + + private PublicKey publicKey; + private PrivateKey privateKey; + + private PublicKey getPublicKey() { + return publicKey; + } + + private void setPublicKey(PublicKey publicKey) { + this.publicKey = publicKey; + } + + private PrivateKey getPrivateKey() { + return privateKey; + } + + private void setPrivateKey(PrivateKey privateKey) { + this.privateKey = privateKey; + } + + public CryptoManager() { + try { + String pfxFileName = Thread.currentThread().getContextClassLoader() + .getResource("key.pfx").getFile(); + String pfxPassword = "123456"; + File pfxFile = new File(pfxFileName); + FileInputStream pfxFileInputStream = new FileInputStream(pfxFile); + KeyStore keyStore = KeyStore.getInstance("PKCS12"); + keyStore.load(pfxFileInputStream, pfxPassword.toCharArray()); + pfxFileInputStream.close(); + Enumeration aliases = keyStore.aliases(); + if (aliases.hasMoreElements()) { + String alias = aliases.nextElement(); + PrivateKeyEntry privateKeyEntry = (PrivateKeyEntry) keyStore + .getEntry(alias, new KeyStore.PasswordProtection( + pfxPassword.toCharArray())); + this.setPrivateKey(privateKeyEntry.getPrivateKey()); + this.setPublicKey(privateKeyEntry.getCertificate() + .getPublicKey()); + } + } catch (Exception e) { + e.printStackTrace(); + } + } + + public byte[] encrypt(byte[] data) { + try { + Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); + cipher.init(Cipher.ENCRYPT_MODE, this.getPublicKey()); + int inputLen = data.length; + ByteArrayOutputStream out = new ByteArrayOutputStream(); + int offSet = 0; + byte[] cache; + int i = 0; + while (inputLen - offSet > 0) { + if (inputLen - offSet > MAX_ENCRYPT_BLOCK) { + cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK); + } else { + cache = cipher.doFinal(data, offSet, inputLen - offSet); + } + out.write(cache, 0, cache.length); + i++; + offSet = i * MAX_ENCRYPT_BLOCK; + } + byte[] encryptedData = out.toByteArray(); + out.close(); + return encryptedData; + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } + + public byte[] decrypt(byte[] encryptedData) { + try { + Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding"); + cipher.init(Cipher.DECRYPT_MODE, this.getPrivateKey()); + int inputLen = encryptedData.length; + ByteArrayOutputStream out = new ByteArrayOutputStream(); + int offSet = 0; + byte[] cache; + int i = 0; + while (inputLen - offSet > 0) { + if (inputLen - offSet > MAX_DECRYPT_BLOCK) { + cache = cipher.doFinal(encryptedData, offSet, + MAX_DECRYPT_BLOCK); + } else { + cache = cipher.doFinal(encryptedData, offSet, inputLen + - offSet); + } + out.write(cache, 0, cache.length); + i++; + offSet = i * MAX_DECRYPT_BLOCK; + } + byte[] decryptedData = out.toByteArray(); + out.close(); + return decryptedData; + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } +} diff --git a/src/main/java/org/bench4q/master/helper/HttpHelper.java b/src/main/java/org/bench4q/master/helper/HttpHelper.java new file mode 100644 index 00000000..2793d1bb --- /dev/null +++ b/src/main/java/org/bench4q/master/helper/HttpHelper.java @@ -0,0 +1,40 @@ +package org.bench4q.master.helper; + +import java.io.BufferedReader; +import java.io.InputStreamReader; +import java.net.HttpURLConnection; +import java.net.URL; + +import org.springframework.stereotype.Component; + +@Component +public class HttpHelper { + + public String get(String url, String accessToken) { + try { + URL target = new URL(url); + HttpURLConnection httpURLConnection = (HttpURLConnection) target + .openConnection(); + httpURLConnection.setDoOutput(false); + httpURLConnection.setDoInput(true); + httpURLConnection.setUseCaches(false); + httpURLConnection.setRequestMethod("GET"); + if (accessToken != null) { + httpURLConnection.setRequestProperty("Authorization", "Bearer " + + accessToken); + } + 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 stringBuffer.toString(); + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } +} diff --git a/src/main/resources/key.pfx b/src/main/resources/key.pfx new file mode 100644 index 0000000000000000000000000000000000000000..af0ccff3a88b1b23cfef8441aca4a501966dfdfe GIT binary patch literal 2542 zcmY*ac|4SB8-B-(VaA#zl*m%ZHZ%s2GAY~GvhQR!vacuWWGO<8jIs+c4P(ucts|5e zyRt=OS5et>rtj_izVDph_j`W#^W67!UH5Z6|Ge*wA|TcoAW#$m@f40Ym#CAt#|B}7 z6cP|wFajb2gws(3IP?Eej0Z3R;|_|z_zjFNaF+jeu_7T1g#;KKMSvZm1mVd4!QkcW zFlHgUjH+n~hbaaIrXd&sHt|S4VAhPwUd_S8kw?zxBU?1ER6=}G=df|koC@s89_=zd%q`%LS4=&Tk5^6w2*WMb^c=N$qAAKeI zC9*H!#Y11bv`ry*iq}BaEVRHgbbJ1PafOtWglA}8m+R9?s5*~-R+ag## zswBdH6#tD8Co4D*WkZ^0NkOK1(szansEUZB&Ej!9J?Opa!>U^JP?@O68!07R)pfNz zwlmj}ce_)pYNsacVzP%G$KkY#Lo3X?XYqc)Ew3Z~tnlA^5YFdj64-2{sSc4@KK68b z*P|UNKh68l>Wx#L+G0SXO%dA#j(!{JcxH5EneZs@)s06Z?i?CU%97u(xD;UnF^EQz zvAjRl;gKWFv2rQIt|tFgMok#%h0nx>qCU&ttA#Q0Pg2kY}Sx3(498D9Qcxsyw819W7wM zIcbT@99=bVH`g##L^k&id|7UuLexCe%Uv}-nz#7a;5HK5^v(D7mmdsG*4pD|4z9=` z5AoK6UHg&W)dM=lW|huI&hU9&;R=v$@rmYm=1{*3$*tQNYQz#I$(I#2E$!oBJ86?)DlAHRy-EE)iYZm(XRY z+%sc*QLIEZh@HL_HCyRrqH@y&Nh;yVV@XK*G`|tRTD{BX%nGb@99R=qkM2*CNK$qe zpJ0i_Y6_9e19Gs1nKEtSHMweXLtTf+B9+ehLuJD-W`D?-cEibn1{|lOjVu~62V088 zfxbGAM8!~|&nT9QZyTDZ{-kuqQ_C#|_)|jgWK`4D!A^C7WlA#3=8miuEi=RSWdmBh zlvaK#f>PaU>?wbL`3FUGG*8Roq$J_NTRXJ;);+Yj7Dm7B9&@hd>#vIz*vy(Rwxtds zt~{I>JZw|>JWeXFt~Mmg`)Kj*j`rLiR*a6Hp>fR3Et2Zp0k_LD8CPPB`uLXG%mkIf zd}Gz+3w7;`Rf?R8T@ZbGhy$V?QG(`G)SDyOtrb7V?dm&n=h_#AApWoOmefZ1m1C<+ zk2ScZl%C9MhQ22W`*Ry;@{ZW_h?&+ih!s{n_=AOHZM?BNJ$I0ObEC?A6;7z-H!27njf0t5nn zKoA)2KrnC`Fa`JDh%ev)R#(700`LbhKd=r2oWb1l@2=B;@!z^ouyO_5fIyVnzn(k_ zRzen_AQZp@X24Cb=>nh#%Fv(*3KXjV7(f;bcR&G91v50rDuAdgXy67`zcE)3aR+XI z4C?Qt401{U21S6z{A0ufFC;+yLCA*z0)WTAPhf)l-vEIB9stn%2*w8q8yUX`Kr8{O z;{$Acd7SR+^Y9lnbn>dG~BXXU@d(&8m9Z8u0AcOE2`Fg#z{9Xxj0kx zJWK#{n7Y?PQVx9-kFO~p9sDJv>&pDollWqMiE<|AJtX|{n_+DWclhTL>~qdTHfm|y zI=3V-HHmx%E`XGP3r_qj^w4|-=PH~RnTMFi6lSl%6HGshZH^K3{2Wg&q+1((46OR3 zE~~&0p3W~XNgFuxC?W07hf4$=9$}0eqc6L zoXp0U=W~Bh2F_f10PT53g$$I@H8w(2YZp%M4+hJO+%bdVOUg*SQYBTep@(&@;yQpq z==!S(b)cIFQ>FE-E(e@ z>sILTxXPiwrn%F@(mj&O%rieb7XNrq3boM=DeHwGoK_E#sikd5Ha*O*OWp-L zx$bAD?h31iTOOR}Tfuk_@A|dHr}?K2uwjVYwA^)8}?U!DH%w5F&i~{k9>mesDW&}oQPX*Lfcthwk(QTto8BWVR z`v^exOZn>U@OM8x^T_hvWUW8TBVCF%wRX5!Bv8ZAd>o>6%4o;oU~aWll=+1V@2;(W z=#l@LQOaeF4~NHM>@WW?;pC{Y&5)0%l^BgzEUjp)H|>h!Y^%ZgB;IRjcm8D1g>P%l z&1$}IX-rYMlFdcSt30VqT!U8hD$72$M4u94&RP=k6vF%Vm+TOQNY|gR?$vKqv-#|D zko>$&OX*Eb@adOg`EQ56aO?DOJl?ag=X0x7ydZ{g{4~8x-{mK}Q0Vd#K{#;Ub7uOP zE(w&sxHtCO**Tg#YA(Lug?ewbn0goPamQ^TJ3h9CKiQQ@RIPgSp`23TSNIa8h7v|G z!5O95p$sQrJP}#!cdGfXokH^E!n7Aky7jiXRAD?6-Rx#6gPq}!klD1Hxqq>3e5CE~ G5AQ#u>T!_( literal 0 HcmV?d00001 diff --git a/src/test/java/org/bench4q/master/test/AuthenticationTest.java b/src/test/java/org/bench4q/master/test/AuthenticationTest.java new file mode 100644 index 00000000..ea2ec9e5 --- /dev/null +++ b/src/test/java/org/bench4q/master/test/AuthenticationTest.java @@ -0,0 +1,21 @@ +package org.bench4q.master.test; + +import org.bench4q.master.helper.HttpHelper; +import org.junit.Assert; +import org.junit.Test; + +public class AuthenticationTest { + @Test + public void testAuthenticationUser() { + String accessToken = "077e228e31ee315ed9fb03d45be559a162aecc8a8c614d7538459af807387cc3d04b065d015864d91627c8c73858d734ab0eb24b3d673efd2f5f3aa518cb48b511279a712c85cf8b84dabb32be6060fce1f077ff12818af870315fa03dafcb7618d8e87f98f1971abe569303a40d59aa3803d95c6b5a7dc42a22afee8a169b455e65dd56f8e035dd2549d028ddf814009ae600788c19817ade14321c65cc9f64dfc38000e6087e6423843a9af0cb2d3120f680a6f6e441f8b244d592b7390063a86587570180b5d4689eecf8480cfa37214adfe9f95a2b4deae6a96a3f4a3542e04f32c0493e8b8b23fe5220bb3c01a726b5274884631df61824c47d77d6d70d666aeb043da4f6e6697d7492b8965ac91ceeeb5fc324152a1c70a53ca74834672d526618f6cea2c4b3945b3117d95836e7d52c1756e6ed302d6c1d048ff9834e01ffb84b9ff3f99cc6d140b0dfc342820c291b7d0469581a598d214b14028684b92a131d322d979848bad864d93f5329b526f64ddb27be18f322f9837b33fefca5b7a2215c93faff5d09b21863f1f79780f78e35da6479e9484805508f1ee030b73a7d93a7ed14ed76d582faa20147a6c34a586905f712a0c1ffa25367e275887da4a7b2d6224c497a26de485d569ec67fefb907753276e234bca389496122b556d206cdf7c7a7976ee2780cdb6cf514ef71e5a8b64ab5015ef8c75b2e30fd44"; + String actual = new HttpHelper().get("http://localhost:8080/", + accessToken); + Assert.assertEquals("Hello [Test]", actual); + } + + @Test + public void testAuthenticationAnonymousUser() { + String actual = new HttpHelper().get("http://localhost:8080/", null); + Assert.assertEquals("Hello [Anonymous User]", actual); + } +} From ee57a36ba20db30f9bf18df9fff6c8793b2b9912 Mon Sep 17 00:00:00 2001 From: Zhen Tang Date: Wed, 26 Jun 2013 00:06:05 +0800 Subject: [PATCH 007/684] 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 008/684] 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 009/684] 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 010/684] 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 011/684] 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 012/684] 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 013/684] 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 014/684] 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 015/684] 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 e7256882b684374f350a072f5947a8eb320a8397 Mon Sep 17 00:00:00 2001 From: coderfengyun Date: Thu, 27 Jun 2013 16:04:18 +0800 Subject: [PATCH 016/684] add entities about database --- .../org/bench4q/master/entity/Script.java | 56 ++++++ .../java/org/bench4q/master/entity/User.java | 10 + .../org/bench4q/master/entity/behavior.java | 46 +++++ .../java/org/bench4q/master/entity/group.java | 53 ++++++ .../bench4q/master/entity/loadprofile.java | 33 ++++ .../org/bench4q/master/entity/plugin.java | 43 +++++ .../org/bench4q/master/entity/sample.java | 179 ++++++++++++++++++ .../java/org/bench4q/master/entity/timer.java | 53 ++++++ 8 files changed, 473 insertions(+) create mode 100644 src/main/java/org/bench4q/master/entity/Script.java create mode 100644 src/main/java/org/bench4q/master/entity/behavior.java create mode 100644 src/main/java/org/bench4q/master/entity/group.java create mode 100644 src/main/java/org/bench4q/master/entity/loadprofile.java create mode 100644 src/main/java/org/bench4q/master/entity/plugin.java create mode 100644 src/main/java/org/bench4q/master/entity/sample.java create mode 100644 src/main/java/org/bench4q/master/entity/timer.java diff --git a/src/main/java/org/bench4q/master/entity/Script.java b/src/main/java/org/bench4q/master/entity/Script.java new file mode 100644 index 00000000..3b1c3cd0 --- /dev/null +++ b/src/main/java/org/bench4q/master/entity/Script.java @@ -0,0 +1,56 @@ +package org.bench4q.master.entity; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Table; + +import com.sun.org.apache.xerces.internal.impl.dv.xs.DateTimeDV; + +@Entity +@Table(name = "Script") +public class Script { + + private int id; + private String name; + private DateTimeDV create_datetime; + private int user_id; + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id", nullable = false) + public int getId() { + return id; + } + public void setId(int id) { + this.id = id; + } + + @Column(name = "name", nullable = false) + public String getName() { + return name; + } + public void setName(String scriptName) { + this.name = scriptName; + } + + @Column(name = "create_datetime", nullable = false) + public DateTimeDV getCreate_datetime() { + return create_datetime; + } + public void setCreate_datetime(DateTimeDV create_datetime) { + this.create_datetime = create_datetime; + } + + @Column(name = "user_id", nullable = false) + public int getUser_id() { + return user_id; + } + public void setUser_id(int user_id) { + this.user_id = user_id; + } + + +} diff --git a/src/main/java/org/bench4q/master/entity/User.java b/src/main/java/org/bench4q/master/entity/User.java index e33f404a..fb22e1dd 100644 --- a/src/main/java/org/bench4q/master/entity/User.java +++ b/src/main/java/org/bench4q/master/entity/User.java @@ -13,6 +13,7 @@ public class User { private int id; private String userName; private String password; + private byte scope; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @@ -43,4 +44,13 @@ public class User { this.password = password; } + @Column(name = "scope", nullable = false) + public byte getScope() { + return scope; + } + + public void setScope(byte scope) { + this.scope = scope; + } + } diff --git a/src/main/java/org/bench4q/master/entity/behavior.java b/src/main/java/org/bench4q/master/entity/behavior.java new file mode 100644 index 00000000..d90dac66 --- /dev/null +++ b/src/main/java/org/bench4q/master/entity/behavior.java @@ -0,0 +1,46 @@ +package org.bench4q.master.entity; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Table; + +@Entity +@Table(name = "behavior") +public class behavior { + //id is the identifier only in database, in fact, behaviorstring is the identifier in the dtd + private int id; + private int Script_id; + private String behaviorstring; + + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id", nullable = false) + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + @Column(name = "script_id", nullable = false) + public int getScript_id() { + return Script_id; + } + public void setScript_id(int script_id) { + Script_id = script_id; + } + + @Column(name = "behaviorstring", nullable = false) + public String getBehaviorString() { + return behaviorstring; + } + + public void setBehaviorString(String behaviorstring) { + this.behaviorstring = behaviorstring; + } +} diff --git a/src/main/java/org/bench4q/master/entity/group.java b/src/main/java/org/bench4q/master/entity/group.java new file mode 100644 index 00000000..52d7166b --- /dev/null +++ b/src/main/java/org/bench4q/master/entity/group.java @@ -0,0 +1,53 @@ +package org.bench4q.master.entity; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Table; + +@Entity +@Table(name = "group") +public class group { + private int id; + private int behavior_id; + private int loadprofile_id; + private String forceStop; + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id", nullable = false) + public int getId() { + return id; + } + public void setId(int id) { + this.id = id; + } + + @Column(name = "behavior_id", nullable = false) + public int getBehavior_id() { + return behavior_id; + } + public void setBehavior_id(int behavior_id) { + this.behavior_id = behavior_id; + } + + @Column(name = "forceStop", nullable = false) + public String getForceStop() { + return forceStop; + } + public void setForceStop(String forceStop) { + this.forceStop = forceStop; + } + + @Column(name = "loadprofile_id", nullable = false) + public int getLoadprofile_id() { + return loadprofile_id; + } + public void setLoadprofile_id(int loadprofile_id) { + this.loadprofile_id = loadprofile_id; + } + + +} diff --git a/src/main/java/org/bench4q/master/entity/loadprofile.java b/src/main/java/org/bench4q/master/entity/loadprofile.java new file mode 100644 index 00000000..f0b469f9 --- /dev/null +++ b/src/main/java/org/bench4q/master/entity/loadprofile.java @@ -0,0 +1,33 @@ +package org.bench4q.master.entity; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Table; + +@Entity +@Table(name = "loadprofile") +public class loadprofile { + private int id; + private int script_id; + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id", nullable = false) + public int getId() { + return id; + } + public void setId(int id) { + this.id = id; + } + + @Column(name = "script_id", nullable = false) + public int getScript_id() { + return script_id; + } + public void setScript_id(int script_id) { + this.script_id = script_id; + } +} diff --git a/src/main/java/org/bench4q/master/entity/plugin.java b/src/main/java/org/bench4q/master/entity/plugin.java new file mode 100644 index 00000000..76c4efe6 --- /dev/null +++ b/src/main/java/org/bench4q/master/entity/plugin.java @@ -0,0 +1,43 @@ +package org.bench4q.master.entity; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Table; + +@Entity +@Table(name = "plugin") +public class plugin { + private int id; + private String use; + private String name; + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id", nullable = false) + public int getId() { + return id; + } + public void setId(int id) { + this.id = id; + } + + @Column(name = "use", nullable = false) + public String getUse() { + return use; + } + public void setUse(String use) { + this.use = use; + } + + @Column(name = "name", nullable = false) + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + +} diff --git a/src/main/java/org/bench4q/master/entity/sample.java b/src/main/java/org/bench4q/master/entity/sample.java new file mode 100644 index 00000000..2f45592b --- /dev/null +++ b/src/main/java/org/bench4q/master/entity/sample.java @@ -0,0 +1,179 @@ +package org.bench4q.master.entity; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Table; + + +@Entity +@Table(name = "sample") +public class sample { + private int id; + private String name; + //plugin_id is the only identifier of use just in database, and use is the true id of the use in dtd + private int plugin_id; + private int behavior_id; + + //for params + private String params_password; + private String params_parameters; + private String params_realm; + private String params_proxyport; + private String params_cookies; + private String params_proxypassword; + private String params_hostauth; + private String params_cookiepolicy; + private String params_uri; + private String params_username; + private String params_redirect; + private String params_localaddress; + private String params_proxylogin; + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id", nullable = false) + public int getId() { + return id; + } + public void setId(int id) { + this.id = id; + } + + + @Column(name = "name", nullable = false) + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + + @Column(name = "plugin_id", nullable = false) + public int getPlugin_id() { + return plugin_id; + } + public void setPlugin_id(int plugin_id) { + this.plugin_id = plugin_id; + } + + @Column(name = "behavior_id", nullable = false) + public int getBehavior_id() { + return behavior_id; + } + public void setBehavior_id(int behavior_id) { + this.behavior_id = behavior_id; + } + /** + * For Parameters in sample + */ + + @Column(name = "password", nullable = false) + public String getParams_Password() { + return params_password; + } + public void setParams_Password(String password) { + this.params_password = password; + } + + @Column(name = "parameters", nullable = false) + public String getParams_Parameters() { + return params_parameters; + } + public void setParams_Parameters(String parameters) { + this.params_parameters = parameters; + } + + @Column(name = "realm", nullable = false) + public String getParams_Realm() { + return params_realm; + } + public void setParams_Realm(String realm) { + this.params_realm = realm; + } + + @Column(name = "proxyport", nullable = false) + public String getParams_Proxyport() { + return params_proxyport; + } + public void setParams_Proxyport(String proxyport) { + this.params_proxyport = proxyport; + } + + @Column(name = "cookies", nullable = false) + public String getParams_Cookies() { + return params_cookies; + } + public void setParams_Cookies(String cookies) { + this.params_cookies = cookies; + } + + @Column(name = "proxypassword", nullable = false) + public String getParams_Proxypassword() { + return params_proxypassword; + } + public void setParams_Proxypassword(String proxypassword) { + this.params_proxypassword = proxypassword; + } + + @Column(name = "hostauth", nullable = false) + public String getParams_Hostauth() { + return params_hostauth; + } + public void setParams_Hostauth(String hostauth) { + this.params_hostauth = hostauth; + } + + @Column(name = "cookiepolicy", nullable = false) + public String getParams_Cookiepolicy() { + return params_cookiepolicy; + } + public void setParams_Cookiepolicy(String cookiepolicy) { + this.params_cookiepolicy = cookiepolicy; + } + + @Column(name = "uri", nullable = false) + public String getParams_Uri() { + return params_uri; + } + public void setParams_Uri(String uri) { + this.params_uri = uri; + } + + @Column(name = "username", nullable = false) + public String getParams_Username() { + return params_username; + } + public void setParams_Username(String username) { + this.params_username = username; + } + + @Column(name = "redirect", nullable = false) + public String getParams_Redirect() { + return params_redirect; + } + public void setParams_Redirect(String redirect) { + this.params_redirect = redirect; + } + + @Column(name = "localaddress", nullable = false) + public String getParams_Localaddress() { + return params_localaddress; + } + public void setParams_Localaddress(String localaddress) { + this.params_localaddress = localaddress; + } + + @Column(name = "proxylogin", nullable = false) + public String getParams_Proxylogin() { + return params_proxylogin; + } + public void setParams_Proxylogin(String proxylogin) { + this.params_proxylogin = proxylogin; + } + + + +} diff --git a/src/main/java/org/bench4q/master/entity/timer.java b/src/main/java/org/bench4q/master/entity/timer.java new file mode 100644 index 00000000..a18e2603 --- /dev/null +++ b/src/main/java/org/bench4q/master/entity/timer.java @@ -0,0 +1,53 @@ +package org.bench4q.master.entity; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Table; + +@Entity +@Table(name = "timer") +public class timer { + private int id; + private int plugin_id; + private int behavior_id; + private String name; + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id", nullable = false) + public int getId() { + return id; + } + public void setId(int id) { + this.id = id; + } + + @Column(name = "plugin_id", nullable = false) + public int getPlugin_id() { + return plugin_id; + } + public void setPlugin_id(int plugin_id) { + this.plugin_id = plugin_id; + } + + @Column(name = "name", nullable = false) + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + + @Column(name = "behavior_id", nullable = false) + public int getBehavior_id() { + return behavior_id; + } + public void setBehavior_id(int behavior_id) { + this.behavior_id = behavior_id; + } + + +} From 7344b4e3e1bcc84ee7bf3503ca858b1683ff3ffe Mon Sep 17 00:00:00 2001 From: Zhen Tang Date: Thu, 27 Jun 2013 16:10:04 +0800 Subject: [PATCH 017/684] 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 190194e83695961e419e49206e8f577a1c87d2bb Mon Sep 17 00:00:00 2001 From: coderfengyun Date: Thu, 27 Jun 2013 16:54:26 +0800 Subject: [PATCH 018/684] Add some entities about database, and ScriptCapture --- .../bench4q/master/api/BaseController.java | 4 +- .../bench4q/master/api/HomeController.java | 2 +- .../bench4q/master/api/UserController.java | 2 +- .../org/bench4q/master/auth/AccessToken.java | 8 +- .../master/auth/AuthenticationManager.java | 10 +- .../org/bench4q/master/entity/behavior.java | 46 ----- .../bench4q/master/entity/db/Behavior.java | 47 +++++ .../entity/{group.java => db/Group.java} | 22 +-- .../{loadprofile.java => db/LoadProfile.java} | 14 +- .../entity/{plugin.java => db/Plugin.java} | 4 +- .../org/bench4q/master/entity/db/Sample.java | 179 ++++++++++++++++++ .../master/entity/{ => db}/Script.java | 26 +-- .../entity/{timer.java => db/Timer.java} | 28 +-- .../bench4q/master/entity/{ => db}/User.java | 2 +- .../org/bench4q/master/entity/sample.java | 179 ------------------ .../bench4q/master/service/UserService.java | 4 +- 16 files changed, 289 insertions(+), 288 deletions(-) delete mode 100644 src/main/java/org/bench4q/master/entity/behavior.java create mode 100644 src/main/java/org/bench4q/master/entity/db/Behavior.java rename src/main/java/org/bench4q/master/entity/{group.java => db/Group.java} (66%) rename src/main/java/org/bench4q/master/entity/{loadprofile.java => db/LoadProfile.java} (67%) rename src/main/java/org/bench4q/master/entity/{plugin.java => db/Plugin.java} (88%) create mode 100644 src/main/java/org/bench4q/master/entity/db/Sample.java rename src/main/java/org/bench4q/master/entity/{ => db}/Script.java (58%) rename src/main/java/org/bench4q/master/entity/{timer.java => db/Timer.java} (55%) rename src/main/java/org/bench4q/master/entity/{ => db}/User.java (91%) delete mode 100644 src/main/java/org/bench4q/master/entity/sample.java diff --git a/src/main/java/org/bench4q/master/api/BaseController.java b/src/main/java/org/bench4q/master/api/BaseController.java index abb24a55..f82e0589 100644 --- a/src/main/java/org/bench4q/master/api/BaseController.java +++ b/src/main/java/org/bench4q/master/api/BaseController.java @@ -3,7 +3,7 @@ package org.bench4q.master.api; import javax.servlet.http.HttpServletRequest; import org.bench4q.master.auth.AuthenticationManager; -import org.bench4q.master.entity.User; +import org.bench4q.master.entity.db.User; import org.springframework.beans.factory.annotation.Autowired; public abstract class BaseController { @@ -33,7 +33,7 @@ public abstract class BaseController { return this.getAuthenticationManager().getPrincipal(this.getRequest()); } - protected boolean checkScope(String scope) { + protected boolean checkScope(byte scope) { return this.getAuthenticationManager().checkScope(this.getRequest(), scope); } diff --git a/src/main/java/org/bench4q/master/api/HomeController.java b/src/main/java/org/bench4q/master/api/HomeController.java index 5fdb7fe1..63ff7a61 100644 --- a/src/main/java/org/bench4q/master/api/HomeController.java +++ b/src/main/java/org/bench4q/master/api/HomeController.java @@ -1,6 +1,6 @@ package org.bench4q.master.api; -import org.bench4q.master.entity.User; +import org.bench4q.master.entity.db.User; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; diff --git a/src/main/java/org/bench4q/master/api/UserController.java b/src/main/java/org/bench4q/master/api/UserController.java index cc1b981c..8897d53b 100644 --- a/src/main/java/org/bench4q/master/api/UserController.java +++ b/src/main/java/org/bench4q/master/api/UserController.java @@ -4,7 +4,7 @@ import org.bench4q.master.api.model.AuthorizeResponseModel; import org.bench4q.master.api.model.RegisterResponseModel; import org.bench4q.master.auth.AccessToken; import org.bench4q.master.auth.AuthenticationManager; -import org.bench4q.master.entity.User; +import org.bench4q.master.entity.db.User; import org.bench4q.master.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; diff --git a/src/main/java/org/bench4q/master/auth/AccessToken.java b/src/main/java/org/bench4q/master/auth/AccessToken.java index 4668d574..5832fcba 100644 --- a/src/main/java/org/bench4q/master/auth/AccessToken.java +++ b/src/main/java/org/bench4q/master/auth/AccessToken.java @@ -2,15 +2,15 @@ package org.bench4q.master.auth; import java.io.Serializable; import java.util.Date; -import java.util.List; public class AccessToken implements Serializable { private static final long serialVersionUID = 4134631390384650898L; private String userName; private String password; + private byte scope; private Date generateTime; private int expiresIn; - private List scope; + public String getUserName() { return userName; @@ -44,11 +44,11 @@ public class AccessToken implements Serializable { this.expiresIn = expiresIn; } - public List getScope() { + public byte getScope() { return scope; } - public void setScope(List scope) { + public void setScope(byte scope) { this.scope = scope; } diff --git a/src/main/java/org/bench4q/master/auth/AuthenticationManager.java b/src/main/java/org/bench4q/master/auth/AuthenticationManager.java index 99be4f06..61cddc25 100644 --- a/src/main/java/org/bench4q/master/auth/AuthenticationManager.java +++ b/src/main/java/org/bench4q/master/auth/AuthenticationManager.java @@ -4,13 +4,12 @@ import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; -import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import javax.servlet.http.HttpServletRequest; -import org.bench4q.master.entity.User; +import org.bench4q.master.entity.db.User; import org.bench4q.master.helper.StringHelper; import org.bench4q.master.service.UserService; import org.springframework.beans.factory.annotation.Autowired; @@ -58,12 +57,12 @@ public class AuthenticationManager { return this.extractUser(accessToken); } - public boolean checkScope(HttpServletRequest request, String scope) { + public boolean checkScope(HttpServletRequest request, byte scope) { AccessToken accessToken = this.getAccessToken(request); if (accessToken == null) { return false; } - return accessToken.getScope().contains(scope); + return accessToken.getScope() >= scope; } public String generateCredential(User user) { @@ -105,8 +104,7 @@ public class AuthenticationManager { accessToken.setPassword(user.getPassword()); accessToken.setUserName(user.getUserName()); // TODO: scope - accessToken.setScope(new ArrayList()); - accessToken.getScope().add("all"); + accessToken.setScope(user.getScope()); return accessToken; } diff --git a/src/main/java/org/bench4q/master/entity/behavior.java b/src/main/java/org/bench4q/master/entity/behavior.java deleted file mode 100644 index d90dac66..00000000 --- a/src/main/java/org/bench4q/master/entity/behavior.java +++ /dev/null @@ -1,46 +0,0 @@ -package org.bench4q.master.entity; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.Table; - -@Entity -@Table(name = "behavior") -public class behavior { - //id is the identifier only in database, in fact, behaviorstring is the identifier in the dtd - private int id; - private int Script_id; - private String behaviorstring; - - - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - @Column(name = "id", nullable = false) - public int getId() { - return id; - } - - public void setId(int id) { - this.id = id; - } - - @Column(name = "script_id", nullable = false) - public int getScript_id() { - return Script_id; - } - public void setScript_id(int script_id) { - Script_id = script_id; - } - - @Column(name = "behaviorstring", nullable = false) - public String getBehaviorString() { - return behaviorstring; - } - - public void setBehaviorString(String behaviorstring) { - this.behaviorstring = behaviorstring; - } -} diff --git a/src/main/java/org/bench4q/master/entity/db/Behavior.java b/src/main/java/org/bench4q/master/entity/db/Behavior.java new file mode 100644 index 00000000..895bdae1 --- /dev/null +++ b/src/main/java/org/bench4q/master/entity/db/Behavior.java @@ -0,0 +1,47 @@ +package org.bench4q.master.entity.db; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Table; + +@Entity +@Table(name = "behavior") +public class Behavior { + // id is the identifier only in database, in fact, behaviorstring is the + // identifier in the dtd + private int id; + private int scriptId; + private String behaviorString; + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id", nullable = false) + public int getId() { + return id; + } + + public void setId(int id) { + this.id = id; + } + + @Column(name = "scriptId", nullable = false) + public int getScriptId() { + return scriptId; + } + + public void setScriptId(int scriptId) { + this.scriptId = scriptId; + } + + @Column(name = "behaviorString", nullable = false) + public String getBehaviorString() { + return behaviorString; + } + + public void setBehaviorString(String behaviorItring) { + this.behaviorString = behaviorItring; + } +} diff --git a/src/main/java/org/bench4q/master/entity/group.java b/src/main/java/org/bench4q/master/entity/db/Group.java similarity index 66% rename from src/main/java/org/bench4q/master/entity/group.java rename to src/main/java/org/bench4q/master/entity/db/Group.java index 52d7166b..988bf1f6 100644 --- a/src/main/java/org/bench4q/master/entity/group.java +++ b/src/main/java/org/bench4q/master/entity/db/Group.java @@ -1,4 +1,4 @@ -package org.bench4q.master.entity; +package org.bench4q.master.entity.db; import javax.persistence.Column; import javax.persistence.Entity; @@ -9,10 +9,10 @@ import javax.persistence.Table; @Entity @Table(name = "group") -public class group { +public class Group { private int id; - private int behavior_id; - private int loadprofile_id; + private int behaviorId; + private int loadProfileId; private String forceStop; @Id @@ -25,12 +25,12 @@ public class group { this.id = id; } - @Column(name = "behavior_id", nullable = false) - public int getBehavior_id() { - return behavior_id; + @Column(name = "behaviorId", nullable = false) + public int getBehaviorId() { + return behaviorId; } - public void setBehavior_id(int behavior_id) { - this.behavior_id = behavior_id; + public void setBehaviorId(int behaviorId) { + this.behaviorId = behaviorId; } @Column(name = "forceStop", nullable = false) @@ -43,10 +43,10 @@ public class group { @Column(name = "loadprofile_id", nullable = false) public int getLoadprofile_id() { - return loadprofile_id; + return loadProfileId; } public void setLoadprofile_id(int loadprofile_id) { - this.loadprofile_id = loadprofile_id; + this.loadProfileId = loadprofile_id; } diff --git a/src/main/java/org/bench4q/master/entity/loadprofile.java b/src/main/java/org/bench4q/master/entity/db/LoadProfile.java similarity index 67% rename from src/main/java/org/bench4q/master/entity/loadprofile.java rename to src/main/java/org/bench4q/master/entity/db/LoadProfile.java index f0b469f9..48f27da7 100644 --- a/src/main/java/org/bench4q/master/entity/loadprofile.java +++ b/src/main/java/org/bench4q/master/entity/db/LoadProfile.java @@ -1,4 +1,4 @@ -package org.bench4q.master.entity; +package org.bench4q.master.entity.db; import javax.persistence.Column; import javax.persistence.Entity; @@ -9,9 +9,9 @@ import javax.persistence.Table; @Entity @Table(name = "loadprofile") -public class loadprofile { +public class LoadProfile { private int id; - private int script_id; + private int scriptId; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @@ -24,10 +24,10 @@ public class loadprofile { } @Column(name = "script_id", nullable = false) - public int getScript_id() { - return script_id; + public int getScriptId() { + return scriptId; } - public void setScript_id(int script_id) { - this.script_id = script_id; + public void setScriptId(int scriptId) { + this.scriptId = scriptId; } } diff --git a/src/main/java/org/bench4q/master/entity/plugin.java b/src/main/java/org/bench4q/master/entity/db/Plugin.java similarity index 88% rename from src/main/java/org/bench4q/master/entity/plugin.java rename to src/main/java/org/bench4q/master/entity/db/Plugin.java index 76c4efe6..88efe33c 100644 --- a/src/main/java/org/bench4q/master/entity/plugin.java +++ b/src/main/java/org/bench4q/master/entity/db/Plugin.java @@ -1,4 +1,4 @@ -package org.bench4q.master.entity; +package org.bench4q.master.entity.db; import javax.persistence.Column; import javax.persistence.Entity; @@ -9,7 +9,7 @@ import javax.persistence.Table; @Entity @Table(name = "plugin") -public class plugin { +public class Plugin { private int id; private String use; private String name; diff --git a/src/main/java/org/bench4q/master/entity/db/Sample.java b/src/main/java/org/bench4q/master/entity/db/Sample.java new file mode 100644 index 00000000..7a951d1b --- /dev/null +++ b/src/main/java/org/bench4q/master/entity/db/Sample.java @@ -0,0 +1,179 @@ +package org.bench4q.master.entity.db; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.Table; + + +@Entity +@Table(name = "sample") +public class Sample { + private int id; + private String name; + //plugin_id is the only identifier of use just in database, and use is the true id of the use in dtd + private int pluginId; + private int behaviorId; + + //for params + private String paramsPassword; + private String paramsParameters; + private String paramsRealm; + private String paramsProxyport; + private String paramsCookies; + private String paramsProxypassword; + private String paramsHostauth; + private String paramsCookiepolicy; + private String paramsUri; + private String paramsUsername; + private String paramsRedirect; + private String paramsLocaladdress; + private String paramsProxylogin; + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id", nullable = false) + public int getId() { + return id; + } + public void setId(int id) { + this.id = id; + } + + + @Column(name = "name", nullable = false) + public String getName() { + return name; + } + public void setName(String name) { + this.name = name; + } + + @Column(name = "pluginId", nullable = false) + public int getPluginId() { + return pluginId; + } + public void setPluginId(int pluginId) { + this.pluginId = pluginId; + } + + @Column(name = "behaviorId", nullable = false) + public int getBehaviorId() { + return behaviorId; + } + public void setBehaviorId(int behaviorId) { + this.behaviorId = behaviorId; + } + /** + * For Parameters in sample + */ + + @Column(name = "paramsPassword", nullable = false) + public String getParamsPassword() { + return paramsPassword; + } + public void setParamsPassword(String password) { + this.paramsPassword = password; + } + + @Column(name = "paramsParameters", nullable = false) + public String getParams_Parameters() { + return paramsParameters; + } + public void setParamsParameters(String parameters) { + this.paramsParameters = parameters; + } + + @Column(name = "paramsRealm", nullable = false) + public String getParamsRealm() { + return paramsRealm; + } + public void setParamsRealm(String realm) { + this.paramsRealm = realm; + } + + @Column(name = "paramsProxyport", nullable = false) + public String getParamsProxyport() { + return paramsProxyport; + } + public void setParamsProxyport(String proxyport) { + this.paramsProxyport = proxyport; + } + + @Column(name = "paramsCookies", nullable = false) + public String getParamsCookies() { + return paramsCookies; + } + public void setParamsCookies(String cookies) { + this.paramsCookies = cookies; + } + + @Column(name = "paramsProxypassword", nullable = false) + public String getParamsProxypassword() { + return paramsProxypassword; + } + public void setParamsProxypassword(String proxypassword) { + this.paramsProxypassword = proxypassword; + } + + @Column(name = "paramsHostauth", nullable = false) + public String getParamsHostauth() { + return paramsHostauth; + } + public void setParamsHostauth(String hostauth) { + this.paramsHostauth = hostauth; + } + + @Column(name = "paramsCookiepolicy", nullable = false) + public String getParamsCookiepolicy() { + return paramsCookiepolicy; + } + public void setParamsCookiepolicy(String cookiepolicy) { + this.paramsCookiepolicy = cookiepolicy; + } + + @Column(name = "paramsUri", nullable = false) + public String getParamsUri() { + return paramsUri; + } + public void setParamsUri(String uri) { + this.paramsUri = uri; + } + + @Column(name = "paramsUsername", nullable = false) + public String getParamsUsername() { + return paramsUsername; + } + public void setParamsUsername(String username) { + this.paramsUsername = username; + } + + @Column(name = "paramsRedirect", nullable = false) + public String getParamsRedirect() { + return paramsRedirect; + } + public void setParamsRedirect(String redirect) { + this.paramsRedirect = redirect; + } + + @Column(name = "paramsLocaladdress", nullable = false) + public String getParamsLocaladdress() { + return paramsLocaladdress; + } + public void setParamsLocaladdress(String localaddress) { + this.paramsLocaladdress = localaddress; + } + + @Column(name = "paramsProxylogin", nullable = false) + public String getParamsProxylogin() { + return paramsProxylogin; + } + public void setParamsProxylogin(String proxylogin) { + this.paramsProxylogin = proxylogin; + } + + + +} diff --git a/src/main/java/org/bench4q/master/entity/Script.java b/src/main/java/org/bench4q/master/entity/db/Script.java similarity index 58% rename from src/main/java/org/bench4q/master/entity/Script.java rename to src/main/java/org/bench4q/master/entity/db/Script.java index 3b1c3cd0..d76247b8 100644 --- a/src/main/java/org/bench4q/master/entity/Script.java +++ b/src/main/java/org/bench4q/master/entity/db/Script.java @@ -1,4 +1,4 @@ -package org.bench4q.master.entity; +package org.bench4q.master.entity.db; import javax.persistence.Column; import javax.persistence.Entity; @@ -15,8 +15,8 @@ public class Script { private int id; private String name; - private DateTimeDV create_datetime; - private int user_id; + private DateTimeDV createDatetime; + private int userId; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @@ -36,20 +36,20 @@ public class Script { this.name = scriptName; } - @Column(name = "create_datetime", nullable = false) - public DateTimeDV getCreate_datetime() { - return create_datetime; + @Column(name = "createDatetime", nullable = false) + public DateTimeDV getCreateDatetime() { + return createDatetime; } - public void setCreate_datetime(DateTimeDV create_datetime) { - this.create_datetime = create_datetime; + public void setCreateDatetime(DateTimeDV createDatetime) { + this.createDatetime = createDatetime; } - @Column(name = "user_id", nullable = false) - public int getUser_id() { - return user_id; + @Column(name = "userId", nullable = false) + public int getUserId() { + return userId; } - public void setUser_id(int user_id) { - this.user_id = user_id; + public void setUserId(int userId) { + this.userId = userId; } diff --git a/src/main/java/org/bench4q/master/entity/timer.java b/src/main/java/org/bench4q/master/entity/db/Timer.java similarity index 55% rename from src/main/java/org/bench4q/master/entity/timer.java rename to src/main/java/org/bench4q/master/entity/db/Timer.java index a18e2603..81c2f807 100644 --- a/src/main/java/org/bench4q/master/entity/timer.java +++ b/src/main/java/org/bench4q/master/entity/db/Timer.java @@ -1,4 +1,4 @@ -package org.bench4q.master.entity; +package org.bench4q.master.entity.db; import javax.persistence.Column; import javax.persistence.Entity; @@ -9,10 +9,10 @@ import javax.persistence.Table; @Entity @Table(name = "timer") -public class timer { +public class Timer { private int id; - private int plugin_id; - private int behavior_id; + private int pluginId; + private int behaviorId; private String name; @Id @@ -25,12 +25,12 @@ public class timer { this.id = id; } - @Column(name = "plugin_id", nullable = false) - public int getPlugin_id() { - return plugin_id; + @Column(name = "pluginId", nullable = false) + public int getPluginId() { + return pluginId; } - public void setPlugin_id(int plugin_id) { - this.plugin_id = plugin_id; + public void setPluginId(int pluginId) { + this.pluginId = pluginId; } @Column(name = "name", nullable = false) @@ -41,12 +41,12 @@ public class timer { this.name = name; } - @Column(name = "behavior_id", nullable = false) - public int getBehavior_id() { - return behavior_id; + @Column(name = "behaviorId", nullable = false) + public int getBehaviorId() { + return behaviorId; } - public void setBehavior_id(int behavior_id) { - this.behavior_id = behavior_id; + public void setBehaviorId(int behaviorId) { + this.behaviorId = behaviorId; } diff --git a/src/main/java/org/bench4q/master/entity/User.java b/src/main/java/org/bench4q/master/entity/db/User.java similarity index 91% rename from src/main/java/org/bench4q/master/entity/User.java rename to src/main/java/org/bench4q/master/entity/db/User.java index fb22e1dd..c7652779 100644 --- a/src/main/java/org/bench4q/master/entity/User.java +++ b/src/main/java/org/bench4q/master/entity/db/User.java @@ -1,4 +1,4 @@ -package org.bench4q.master.entity; +package org.bench4q.master.entity.db; import javax.persistence.Column; import javax.persistence.Entity; diff --git a/src/main/java/org/bench4q/master/entity/sample.java b/src/main/java/org/bench4q/master/entity/sample.java deleted file mode 100644 index 2f45592b..00000000 --- a/src/main/java/org/bench4q/master/entity/sample.java +++ /dev/null @@ -1,179 +0,0 @@ -package org.bench4q.master.entity; - -import javax.persistence.Column; -import javax.persistence.Entity; -import javax.persistence.GeneratedValue; -import javax.persistence.GenerationType; -import javax.persistence.Id; -import javax.persistence.Table; - - -@Entity -@Table(name = "sample") -public class sample { - private int id; - private String name; - //plugin_id is the only identifier of use just in database, and use is the true id of the use in dtd - private int plugin_id; - private int behavior_id; - - //for params - private String params_password; - private String params_parameters; - private String params_realm; - private String params_proxyport; - private String params_cookies; - private String params_proxypassword; - private String params_hostauth; - private String params_cookiepolicy; - private String params_uri; - private String params_username; - private String params_redirect; - private String params_localaddress; - private String params_proxylogin; - - @Id - @GeneratedValue(strategy = GenerationType.IDENTITY) - @Column(name = "id", nullable = false) - public int getId() { - return id; - } - public void setId(int id) { - this.id = id; - } - - - @Column(name = "name", nullable = false) - public String getName() { - return name; - } - public void setName(String name) { - this.name = name; - } - - @Column(name = "plugin_id", nullable = false) - public int getPlugin_id() { - return plugin_id; - } - public void setPlugin_id(int plugin_id) { - this.plugin_id = plugin_id; - } - - @Column(name = "behavior_id", nullable = false) - public int getBehavior_id() { - return behavior_id; - } - public void setBehavior_id(int behavior_id) { - this.behavior_id = behavior_id; - } - /** - * For Parameters in sample - */ - - @Column(name = "password", nullable = false) - public String getParams_Password() { - return params_password; - } - public void setParams_Password(String password) { - this.params_password = password; - } - - @Column(name = "parameters", nullable = false) - public String getParams_Parameters() { - return params_parameters; - } - public void setParams_Parameters(String parameters) { - this.params_parameters = parameters; - } - - @Column(name = "realm", nullable = false) - public String getParams_Realm() { - return params_realm; - } - public void setParams_Realm(String realm) { - this.params_realm = realm; - } - - @Column(name = "proxyport", nullable = false) - public String getParams_Proxyport() { - return params_proxyport; - } - public void setParams_Proxyport(String proxyport) { - this.params_proxyport = proxyport; - } - - @Column(name = "cookies", nullable = false) - public String getParams_Cookies() { - return params_cookies; - } - public void setParams_Cookies(String cookies) { - this.params_cookies = cookies; - } - - @Column(name = "proxypassword", nullable = false) - public String getParams_Proxypassword() { - return params_proxypassword; - } - public void setParams_Proxypassword(String proxypassword) { - this.params_proxypassword = proxypassword; - } - - @Column(name = "hostauth", nullable = false) - public String getParams_Hostauth() { - return params_hostauth; - } - public void setParams_Hostauth(String hostauth) { - this.params_hostauth = hostauth; - } - - @Column(name = "cookiepolicy", nullable = false) - public String getParams_Cookiepolicy() { - return params_cookiepolicy; - } - public void setParams_Cookiepolicy(String cookiepolicy) { - this.params_cookiepolicy = cookiepolicy; - } - - @Column(name = "uri", nullable = false) - public String getParams_Uri() { - return params_uri; - } - public void setParams_Uri(String uri) { - this.params_uri = uri; - } - - @Column(name = "username", nullable = false) - public String getParams_Username() { - return params_username; - } - public void setParams_Username(String username) { - this.params_username = username; - } - - @Column(name = "redirect", nullable = false) - public String getParams_Redirect() { - return params_redirect; - } - public void setParams_Redirect(String redirect) { - this.params_redirect = redirect; - } - - @Column(name = "localaddress", nullable = false) - public String getParams_Localaddress() { - return params_localaddress; - } - public void setParams_Localaddress(String localaddress) { - this.params_localaddress = localaddress; - } - - @Column(name = "proxylogin", nullable = false) - public String getParams_Proxylogin() { - return params_proxylogin; - } - public void setParams_Proxylogin(String proxylogin) { - this.params_proxylogin = proxylogin; - } - - - -} diff --git a/src/main/java/org/bench4q/master/service/UserService.java b/src/main/java/org/bench4q/master/service/UserService.java index 7f0b423e..01ca2566 100644 --- a/src/main/java/org/bench4q/master/service/UserService.java +++ b/src/main/java/org/bench4q/master/service/UserService.java @@ -1,6 +1,7 @@ package org.bench4q.master.service; -import org.bench4q.master.entity.User; +import org.bench4q.master.entity.Constant; +import org.bench4q.master.entity.db.User; import org.bench4q.master.helper.HashHelper; import org.bench4q.master.helper.SessionHelper; import org.hibernate.Session; @@ -44,6 +45,7 @@ public class UserService { user = new User(); user.setUserName(userName); user.setPassword(this.hashPassword(password)); + user.setScope(Constant.NORAML_AUTHENTICATION); session.merge(user); transaction.commit(); return true; From 0e7bd6897fe5079721c2c63f2375bfe8ca42d32e Mon Sep 17 00:00:00 2001 From: coderfengyun Date: Thu, 27 Jun 2013 16:55:15 +0800 Subject: [PATCH 019/684] Add some constant and RecordScript --- .../master/api/RecordScriptController.java | 91 +++++++++++++++++++ .../OperateScriptServerResponseModel.java | 26 ++++++ .../org/bench4q/master/entity/Constant.java | 8 ++ .../master/service/RecordScriptService.java | 5 + 4 files changed, 130 insertions(+) create mode 100644 src/main/java/org/bench4q/master/api/RecordScriptController.java create mode 100644 src/main/java/org/bench4q/master/api/model/OperateScriptServerResponseModel.java create mode 100644 src/main/java/org/bench4q/master/entity/Constant.java create mode 100644 src/main/java/org/bench4q/master/service/RecordScriptService.java diff --git a/src/main/java/org/bench4q/master/api/RecordScriptController.java b/src/main/java/org/bench4q/master/api/RecordScriptController.java new file mode 100644 index 00000000..a204a950 --- /dev/null +++ b/src/main/java/org/bench4q/master/api/RecordScriptController.java @@ -0,0 +1,91 @@ +package org.bench4q.master.api; + +import javax.servlet.http.HttpServletRequest; + +import org.bench4q.master.api.model.OperateScriptServerResponseModel; +import org.bench4q.master.auth.AuthenticationManager; +import org.bench4q.master.entity.Constant; +import org.bench4q.master.entity.db.User; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.ResponseBody; + +@Controller +@RequestMapping("/RecordScript") +public class RecordScriptController { + private HttpServletRequest request; + private AuthenticationManager authenticationManager; + + + public HttpServletRequest getRequest() { + return request; + } + + @Autowired + public void setRequest(HttpServletRequest request) { + this.request = request; + } + + public AuthenticationManager getAuthenticationManager() { + return authenticationManager; + } + + @Autowired + public void setAuthenticationManager(AuthenticationManager authenticationManager) { + this.authenticationManager = authenticationManager; + } + + public User getPrinciple() + { + return authenticationManager.getPrincipal(this.getRequest()); + } + + public boolean CheckScope(byte scope) + { + return authenticationManager.checkScope(this.getRequest(), scope); + } + + @RequestMapping(value = "/startScriptRecordServer", method = RequestMethod.GET) + @ResponseBody + public OperateScriptServerResponseModel startScriptRecordServer() + { + OperateScriptServerResponseModel responseModel = + new OperateScriptServerResponseModel(); + + if(!this.CheckScope(Constant.NORAML_AUTHENTICATION)) + { + + responseModel.setSuccess(false); + responseModel.setFailCauseString("has no power for this!!!"); + return responseModel; + } + + //TODO: add startScriptRecordServer + + responseModel.setSuccess(true); + responseModel.setFailCauseString(""); + return responseModel; + } + + @RequestMapping(value = "/stopScriptRecordServer", method = RequestMethod.GET) + @ResponseBody + public OperateScriptServerResponseModel stopScriptRecordServer(@RequestParam String accessTocken) + { + OperateScriptServerResponseModel responseModel = + new OperateScriptServerResponseModel(); + if (!CheckScope(Constant.NORAML_AUTHENTICATION)) + { + responseModel.setSuccess(false); + responseModel.setFailCauseString("has no power for this!!!"); + return responseModel; + } + //TODO: add stopScriptServer + + responseModel.setSuccess(true); + responseModel.setFailCauseString(""); + return responseModel; + } +} diff --git a/src/main/java/org/bench4q/master/api/model/OperateScriptServerResponseModel.java b/src/main/java/org/bench4q/master/api/model/OperateScriptServerResponseModel.java new file mode 100644 index 00000000..c8e5da14 --- /dev/null +++ b/src/main/java/org/bench4q/master/api/model/OperateScriptServerResponseModel.java @@ -0,0 +1,26 @@ +package org.bench4q.master.api.model; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; + +@XmlRootElement(name = "OperateScriptServerResponse") +public class OperateScriptServerResponseModel { + private boolean success; + private String failCauseString; + + @XmlElement + public boolean isSuccess() { + return success; + } + public void setSuccess(boolean success) { + this.success = success; + } + + @XmlElement + public String getFailCauseString() { + return failCauseString; + } + public void setFailCauseString(String failCauseString) { + this.failCauseString = failCauseString; + } +} diff --git a/src/main/java/org/bench4q/master/entity/Constant.java b/src/main/java/org/bench4q/master/entity/Constant.java new file mode 100644 index 00000000..33a4b68d --- /dev/null +++ b/src/main/java/org/bench4q/master/entity/Constant.java @@ -0,0 +1,8 @@ +package org.bench4q.master.entity; + +public class Constant { + public static byte NORAML_AUTHENTICATION = 0; + public static byte SUPER_AUTHENTICATION = 1; + + public static Integer getPortLock = 0; +} diff --git a/src/main/java/org/bench4q/master/service/RecordScriptService.java b/src/main/java/org/bench4q/master/service/RecordScriptService.java new file mode 100644 index 00000000..817f870b --- /dev/null +++ b/src/main/java/org/bench4q/master/service/RecordScriptService.java @@ -0,0 +1,5 @@ +package org.bench4q.master.service; + +public class RecordScriptService { + +} From d41cb8d32aaac5a910216dc57049a4e57ea4f510 Mon Sep 17 00:00:00 2001 From: Zhen Tang Date: Thu, 27 Jun 2013 17:43:04 +0800 Subject: [PATCH 020/684] 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 021/684] 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 022/684] 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 023/684] 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 024/684] 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 025/684] 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 026/684] 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 027/684] 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 028/684] 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 453bfeafebf72b5913224003024884ea00f02a27 Mon Sep 17 00:00:00 2001 From: coderfengyun Date: Sun, 30 Jun 2013 11:05:25 +0800 Subject: [PATCH 029/684] add AgentInfo and do some modify --- .../master/api/RecordScriptController.java | 56 ++++++++++++------- .../api/model/AuthorizeResponseModel.java | 2 +- .../api/model/RegisterResponseModel.java | 3 +- .../org/bench4q/master/entity/AgentInfo.java | 34 +++++++++++ .../org/bench4q/master/entity/Constant.java | 5 ++ .../bench4q/master/entity/db/Behavior.java | 6 +- .../org/bench4q/master/entity/db/Group.java | 8 +-- .../bench4q/master/entity/db/LoadProfile.java | 2 +- .../org/bench4q/master/entity/db/Sample.java | 54 +++++++++--------- .../org/bench4q/master/entity/db/Script.java | 16 +++--- src/main/resources/hibernate.cfg.xml | 9 ++- 11 files changed, 128 insertions(+), 67 deletions(-) create mode 100644 src/main/java/org/bench4q/master/entity/AgentInfo.java diff --git a/src/main/java/org/bench4q/master/api/RecordScriptController.java b/src/main/java/org/bench4q/master/api/RecordScriptController.java index a204a950..8395b84f 100644 --- a/src/main/java/org/bench4q/master/api/RecordScriptController.java +++ b/src/main/java/org/bench4q/master/api/RecordScriptController.java @@ -1,5 +1,7 @@ package org.bench4q.master.api; +import java.util.Random; + import javax.servlet.http.HttpServletRequest; import org.bench4q.master.api.model.OperateScriptServerResponseModel; @@ -52,40 +54,54 @@ public class RecordScriptController { @ResponseBody public OperateScriptServerResponseModel startScriptRecordServer() { - OperateScriptServerResponseModel responseModel = - new OperateScriptServerResponseModel(); - if(!this.CheckScope(Constant.NORAML_AUTHENTICATION)) { - - responseModel.setSuccess(false); - responseModel.setFailCauseString("has no power for this!!!"); - return responseModel; + return returnResponseModel(false, + "has no power for this!!!"); + } + if(this.getRequest().getSession().getAttribute("ScriptWizard") != null) + { + return returnResponseModel(false, + "A Script Recording is in Process, please wait"); + } + //TODO: add startScriptRecordServer + synchronized (Constant.getPortLock) + { + int portNum = Constant.ScriptPortPool.size(); + if(portNum == 0) + { + return returnResponseModel(false, + "Script Record port not enough, please wait for a while!"); + } + Random rand = new Random(); + int ran = rand.nextInt(portNum); + @SuppressWarnings("unused") + int portForUse = Constant.ScriptPortPool.get(ran); + Constant.ScriptPortPool.remove(ran); } - //TODO: add startScriptRecordServer - - responseModel.setSuccess(true); - responseModel.setFailCauseString(""); - return responseModel; + return returnResponseModel(true, ""); } @RequestMapping(value = "/stopScriptRecordServer", method = RequestMethod.GET) @ResponseBody public OperateScriptServerResponseModel stopScriptRecordServer(@RequestParam String accessTocken) { - OperateScriptServerResponseModel responseModel = - new OperateScriptServerResponseModel(); if (!CheckScope(Constant.NORAML_AUTHENTICATION)) { - responseModel.setSuccess(false); - responseModel.setFailCauseString("has no power for this!!!"); - return responseModel; + return returnResponseModel(false, "has no power for this!!!"); } //TODO: add stopScriptServer - - responseModel.setSuccess(true); - responseModel.setFailCauseString(""); + return returnResponseModel(true, ""); + } + + private OperateScriptServerResponseModel returnResponseModel(boolean isSuccess, + String failCauseString) + { + OperateScriptServerResponseModel responseModel = + new OperateScriptServerResponseModel(); + responseModel.setSuccess(isSuccess); + responseModel.setFailCauseString(failCauseString); return responseModel; } } diff --git a/src/main/java/org/bench4q/master/api/model/AuthorizeResponseModel.java b/src/main/java/org/bench4q/master/api/model/AuthorizeResponseModel.java index a030fd0a..8a5bf5c6 100644 --- a/src/main/java/org/bench4q/master/api/model/AuthorizeResponseModel.java +++ b/src/main/java/org/bench4q/master/api/model/AuthorizeResponseModel.java @@ -1,8 +1,8 @@ package org.bench4q.master.api.model; +import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; -import com.sun.xml.internal.txw2.annotation.XmlElement; @XmlRootElement(name = "authorizeResponse") public class AuthorizeResponseModel { diff --git a/src/main/java/org/bench4q/master/api/model/RegisterResponseModel.java b/src/main/java/org/bench4q/master/api/model/RegisterResponseModel.java index 538884f5..f17d7a31 100644 --- a/src/main/java/org/bench4q/master/api/model/RegisterResponseModel.java +++ b/src/main/java/org/bench4q/master/api/model/RegisterResponseModel.java @@ -1,9 +1,8 @@ package org.bench4q.master.api.model; +import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; -import com.sun.xml.internal.txw2.annotation.XmlElement; - @XmlRootElement(name = "registerResponse") public class RegisterResponseModel { private boolean success; diff --git a/src/main/java/org/bench4q/master/entity/AgentInfo.java b/src/main/java/org/bench4q/master/entity/AgentInfo.java new file mode 100644 index 00000000..35d9deaa --- /dev/null +++ b/src/main/java/org/bench4q/master/entity/AgentInfo.java @@ -0,0 +1,34 @@ +package org.bench4q.master.entity; + +public class AgentInfo { + private String ipAdress; + private int port; + private int MaxLoad; + private int RemainLoad; + + public String getIpAdress() { + return ipAdress; + } + public void setIpAdress(String ipAdress) { + this.ipAdress = ipAdress; + } + + public int getPort() { + return port; + } + public void setPort(int port) { + this.port = port; + } + public int getMaxLoad() { + return MaxLoad; + } + public void setMaxLoad(int maxLoad) { + MaxLoad = maxLoad; + } + public int getRemainLoad() { + return RemainLoad; + } + public void setRemainLoad(int remainLoad) { + RemainLoad = remainLoad; + } +} diff --git a/src/main/java/org/bench4q/master/entity/Constant.java b/src/main/java/org/bench4q/master/entity/Constant.java index 33a4b68d..17306dd6 100644 --- a/src/main/java/org/bench4q/master/entity/Constant.java +++ b/src/main/java/org/bench4q/master/entity/Constant.java @@ -1,8 +1,13 @@ package org.bench4q.master.entity; +import java.util.Vector; + public class Constant { public static byte NORAML_AUTHENTICATION = 0; public static byte SUPER_AUTHENTICATION = 1; public static Integer getPortLock = 0; + public static Vector AgentPool = new Vector(); + public static Vector ScriptPortPool = new Vector(); } + diff --git a/src/main/java/org/bench4q/master/entity/db/Behavior.java b/src/main/java/org/bench4q/master/entity/db/Behavior.java index 895bdae1..74475d58 100644 --- a/src/main/java/org/bench4q/master/entity/db/Behavior.java +++ b/src/main/java/org/bench4q/master/entity/db/Behavior.java @@ -10,7 +10,7 @@ import javax.persistence.Table; @Entity @Table(name = "behavior") public class Behavior { - // id is the identifier only in database, in fact, behaviorstring is the + // id is the identifier only in database, in fact, behaviorString is the // identifier in the dtd private int id; private int scriptId; @@ -41,7 +41,7 @@ public class Behavior { return behaviorString; } - public void setBehaviorString(String behaviorItring) { - this.behaviorString = behaviorItring; + public void setBehaviorString(String behaviorString) { + this.behaviorString = behaviorString; } } diff --git a/src/main/java/org/bench4q/master/entity/db/Group.java b/src/main/java/org/bench4q/master/entity/db/Group.java index 988bf1f6..46871701 100644 --- a/src/main/java/org/bench4q/master/entity/db/Group.java +++ b/src/main/java/org/bench4q/master/entity/db/Group.java @@ -41,12 +41,12 @@ public class Group { this.forceStop = forceStop; } - @Column(name = "loadprofile_id", nullable = false) - public int getLoadprofile_id() { + @Column(name = "loadProfileId", nullable = false) + public int getLoadprofileId() { return loadProfileId; } - public void setLoadprofile_id(int loadprofile_id) { - this.loadProfileId = loadprofile_id; + public void setLoadprofileId(int loadprofileId) { + this.loadProfileId = loadprofileId; } diff --git a/src/main/java/org/bench4q/master/entity/db/LoadProfile.java b/src/main/java/org/bench4q/master/entity/db/LoadProfile.java index 48f27da7..9c35b04d 100644 --- a/src/main/java/org/bench4q/master/entity/db/LoadProfile.java +++ b/src/main/java/org/bench4q/master/entity/db/LoadProfile.java @@ -23,7 +23,7 @@ public class LoadProfile { this.id = id; } - @Column(name = "script_id", nullable = false) + @Column(name = "scriptId", nullable = false) public int getScriptId() { return scriptId; } diff --git a/src/main/java/org/bench4q/master/entity/db/Sample.java b/src/main/java/org/bench4q/master/entity/db/Sample.java index 7a951d1b..85512a99 100644 --- a/src/main/java/org/bench4q/master/entity/db/Sample.java +++ b/src/main/java/org/bench4q/master/entity/db/Sample.java @@ -74,104 +74,104 @@ public class Sample { public String getParamsPassword() { return paramsPassword; } - public void setParamsPassword(String password) { - this.paramsPassword = password; + public void setParamsPassword(String paramsPassword) { + this.paramsPassword = paramsPassword; } @Column(name = "paramsParameters", nullable = false) - public String getParams_Parameters() { + public String getParamsParameters() { return paramsParameters; } - public void setParamsParameters(String parameters) { - this.paramsParameters = parameters; + public void setParamsParameters(String paramsParameters) { + this.paramsParameters = paramsParameters; } @Column(name = "paramsRealm", nullable = false) public String getParamsRealm() { return paramsRealm; } - public void setParamsRealm(String realm) { - this.paramsRealm = realm; + public void setParamsRealm(String paramsRealm) { + this.paramsRealm = paramsRealm; } @Column(name = "paramsProxyport", nullable = false) public String getParamsProxyport() { return paramsProxyport; } - public void setParamsProxyport(String proxyport) { - this.paramsProxyport = proxyport; + public void setParamsProxyport(String paramsProxyport) { + this.paramsProxyport = paramsProxyport; } @Column(name = "paramsCookies", nullable = false) public String getParamsCookies() { return paramsCookies; } - public void setParamsCookies(String cookies) { - this.paramsCookies = cookies; + public void setParamsCookies(String paramsCookies) { + this.paramsCookies = paramsCookies; } @Column(name = "paramsProxypassword", nullable = false) public String getParamsProxypassword() { return paramsProxypassword; } - public void setParamsProxypassword(String proxypassword) { - this.paramsProxypassword = proxypassword; + public void setParamsProxypassword(String paramsProxypassword) { + this.paramsProxypassword = paramsProxypassword; } @Column(name = "paramsHostauth", nullable = false) public String getParamsHostauth() { return paramsHostauth; } - public void setParamsHostauth(String hostauth) { - this.paramsHostauth = hostauth; + public void setParamsHostauth(String paramsHostauth) { + this.paramsHostauth = paramsHostauth; } @Column(name = "paramsCookiepolicy", nullable = false) public String getParamsCookiepolicy() { return paramsCookiepolicy; } - public void setParamsCookiepolicy(String cookiepolicy) { - this.paramsCookiepolicy = cookiepolicy; + public void setParamsCookiepolicy(String paramsCookiepolicy) { + this.paramsCookiepolicy = paramsCookiepolicy; } @Column(name = "paramsUri", nullable = false) public String getParamsUri() { return paramsUri; } - public void setParamsUri(String uri) { - this.paramsUri = uri; + public void setParamsUri(String paramsUri) { + this.paramsUri = paramsUri; } @Column(name = "paramsUsername", nullable = false) public String getParamsUsername() { return paramsUsername; } - public void setParamsUsername(String username) { - this.paramsUsername = username; + public void setParamsUsername(String paramsUsername) { + this.paramsUsername = paramsUsername; } @Column(name = "paramsRedirect", nullable = false) public String getParamsRedirect() { return paramsRedirect; } - public void setParamsRedirect(String redirect) { - this.paramsRedirect = redirect; + public void setParamsRedirect(String paramsRedirect) { + this.paramsRedirect = paramsRedirect; } @Column(name = "paramsLocaladdress", nullable = false) public String getParamsLocaladdress() { return paramsLocaladdress; } - public void setParamsLocaladdress(String localaddress) { - this.paramsLocaladdress = localaddress; + public void setParamsLocaladdress(String paramsLocaladdress) { + this.paramsLocaladdress = paramsLocaladdress; } @Column(name = "paramsProxylogin", nullable = false) public String getParamsProxylogin() { return paramsProxylogin; } - public void setParamsProxylogin(String proxylogin) { - this.paramsProxylogin = proxylogin; + public void setParamsProxylogin(String paramsProxylogin) { + this.paramsProxylogin = paramsProxylogin; } diff --git a/src/main/java/org/bench4q/master/entity/db/Script.java b/src/main/java/org/bench4q/master/entity/db/Script.java index d76247b8..900c0e8a 100644 --- a/src/main/java/org/bench4q/master/entity/db/Script.java +++ b/src/main/java/org/bench4q/master/entity/db/Script.java @@ -1,5 +1,6 @@ package org.bench4q.master.entity.db; +import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; @@ -7,15 +8,13 @@ import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; -import com.sun.org.apache.xerces.internal.impl.dv.xs.DateTimeDV; - @Entity @Table(name = "Script") public class Script { private int id; private String name; - private DateTimeDV createDatetime; + private Date createDatetime; private int userId; @Id @@ -32,15 +31,15 @@ public class Script { public String getName() { return name; } - public void setName(String scriptName) { - this.name = scriptName; + public void setName(String name) { + this.name = name; } - @Column(name = "createDatetime", nullable = false) - public DateTimeDV getCreateDatetime() { + @Column(name = "createDateTime", nullable = false) + public Date getCreateDatetime() { return createDatetime; } - public void setCreateDatetime(DateTimeDV createDatetime) { + public void setCreateDatetime(Date createDatetime) { this.createDatetime = createDatetime; } @@ -53,4 +52,5 @@ public class Script { } + } diff --git a/src/main/resources/hibernate.cfg.xml b/src/main/resources/hibernate.cfg.xml index 5911c827..2cdad0b1 100644 --- a/src/main/resources/hibernate.cfg.xml +++ b/src/main/resources/hibernate.cfg.xml @@ -15,6 +15,13 @@ org.hibernate.dialect.MySQLDialect update - + + + + + + + + \ No newline at end of file From f4f22a47d4952b1b4da74308f0c37f8941d2a3f5 Mon Sep 17 00:00:00 2001 From: Zhen Tang Date: Sun, 30 Jun 2013 11:48:52 +0800 Subject: [PATCH 030/684] 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 031/684] 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 766f46ee4193151488d5cffab87e8d8bb90030ba Mon Sep 17 00:00:00 2001 From: coderfengyun Date: Sun, 30 Jun 2013 15:43:47 +0800 Subject: [PATCH 032/684] add things about the HTTPCAPTURE --- .../bench4q/master/api/BaseController.java | 1 + .../master/api/RecordScriptController.java | 83 +++++------ .../org/bench4q/master/entity/Constant.java | 2 + .../bench4q/master/entity/ScriptCapturer.java | 133 ++++++++++++++++++ 4 files changed, 173 insertions(+), 46 deletions(-) create mode 100644 src/main/java/org/bench4q/master/entity/ScriptCapturer.java diff --git a/src/main/java/org/bench4q/master/api/BaseController.java b/src/main/java/org/bench4q/master/api/BaseController.java index f82e0589..e5cbf8be 100644 --- a/src/main/java/org/bench4q/master/api/BaseController.java +++ b/src/main/java/org/bench4q/master/api/BaseController.java @@ -37,4 +37,5 @@ public abstract class BaseController { return this.getAuthenticationManager().checkScope(this.getRequest(), scope); } + } diff --git a/src/main/java/org/bench4q/master/api/RecordScriptController.java b/src/main/java/org/bench4q/master/api/RecordScriptController.java index 8395b84f..742186d6 100644 --- a/src/main/java/org/bench4q/master/api/RecordScriptController.java +++ b/src/main/java/org/bench4q/master/api/RecordScriptController.java @@ -1,13 +1,9 @@ package org.bench4q.master.api; import java.util.Random; - -import javax.servlet.http.HttpServletRequest; - import org.bench4q.master.api.model.OperateScriptServerResponseModel; -import org.bench4q.master.auth.AuthenticationManager; import org.bench4q.master.entity.Constant; -import org.bench4q.master.entity.db.User; +import org.bench4q.master.entity.ScriptCapturer; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @@ -17,82 +13,76 @@ import org.springframework.web.bind.annotation.ResponseBody; @Controller @RequestMapping("/RecordScript") -public class RecordScriptController { - private HttpServletRequest request; - private AuthenticationManager authenticationManager; - - - public HttpServletRequest getRequest() { - return request; - } +public class RecordScriptController extends BaseController { + private int portForRecord; + private ScriptCapturer scriptCapturer; @Autowired - public void setRequest(HttpServletRequest request) { - this.request = request; + public int getPortForRecord() { + return portForRecord; } - - public AuthenticationManager getAuthenticationManager() { - return authenticationManager; + + public void setPortForRecord(int portForRecord) { + this.portForRecord = portForRecord; } - @Autowired - public void setAuthenticationManager(AuthenticationManager authenticationManager) { - this.authenticationManager = authenticationManager; + public ScriptCapturer getScriptCapturer() { + return scriptCapturer; } - - public User getPrinciple() - { - return authenticationManager.getPrincipal(this.getRequest()); + + public void setScriptCapturer(ScriptCapturer scriptCapturer) { + this.scriptCapturer = scriptCapturer; } - - public boolean CheckScope(byte scope) - { - return authenticationManager.checkScope(this.getRequest(), scope); - } - @RequestMapping(value = "/startScriptRecordServer", method = RequestMethod.GET) @ResponseBody - public OperateScriptServerResponseModel startScriptRecordServer() + public OperateScriptServerResponseModel startScriptRecordServer(@RequestParam String accessTocken) { - if(!this.CheckScope(Constant.NORAML_AUTHENTICATION)) + if(!this.checkScope(Constant.NORAML_AUTHENTICATION)) { return returnResponseModel(false, "has no power for this!!!"); } - if(this.getRequest().getSession().getAttribute("ScriptWizard") != null) - { - return returnResponseModel(false, - "A Script Recording is in Process, please wait"); - } //TODO: add startScriptRecordServer synchronized (Constant.getPortLock) { - int portNum = Constant.ScriptPortPool.size(); - if(portNum == 0) + int portSumNum = Constant.ScriptPortPool.size(); + if(portSumNum == 0) { return returnResponseModel(false, "Script Record port not enough, please wait for a while!"); } Random rand = new Random(); - int ran = rand.nextInt(portNum); - @SuppressWarnings("unused") - int portForUse = Constant.ScriptPortPool.get(ran); + int ran = rand.nextInt(portSumNum); + setPortForRecord(Constant.ScriptPortPool.get(ran)); Constant.ScriptPortPool.remove(ran); } - return returnResponseModel(true, ""); + //String pathString = this.getClass().getResource("/").getPath(); + scriptCapturer = new ScriptCapturer(portForRecord, "C:\\Script\\", + this.getPrincipal().getUserName()); + scriptCapturer.startCurrentRecord(); + System.out.println("server started and begin to wait!"); + + return returnResponseModel(true, "you should set you agent server now, please use IP address: " + + scriptCapturer.getIpHttpCaptureServerAdress() +" and port number : " + + scriptCapturer.getIpHttpCaptureServerAdress() + "!"); } @RequestMapping(value = "/stopScriptRecordServer", method = RequestMethod.GET) @ResponseBody public OperateScriptServerResponseModel stopScriptRecordServer(@RequestParam String accessTocken) { - if (!CheckScope(Constant.NORAML_AUTHENTICATION)) + if (!checkScope(Constant.NORAML_AUTHENTICATION)) { return returnResponseModel(false, "has no power for this!!!"); } + if (this.getScriptCapturer().equals(null)) { + return returnResponseModel(false, "there is no RecordingServer to stop"); + } //TODO: add stopScriptServer - return returnResponseModel(true, ""); + scriptCapturer.stopCurrentRecord(); + Constant.ScriptPortPool.add(this.getPortForRecord()); + return returnResponseModel(true, "RecordServer stop"); } private OperateScriptServerResponseModel returnResponseModel(boolean isSuccess, @@ -104,4 +94,5 @@ public class RecordScriptController { responseModel.setFailCauseString(failCauseString); return responseModel; } + } diff --git a/src/main/java/org/bench4q/master/entity/Constant.java b/src/main/java/org/bench4q/master/entity/Constant.java index 17306dd6..477f9c84 100644 --- a/src/main/java/org/bench4q/master/entity/Constant.java +++ b/src/main/java/org/bench4q/master/entity/Constant.java @@ -3,11 +3,13 @@ package org.bench4q.master.entity; import java.util.Vector; public class Constant { + public static byte NORAML_AUTHENTICATION = 0; public static byte SUPER_AUTHENTICATION = 1; public static Integer getPortLock = 0; public static Vector AgentPool = new Vector(); public static Vector ScriptPortPool = new Vector(); + public static String HTTPCAPTUREGENERATOR = "maxq.generator.IsacCodeGenerator"; } diff --git a/src/main/java/org/bench4q/master/entity/ScriptCapturer.java b/src/main/java/org/bench4q/master/entity/ScriptCapturer.java new file mode 100644 index 00000000..6c454631 --- /dev/null +++ b/src/main/java/org/bench4q/master/entity/ScriptCapturer.java @@ -0,0 +1,133 @@ +package org.bench4q.master.entity; + +import java.io.IOException; +import javax.swing.JTextArea; +import maxq.HttpCapture; +import maxq.Utils.UserException; + +public class ScriptCapturer { + + private HttpCapture httpCapture = null; + private int portForRecord; + private String scriptPath; + private boolean isRecording; + private boolean isProxyServerRunning; + private String ipHttpCaptureServerAdress; + + public ScriptCapturer(int portForRecord, String scriptParentPath, String userName) + { + this.setPortForRecord(portForRecord); + this.setScriptPath(scriptParentPath + userName + "\\Script_test.xml"); + //TODO get the machine's ipAdress + this.setIpHttpCaptureServerAdress(""); + } + + public boolean isRecording() { + return isRecording; + } + + public void setRecording(boolean isRecording) { + this.isRecording = isRecording; + } + + public String getScriptPath() { + return scriptPath; + } + + public void setScriptPath(String scriptPath) { + this.scriptPath = scriptPath; + } + + public boolean isProxyServerRunning() { + return isProxyServerRunning; + } + + public void setProxyServerRunning(boolean isProxyServerRunning) { + this.isProxyServerRunning = isProxyServerRunning; + } + + public String getIpHttpCaptureServerAdress() { + return ipHttpCaptureServerAdress; + } + + public void setIpHttpCaptureServerAdress(String ipHttpCaptureServerAdress) { + this.ipHttpCaptureServerAdress = ipHttpCaptureServerAdress; + } + + public int getPortForRecord() { + return portForRecord; + } + + public void setPortForRecord(int portForRecord) { + this.portForRecord = portForRecord; + } + + private void startHttpCaptureProxyServer() { + try { + httpCapture = new HttpCapture( this.getScriptPath(), this.getPortForRecord(), + Constant.HTTPCAPTUREGENERATOR, new JTextArea()); + httpCapture.startProxyServer(); + this.setProxyServerRunning(true); + System.out.println("INFO: Proxy Server Started at Port: " + this.getPortForRecord()); + } catch (IOException e1) { + System.out.println("Error When build the proxy server!"); + e1.printStackTrace(); + } catch (UserException e1) { + System.out.println("Error When build the proxy server!"); + e1.printStackTrace(); + } + } + + public void shutHttpCaptureProxyServer(){ + try { + if (!isProxyServerRunning()) { + return; + } + if(this.isRecording()){ + httpCapture.stopRecording(); + } + httpCapture.shutProxyServer(); + } catch (IOException e1) { + System.out.println("Error When shut the httpCapture proxy server!"); + e1.printStackTrace(); + } catch (UserException e1) { + System.out.println("Error When shut the httpCapture proxy server!"); + e1.printStackTrace(); + } + } + + public void startCurrentRecord() + { + try { + if(!this.isProxyServerRunning()) + { + this.startHttpCaptureProxyServer(); + } + httpCapture.startRecording(); + this.setRecording(true); + } catch (IOException e1) { + System.out.println("Error When start recording!"); + e1.printStackTrace(); + } catch (UserException e1) { + System.out.println("Error When start recording!"); + e1.printStackTrace(); + } + } + + public void stopCurrentRecord() { + try { + if(!this.isRecording()) + { + return; + } + httpCapture.stopRecording(); + this.setRecording(false); + } catch (IOException e1) { + System.out.println("Error When stop recording!"); + e1.printStackTrace(); + } catch (UserException e1) { + System.out.println("Error When stop recording!"); + e1.printStackTrace(); + } + } +} From 14d9f54e3d18729ec281df61f2721569f21675f2 Mon Sep 17 00:00:00 2001 From: Zhen Tang Date: Sun, 30 Jun 2013 15:54:22 +0800 Subject: [PATCH 033/684] 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 034/684] 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 035/684] 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 036/684] 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 037/684] 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 038/684] 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 039/684] 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 040/684] 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 041/684] 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 0a33058678496c990c3b29e4e8622cbdd93f5bf4 Mon Sep 17 00:00:00 2001 From: coderfengyun Date: Thu, 4 Jul 2013 17:37:43 +0800 Subject: [PATCH 042/684] something about httpcapture --- .../generator/GeneratorFactory.java | 69 +++++++++++++++++++ .../generator/IScriptGenerator.java | 23 +++++++ 2 files changed, 92 insertions(+) create mode 100644 src/main/java/org/bench4q/master/entity/httpcapture/generator/GeneratorFactory.java create mode 100644 src/main/java/org/bench4q/master/entity/httpcapture/generator/IScriptGenerator.java diff --git a/src/main/java/org/bench4q/master/entity/httpcapture/generator/GeneratorFactory.java b/src/main/java/org/bench4q/master/entity/httpcapture/generator/GeneratorFactory.java new file mode 100644 index 00000000..37da1ad3 --- /dev/null +++ b/src/main/java/org/bench4q/master/entity/httpcapture/generator/GeneratorFactory.java @@ -0,0 +1,69 @@ +package org.bench4q.master.entity.httpcapture.generator; + +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import org.bench4q.master.entity.httpcapture.Config; +import org.bench4q.master.entity.httpcapture.ProxyServer.Observer; +import org.bench4q.master.entity.httpcapture.Utils; +import org.bench4q.master.entity.httpcapture.IScriptAdapter; + +public class GeneratorFactory { + private static Config config = Config.getConfig(); + public static final String GENERATOR_CLASSNAMES_PROPERTY = "generator.classnames"; + public static final String JYTHON_CLASSNAME = "com.bitmechanic.maxq.generator.JythonCodeGenerator"; + + public static String[] getClasses() + { + String names = config.getProperty("generator.classnames", + "com.bitmechanic.maxq.generator.JythonCodeGenerator"); + return Utils.splitString(names, ":"); + } + + public static String getClassDescription(String className) + throws ClassNotFoundException, IllegalAccessException, InvocationTargetException + { + Method getGenDesc; + Class gen = Class.forName(className); + try + { + getGenDesc = gen.getMethod("getGeneratorDescription", gen); + } + catch (NoSuchMethodException e) + { + return className; + } + + return (String)getGenDesc.invoke(null, null); + } + + public static IScriptGenerator newGenerator(String className, IScriptAdapter adapter) + { + Class clazz = null; + try { + clazz = GeneratorFactory.class.getClassLoader().loadClass(className); + } catch (ClassNotFoundException e) { + throw new IllegalStateException("Invalid test script class specified . Class not found:" + className); + } + + if (IScriptGenerator.class.isAssignableFrom(clazz)) { + try { + Class[] generatorConstructorParameterClasses = { IScriptAdapter.class }; + Object[] generatorConstructorParameters = { adapter }; + Constructor constructor = clazz.getDeclaredConstructor(generatorConstructorParameterClasses); + return (IScriptGenerator)constructor.newInstance(generatorConstructorParameters); + } + catch (NoSuchMethodException e) { + throw new IllegalStateException("Invalid test script class specified. Must have a constructor that takes in properties: " + className); + } catch (InstantiationException e) { + throw new IllegalStateException("Invalid test script class specified. Could not construct: " + className); + } catch (InvocationTargetException e) { + e.printStackTrace(); + throw new IllegalStateException("Invalid test script class specified. Exception thrown in constructor: " + className); + } catch (IllegalAccessException e) { + throw new IllegalStateException("Invalid test script class specified. IllegalAccessException: " + className); + } + } + throw new IllegalStateException("Invalid test script class specified. Does not implement IScriptGenerator: " + className); + } +} diff --git a/src/main/java/org/bench4q/master/entity/httpcapture/generator/IScriptGenerator.java b/src/main/java/org/bench4q/master/entity/httpcapture/generator/IScriptGenerator.java new file mode 100644 index 00000000..5459fcbc --- /dev/null +++ b/src/main/java/org/bench4q/master/entity/httpcapture/generator/IScriptGenerator.java @@ -0,0 +1,23 @@ +package org.bench4q.master.entity.httpcapture.generator; + +import org.bench4q.master.entity.httpcapture.ProxyServer; + +public interface IScriptGenerator extends ProxyServer.Observer { + public static final String EOL = System.getProperty("line.separator"); + + public abstract String[] getValidFileExtensions(); + + public abstract String parseTestName(); + + public abstract void doStartRecording(); + + public abstract void doStopRecording(); + + public abstract void doNew(); + + public abstract void doSave(String paramString1, String paramString2); + + public abstract void doLoad(); + + public abstract void close(); +} From 3230a6bebeda7d21d636e8671e108461a66b0e01 Mon Sep 17 00:00:00 2001 From: Zhen Tang Date: Fri, 5 Jul 2013 11:35:31 +0800 Subject: [PATCH 043/684] 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 044/684] 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 045/684] 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 0bd85eb54c1e6abed1824b01be44b48485ad9990 Mon Sep 17 00:00:00 2001 From: coderfengyun Date: Mon, 8 Jul 2013 20:31:39 +0800 Subject: [PATCH 046/684] add something about httpcapture --- pom.xml | 26 ++ .../master/api/RecordPortController.java | 33 ++ .../master/api/RecordScriptController.java | 9 +- .../OrganizeRecordPortResponseModel.java | 26 ++ .../org/bench4q/master/entity/AgentInfo.java | 19 +- .../org/bench4q/master/entity/Constant.java | 2 + .../bench4q/master/entity/ScriptCapturer.java | 10 +- .../master/entity/httpcapture/Config.java | 300 ++++++++++++++++++ .../entity/httpcapture/HttpCapture.java | 69 ++++ .../entity/httpcapture/HttpRequestHeader.java | 193 +++++++++++ .../entity/httpcapture/IScriptAdapter.java | 15 + .../JTextAreaTestScriptAdapter.java | 40 +++ .../master/entity/httpcapture/Param.java | 6 + .../entity/httpcapture/ProxyServer.java | 89 ++++++ .../entity/httpcapture/RequestHandler.java | 214 +++++++++++++ .../master/entity/httpcapture/Test.java | 148 +++++++++ .../master/entity/httpcapture/Utils.java | 122 +++++++ src/main/resources/hibernate.cfg.xml | 13 +- 18 files changed, 1315 insertions(+), 19 deletions(-) create mode 100644 src/main/java/org/bench4q/master/api/RecordPortController.java create mode 100644 src/main/java/org/bench4q/master/api/model/OrganizeRecordPortResponseModel.java create mode 100644 src/main/java/org/bench4q/master/entity/httpcapture/Config.java create mode 100644 src/main/java/org/bench4q/master/entity/httpcapture/HttpCapture.java create mode 100644 src/main/java/org/bench4q/master/entity/httpcapture/HttpRequestHeader.java create mode 100644 src/main/java/org/bench4q/master/entity/httpcapture/IScriptAdapter.java create mode 100644 src/main/java/org/bench4q/master/entity/httpcapture/JTextAreaTestScriptAdapter.java create mode 100644 src/main/java/org/bench4q/master/entity/httpcapture/Param.java create mode 100644 src/main/java/org/bench4q/master/entity/httpcapture/ProxyServer.java create mode 100644 src/main/java/org/bench4q/master/entity/httpcapture/RequestHandler.java create mode 100644 src/main/java/org/bench4q/master/entity/httpcapture/Test.java create mode 100644 src/main/java/org/bench4q/master/entity/httpcapture/Utils.java diff --git a/pom.xml b/pom.xml index b6756476..f965b883 100644 --- a/pom.xml +++ b/pom.xml @@ -52,6 +52,32 @@ mysql-connector-java 5.1.25 + + maxq + maxq + 0.94 + + + org.httpunit + httpunit + 1.7.2 + + + org.apache.logging.log4j + log4j + 2.0-beta7 + pom + + + log4j + log4j + 1.2.17 + + + org.python + jython + 2.7-b1 + bench4q-master diff --git a/src/main/java/org/bench4q/master/api/RecordPortController.java b/src/main/java/org/bench4q/master/api/RecordPortController.java new file mode 100644 index 00000000..965975bf --- /dev/null +++ b/src/main/java/org/bench4q/master/api/RecordPortController.java @@ -0,0 +1,33 @@ +package org.bench4q.master.api; + +import org.bench4q.master.api.model.OrganizeRecordPortResponseModel; +import org.bench4q.master.entity.AgentInfo; +import org.bench4q.master.entity.Constant; +import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.RequestParam; + +@Controller +@RequestMapping("/RecordScript") +public class RecordPortController extends BaseController { + @RequestMapping(value = "/AddPortToPortPool", method = RequestMethod.GET) + public OrganizeRecordPortResponseModel AddPortToPortPool(@RequestParam int port, @RequestParam String accessToken) + { + OrganizeRecordPortResponseModel organizeRecordPortResponseModel = new OrganizeRecordPortResponseModel(); + if(!this.checkScope(Constant.SUPER_AUTHENTICATION)) + { + organizeRecordPortResponseModel.setSuccess(false); + organizeRecordPortResponseModel.setFailCauseString("you don't hava the power to add port to pool!"); + return organizeRecordPortResponseModel; + } + + if (Constant.ScriptPortPool.contains(port)) { + + } + Constant.ScriptPortPool.add(port); + organizeRecordPortResponseModel.setSuccess(true); + organizeRecordPortResponseModel.setFailCauseString("add port " + port +" to ScriptPortPool sucessfully!"); + return organizeRecordPortResponseModel; + } +} diff --git a/src/main/java/org/bench4q/master/api/RecordScriptController.java b/src/main/java/org/bench4q/master/api/RecordScriptController.java index 742186d6..b0551d94 100644 --- a/src/main/java/org/bench4q/master/api/RecordScriptController.java +++ b/src/main/java/org/bench4q/master/api/RecordScriptController.java @@ -33,15 +33,16 @@ public class RecordScriptController extends BaseController { public void setScriptCapturer(ScriptCapturer scriptCapturer) { this.scriptCapturer = scriptCapturer; } + @RequestMapping(value = "/startScriptRecordServer", method = RequestMethod.GET) @ResponseBody public OperateScriptServerResponseModel startScriptRecordServer(@RequestParam String accessTocken) { - if(!this.checkScope(Constant.NORAML_AUTHENTICATION)) + /*if(!this.checkScope(Constant.NORAML_AUTHENTICATION)) { return returnResponseModel(false, "has no power for this!!!"); - } + }*/ //TODO: add startScriptRecordServer synchronized (Constant.getPortLock) { @@ -58,8 +59,10 @@ public class RecordScriptController extends BaseController { } //String pathString = this.getClass().getResource("/").getPath(); + //scriptCapturer = new ScriptCapturer(portForRecord, "C:\\Script\\", + //this.getPrincipal().getUserName()); scriptCapturer = new ScriptCapturer(portForRecord, "C:\\Script\\", - this.getPrincipal().getUserName()); + "Chen"); scriptCapturer.startCurrentRecord(); System.out.println("server started and begin to wait!"); diff --git a/src/main/java/org/bench4q/master/api/model/OrganizeRecordPortResponseModel.java b/src/main/java/org/bench4q/master/api/model/OrganizeRecordPortResponseModel.java new file mode 100644 index 00000000..9b7dea08 --- /dev/null +++ b/src/main/java/org/bench4q/master/api/model/OrganizeRecordPortResponseModel.java @@ -0,0 +1,26 @@ +package org.bench4q.master.api.model; + +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; + +@XmlRootElement(name = "OperateScriptServerResponse") +public class OrganizeRecordPortResponseModel { + private boolean success; + private String failCauseString; + + @XmlElement + public boolean isSuccess() { + return success; + } + public void setSuccess(boolean success) { + this.success = success; + } + + @XmlElement + public String getFailCauseString() { + return failCauseString; + } + public void setFailCauseString(String failCauseString) { + this.failCauseString = failCauseString; + } +} diff --git a/src/main/java/org/bench4q/master/entity/AgentInfo.java b/src/main/java/org/bench4q/master/entity/AgentInfo.java index 35d9deaa..c3d17e19 100644 --- a/src/main/java/org/bench4q/master/entity/AgentInfo.java +++ b/src/main/java/org/bench4q/master/entity/AgentInfo.java @@ -3,9 +3,16 @@ package org.bench4q.master.entity; public class AgentInfo { private String ipAdress; private int port; - private int MaxLoad; - private int RemainLoad; + private int maxLoad; + private int remainLoad; + public AgentInfo(int port, int maxLoad, int remianLoad, String ipAdress) + { + this.setIpAdress(ipAdress); + this.setPort(port); + this.setMaxLoad(maxLoad); + this.setRemainLoad(remianLoad); + } public String getIpAdress() { return ipAdress; } @@ -20,15 +27,15 @@ public class AgentInfo { this.port = port; } public int getMaxLoad() { - return MaxLoad; + return maxLoad; } public void setMaxLoad(int maxLoad) { - MaxLoad = maxLoad; + this.maxLoad = maxLoad; } public int getRemainLoad() { - return RemainLoad; + return remainLoad; } public void setRemainLoad(int remainLoad) { - RemainLoad = remainLoad; + this.remainLoad = remainLoad; } } diff --git a/src/main/java/org/bench4q/master/entity/Constant.java b/src/main/java/org/bench4q/master/entity/Constant.java index 477f9c84..bd9b0455 100644 --- a/src/main/java/org/bench4q/master/entity/Constant.java +++ b/src/main/java/org/bench4q/master/entity/Constant.java @@ -7,6 +7,8 @@ public class Constant { public static byte NORAML_AUTHENTICATION = 0; public static byte SUPER_AUTHENTICATION = 1; + public static int AGENTMAXLOAD = 400; + public static String TESTIPADRESS = "127.0.0.1"; public static Integer getPortLock = 0; public static Vector AgentPool = new Vector(); public static Vector ScriptPortPool = new Vector(); diff --git a/src/main/java/org/bench4q/master/entity/ScriptCapturer.java b/src/main/java/org/bench4q/master/entity/ScriptCapturer.java index 6c454631..cfc00765 100644 --- a/src/main/java/org/bench4q/master/entity/ScriptCapturer.java +++ b/src/main/java/org/bench4q/master/entity/ScriptCapturer.java @@ -2,17 +2,21 @@ package org.bench4q.master.entity; import java.io.IOException; import javax.swing.JTextArea; -import maxq.HttpCapture; -import maxq.Utils.UserException; +//import maxq.HttpCapture; +//import maxq.Utils.UserException; + +import org.bench4q.master.entity.httpcapture.HttpCapture; +import org.bench4q.master.entity.httpcapture.Utils.UserException; public class ScriptCapturer { - private HttpCapture httpCapture = null; + //private HttpCapture httpCapture = null; private int portForRecord; private String scriptPath; private boolean isRecording; private boolean isProxyServerRunning; private String ipHttpCaptureServerAdress; + private HttpCapture httpCapture; public ScriptCapturer(int portForRecord, String scriptParentPath, String userName) { diff --git a/src/main/java/org/bench4q/master/entity/httpcapture/Config.java b/src/main/java/org/bench4q/master/entity/httpcapture/Config.java new file mode 100644 index 00000000..b9605947 --- /dev/null +++ b/src/main/java/org/bench4q/master/entity/httpcapture/Config.java @@ -0,0 +1,300 @@ +package org.bench4q.master.entity.httpcapture; + +import java.io.IOException; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Iterator; +import java.util.List; +import java.util.Properties; +import java.util.regex.Pattern; +import java.util.regex.PatternSyntaxException; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.log4j.ConsoleAppender; +import org.apache.log4j.Layout; +import org.apache.log4j.Level; +import org.apache.log4j.Logger; +import org.apache.log4j.PatternLayout; +import org.python.util.PythonInterpreter; + +public class Config { + private static Config config = null; + private static final Log log = LogFactory.getLog(Config.class); + private static Properties props; + private String pythonPath; + private int port = 8090; + private boolean debug; + private boolean quiet; + private String exist; + private String replace; + private List includeList; + private List excludeList; + private List includePatterns = new ArrayList(); + private List excludePatterns = new ArrayList(); + private String scriptArg; + private ProxySettings proxySettings; + private static String defDriverPkgName = "com.bitmechanic.maxq"; + private static String defValidatorPkgName = "com.bitmechanic.maxq"; + + static + { + Layout layout = new PatternLayout("%d [%t] %-5p %c - %m%n"); + Logger.getRootLogger().addAppender(new ConsoleAppender(layout, "System.err")); + } + + public static Config getConfig() + { + if (config == null) + initConfig(); + return config; + } + + public static void initConfig() + { + config = new Config(); + String maxqDir = System.getProperty("maxq.dir"); + String pathSep = System.getProperty("file.separator"); + + String propertiesFileName = System.getProperty("properties.file", "maxq.properties"); + InputStream propertiesStream = Config.class.getClassLoader().getResourceAsStream(propertiesFileName); + props = new Properties(); + if (propertiesStream != null) + { + try + { + props.load(propertiesStream); + log.debug("Generator: " + props.getProperty("generator.classnames")); + } + catch (IOException e) + { + throw new ExceptionInInitializerError(e); + } + + } + + config.addPythonPath(maxqDir + pathSep + "jython"); + + String path = config.getProperty("python.path"); + if (path != null) { + config.addPythonPath(path); + } + + String portStr = props.getProperty("local.proxy.port"); + if (portStr != null) + config.port = Integer.parseInt(portStr); + } + + public void completeInit() + throws Utils.UserException + { + Level level = this.quiet ? Level.WARN : this.debug ? Level.ALL : Level.INFO; + Logger.getRootLogger().setLevel(level); + + System.setProperty("org.apache.commons.logging.simplelog.defaultlog", "warn"); + + Properties ppref = new Properties(); + if (getPythonPath() != null) + ppref.put("python.path", getPythonPath()); + PythonInterpreter.initialize(System.getProperties(), ppref, new String[0]); + + String host = getProperty("remote.proxy.host"); + Integer port = getPropertyInt("remote.proxy.port"); + if ((host == null ? 1 : 0) != (port == null ? 1 : 0)) + throw new Utils.UserException("Not using proxy server. You must set both remote.proxy.host and remote.proxy.port."); + if ((host != null) && (port != null)) { + this.proxySettings = new ProxySettings(); + this.proxySettings.host = host; + this.proxySettings.port = port.intValue(); + log.info("Proxying requests via " + this.proxySettings.host + ":" + Integer.toString(this.proxySettings.port)); + } + } + + public String getProperty(String prop) + { + return (String)props.get(prop); + } + + public String getProperty(String prop, String def) + { + String val = getProperty(prop); + return (val == null) || (val.equals("")) ? def : val; + } + + public void setProperty(String property, String value) + { + props.setProperty(property, value); + } + + public Integer getPropertyInt(String prop) + throws Utils.UserException + { + String s = getProperty(prop); + if (s == null) + return null; + try { + return new Integer(s); } catch (NumberFormatException e) { + } + throw new Utils.UserException(prop + " property must be an integer"); + } + + public void addPythonPath(String path) + { + if (this.pythonPath == null) + this.pythonPath = path; + else + this.pythonPath = (this.pythonPath + System.getProperty("path.separator") + path); + } + + public String getPythonPath() + { + return this.pythonPath; + } + + public void setPort(int pt) + { + this.port = pt; + } + + public int getPort() + { + return this.port; + } + + public void setDebug(boolean d) + { + this.debug = d; + } + + public boolean isDebug() + { + return this.debug; + } + + public void setQuiet(boolean q) + { + this.quiet = q; + } + + public boolean isQuiet() + { + return this.quiet; + } + + public void setExist(String e) + { + this.exist = e; + } + + public String getExist() + { + return this.exist; + } + + public void setReplace(String e) + { + this.replace = e; + } + + public String getReplace() + { + return this.replace; + } + + public void setIncludePatterns(String[] pats) + { + this.includeList = Arrays.asList(pats); + createPatterns(this.includeList, this.includePatterns); + } + + public void setExcludePatterns(String[] pats) + { + this.excludeList = Arrays.asList(pats); + createPatterns(this.excludeList, this.excludePatterns); + } + + public List getIncludePatterns() + { + return this.includePatterns; + } + + public List getExcludePatterns() + { + return this.excludePatterns; + } + + public void setScriptArg(String arg) + { + this.scriptArg = arg; + } + + public String getScriptArg() + { + return this.scriptArg; + } + + public static String getDriverPkgName() + { + return System.getProperty("maxq.driverpkgname", defDriverPkgName); + } + + public static String getValidatorPkgName() + { + return System.getProperty("maxq.validatorpkgname", defValidatorPkgName); + } + + public static Log getTestLogger() + { + return LogFactory.getLog("com.bitmechanic.maxq.testrun"); + } + + public ProxySettings getProxySettings() + { + return this.proxySettings; + } + + public void setProxySettings(ProxySettings proxySettings) + { + this.proxySettings = proxySettings; + } + + private void createPatterns(List list, List excludePatterns2) + { + Iterator iter = list.iterator(); + excludePatterns2.clear(); + while (iter.hasNext()) + try { + Pattern p = Pattern.compile(iter.next().toString()); + excludePatterns2.add(p); + } catch (PatternSyntaxException e) { + log.error(e); + } + } + + public static class ProxySettings + { + String host; + int port; + + public String getHost() + { + return this.host; + } + + public void setHost(String host) + { + this.host = host; + } + + public int getPort() + { + return this.port; + } + + public void setPort(int port) + { + this.port = port; + } + } +} diff --git a/src/main/java/org/bench4q/master/entity/httpcapture/HttpCapture.java b/src/main/java/org/bench4q/master/entity/httpcapture/HttpCapture.java new file mode 100644 index 00000000..a7bf0c6f --- /dev/null +++ b/src/main/java/org/bench4q/master/entity/httpcapture/HttpCapture.java @@ -0,0 +1,69 @@ +package org.bench4q.master.entity.httpcapture; + +import java.io.File; +import java.io.IOException; +import java.net.ServerSocket; +import javax.swing.JTextArea; + +public class HttpCapture { + private int localport; + private Config config; + private Test currentTest; + private ProxyServer proxy; + private File resultFile; + private JTextArea textArea; + + public HttpCapture(String filepath, int localport, String generator, JTextArea textArea) + { + this.localport = localport; + this.resultFile = new File(filepath + "\\Script.xml"); + this.textArea = textArea; + this.config = Config.getConfig(); + try { + this.config.completeInit(); + this.proxy = new ProxyServer(this.localport); + } catch (Exception e) { + e.printStackTrace(); + } + this.currentTest = new Test(this.proxy, + new JTextAreaTestScriptAdapter(this.textArea), + generator); + } + + public void startProxyServer() throws IOException, Utils.UserException { + this.proxy.start(); + } + public void startRecording() throws IOException, Utils.UserException { + this.currentTest.startRecording(); + this.resultFile.createNewFile(); + this.currentTest.setTestFile(this.resultFile); + } + + public void stopRecording() throws IOException, Utils.UserException { + this.currentTest.stopRecording(); + this.currentTest.save(); + } + public void shutProxyServer() throws IOException, Utils.UserException { + if (this.proxy.getServerSocket() != null) { + this.proxy.getServerSocket().close(); + this.proxy.interrupt(); + } + this.currentTest.close(); + } + + public static void main(String[] args) { + try { + HttpCapture m = new HttpCapture("E:\\Temp", 8090, "maxq.generator.IsacCodeGenerator", new JTextArea()); + m.startProxyServer(); + m.startRecording(); + m.stopRecording(); + m.startRecording(); + m.stopRecording(); + m.shutProxyServer(); + } + catch (Exception localException) + { + } + } + +} diff --git a/src/main/java/org/bench4q/master/entity/httpcapture/HttpRequestHeader.java b/src/main/java/org/bench4q/master/entity/httpcapture/HttpRequestHeader.java new file mode 100644 index 00000000..7c82d8eb --- /dev/null +++ b/src/main/java/org/bench4q/master/entity/httpcapture/HttpRequestHeader.java @@ -0,0 +1,193 @@ +package org.bench4q.master.entity.httpcapture; + +import java.io.IOException; +import java.io.InputStream; +import java.util.StringTokenizer; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +public class HttpRequestHeader { + private static final Log log = LogFactory.getLog(HttpRequestHeader.class); + + public String method = new String(); + + public String url = new String(); + + public String version = new String(); + + public String userAgent = new String(); + + public String referer = new String(); + + public String ifModifiedSince = new String(); + + public String accept = new String(); + + public String authorization = new String(); + + public String contentType = new String(); + + public int contentLength = -1; + + public int oldContentLength = -1; + + public String unrecognized = new String(); + + public boolean pragmaNoCache = false; + static final String CR = "\r\n"; + private InputStream input; + + public HttpRequestHeader(InputStream in) + throws IOException + { + this.input = in; + + StringTokenizer tz = new StringTokenizer(readLine()); + + this.method = getToken(tz).toUpperCase(); + this.url = getToken(tz); + this.version = getToken(tz); + while (true) + { + String line = readLine(); + log.trace(line); + tz = new StringTokenizer(line); + String Token = getToken(tz); + + if (Token.length() == 0) { + break; + } + if (Token.equalsIgnoreCase("USER-AGENT:")) + { + this.userAgent = getRemainder(tz); + } else if (Token.equalsIgnoreCase("ACCEPT:")) + { + this.accept = (this.accept + " " + getRemainder(tz)); + } + else if (Token.equalsIgnoreCase("REFERER:")) + { + this.referer = getRemainder(tz); + } + else if (Token.equalsIgnoreCase("PRAGMA:")) + { + Token = getToken(tz); + + if (Token.equalsIgnoreCase("NO-CACHE")) + this.pragmaNoCache = true; + else + this.unrecognized = + (this.unrecognized + "Pragma:" + Token + " " + + getRemainder(tz) + "\n"); + } else if (Token.equalsIgnoreCase("AUTHORIZATION:")) + { + this.authorization = getRemainder(tz); + } + else if (Token.equalsIgnoreCase("IF-MODIFIED-SINCE:")) + { + String str = getRemainder(tz); + int index = str.indexOf(";"); + if (index == -1) { + this.ifModifiedSince = str; + } else { + this.ifModifiedSince = str.substring(0, index); + + index = str.indexOf("="); + if (index != -1) { + str = str.substring(index + 1); + this.oldContentLength = Integer.parseInt(str); + } + } + } else if (Token.equalsIgnoreCase("CONTENT-LENGTH:")) { + Token = getToken(tz); + this.contentLength = Integer.parseInt(Token); + } else if (Token.equalsIgnoreCase("CONTENT-TYPE:")) { + this.contentType = getRemainder(tz); + } else { + this.unrecognized = (this.unrecognized + Token + " " + getRemainder(tz) + "\r\n"); + } + } + } + + String readLine() + throws IOException + { + StringBuffer sb = new StringBuffer(); + int c; + while ((c = this.input.read()) != 10) + { + if (c == -1) + throw new IOException("unterminated line in request header"); + sb.append((char)c); + } + return sb.toString(); + } + + public String toString(boolean sendUnknowen) + { + if (this.method.length() == 0) { + this.method = "GET"; + } + String Request = this.method + " " + this.url + " HTTP/1.0" + "\r\n"; + + if (this.userAgent.length() > 0) { + Request = Request + "User-Agent:" + this.userAgent + "\r\n"; + } + if (this.referer.length() > 0) { + Request = Request + "Referer:" + this.referer + "\r\n"; + } + if (this.pragmaNoCache) { + Request = Request + "Pragma: no-cache\r\n"; + } + if (this.ifModifiedSince.length() > 0) { + Request = Request + "If-Modified-Since: " + this.ifModifiedSince + "\r\n"; + } + + if (this.accept.length() > 0) + Request = Request + "Accept: " + this.accept + "\r\n"; + else { + Request = Request + "Accept: */* \r\n"; + } + if (this.contentType.length() > 0) { + Request = Request + "Content-Type: " + this.contentType + "\r\n"; + } + if (this.contentLength > 0) { + Request = Request + "Content-Length: " + this.contentLength + "\r\n"; + } + + if (this.authorization.length() != 0) { + Request = Request + "Authorization: " + this.authorization + "\r\n"; + } + if ((sendUnknowen) && + (this.unrecognized.length() != 0)) { + Request = Request + this.unrecognized; + } + + Request = Request + "\r\n"; + + return Request; + } + + public String toString() + { + return toString(true); + } + + String getToken(StringTokenizer tk) + { + String str = ""; + if (tk.hasMoreTokens()) + str = tk.nextToken(); + return str; + } + + String getRemainder(StringTokenizer tk) + { + String str = ""; + if (tk.hasMoreTokens()) + str = tk.nextToken(); + while (tk.hasMoreTokens()) { + str = str + " " + tk.nextToken(); + } + return str; + } +} diff --git a/src/main/java/org/bench4q/master/entity/httpcapture/IScriptAdapter.java b/src/main/java/org/bench4q/master/entity/httpcapture/IScriptAdapter.java new file mode 100644 index 00000000..e9ef49fa --- /dev/null +++ b/src/main/java/org/bench4q/master/entity/httpcapture/IScriptAdapter.java @@ -0,0 +1,15 @@ +package org.bench4q.master.entity.httpcapture; + +public interface IScriptAdapter { + + public abstract void append(String paramString); + + public abstract void insert(String paramString, int paramInt); + + public abstract String getText(); + + public abstract void setText(String paramString); + + public abstract void replace(String paramString, int paramInt1, int paramInt2) + throws IllegalArgumentException; +} diff --git a/src/main/java/org/bench4q/master/entity/httpcapture/JTextAreaTestScriptAdapter.java b/src/main/java/org/bench4q/master/entity/httpcapture/JTextAreaTestScriptAdapter.java new file mode 100644 index 00000000..dc55b61a --- /dev/null +++ b/src/main/java/org/bench4q/master/entity/httpcapture/JTextAreaTestScriptAdapter.java @@ -0,0 +1,40 @@ +package org.bench4q.master.entity.httpcapture; + +import javax.swing.JTextArea; + +public class JTextAreaTestScriptAdapter + implements IScriptAdapter +{ + private JTextArea jTextArea; + + public JTextAreaTestScriptAdapter(JTextArea jTextArea) + { + this.jTextArea = jTextArea; + jTextArea.setText(""); + } + + public void append(String text) + { + this.jTextArea.append(text); + } + + public void insert(String text, int position) + { + this.jTextArea.insert(text, position); + } + + public String getText() + { + return this.jTextArea.getText(); + } + + public void setText(String text) + { + this.jTextArea.setText(text); + } + + public void replace(String string, int start, int end) throws IllegalArgumentException + { + this.jTextArea.replaceRange(string, start, end); + } +} diff --git a/src/main/java/org/bench4q/master/entity/httpcapture/Param.java b/src/main/java/org/bench4q/master/entity/httpcapture/Param.java new file mode 100644 index 00000000..ab994262 --- /dev/null +++ b/src/main/java/org/bench4q/master/entity/httpcapture/Param.java @@ -0,0 +1,6 @@ +package org.bench4q.master.entity.httpcapture; + +public class Param { + public String name; + public String value; +} diff --git a/src/main/java/org/bench4q/master/entity/httpcapture/ProxyServer.java b/src/main/java/org/bench4q/master/entity/httpcapture/ProxyServer.java new file mode 100644 index 00000000..7413b804 --- /dev/null +++ b/src/main/java/org/bench4q/master/entity/httpcapture/ProxyServer.java @@ -0,0 +1,89 @@ +package org.bench4q.master.entity.httpcapture; + +import java.io.IOException; +import java.net.ServerSocket; +import java.net.Socket; +import java.util.Enumeration; +import java.util.Vector; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +public class ProxyServer extends Thread { + private Vector listeners; + private ServerSocket srvSock; + private int count; + private static final Log log = LogFactory.getLog(ProxyServer.class); + + public ProxyServer() throws IOException + { + this(0); + } + + public ProxyServer(int port) + throws IOException + { + this.srvSock = new ServerSocket(port); + this.listeners = new Vector(); + } + + public void addObserver(Observer proxy) + { + this.listeners.addElement(proxy); + } + + public void removeObserver(Observer proxy) + { + this.listeners.removeElement(proxy); + } + + public void processRequest(HttpRequestHeader header, byte[] requestBody) throws Exception + { + for (Enumeration e = this.listeners.elements(); e.hasMoreElements(); ) { + Observer pl = (Observer)e.nextElement(); + pl.processRequest(header, requestBody); + } + } + + public void processResponse(HttpRequestHeader header, byte[] response) throws Exception + { + for (Enumeration e = this.listeners.elements(); e.hasMoreElements(); ) { + Observer pl = (Observer)e.nextElement(); + pl.processResponse(header, response); + } + } + + public void run() + { + while (!Thread.interrupted()) + if (!this.srvSock.isClosed()) + try { + Socket s = this.srvSock.accept(); + RequestHandler handler = new RequestHandler(this, s); + log.trace("New connection. Creating new RequestHandler thread."); + Thread t = new Thread(handler, "MaxQRequestHandler #" + this.count); + t.start(); + this.count += 1; + } + catch (Throwable localThrowable) + { + } + } + + int getLocalPort() + { + return this.srvSock.getLocalPort(); + } + + public ServerSocket getServerSocket() { + return this.srvSock; + } + + public static abstract interface Observer + { + public abstract void processRequest(HttpRequestHeader paramHttpRequestHeader, byte[] paramArrayOfByte) + throws Exception; + + public abstract void processResponse(HttpRequestHeader paramHttpRequestHeader, byte[] paramArrayOfByte) + throws Exception; + } +} diff --git a/src/main/java/org/bench4q/master/entity/httpcapture/RequestHandler.java b/src/main/java/org/bench4q/master/entity/httpcapture/RequestHandler.java new file mode 100644 index 00000000..8d6aad14 --- /dev/null +++ b/src/main/java/org/bench4q/master/entity/httpcapture/RequestHandler.java @@ -0,0 +1,214 @@ +package org.bench4q.master.entity.httpcapture; + +import java.io.BufferedInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.ConnectException; +import java.net.InetAddress; +import java.net.MalformedURLException; +import java.net.Socket; +import java.net.SocketException; +import java.net.URL; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + + +public class RequestHandler implements Runnable{ + + private static final Log log = LogFactory.getLog(RequestHandler.class); + + private Config config = Config.getConfig(); + private InputStream clientIn; + private InputStream serverIn; + private OutputStream clientOut; + private OutputStream serverOut; + private HttpRequestHeader header; + private ProxyServer proxyServer; + private Socket clientSocket; + private Socket serverSocket; + private ByteArrayOutputStream buffer; + private static Object mutex = new Object(); + + RequestHandler(ProxyServer proxyServer, Socket s) + { + assert (s != null); + this.clientSocket = s; + this.buffer = new ByteArrayOutputStream(); + this.proxyServer = proxyServer; + } + + private void initClientServerConnections(Socket s) + throws Throwable + { + this.clientIn = new BufferedInputStream(s.getInputStream()); + this.clientOut = s.getOutputStream(); + try { + this.header = new HttpRequestHeader(this.clientIn); + } + catch (IOException e) + { + log.info("truncated request from browser: " + e.getMessage()); + throw new Utils.SilentException(); + } + if (!this.header.url.startsWith("http")) + throw new Utils.UserException("MaxQ only supports the HTTP protocol."); + URL url = new URL(this.header.url); + + Config.ProxySettings proxy = this.config.getProxySettings(); + int port; + String host; + if (proxy != null) { + host = proxy.host; + port = proxy.port; + } else { + host = url.getHost(); + port = url.getPort(); + } + + if (port < 1) + port = 80; + try { + this.serverSocket = new Socket(InetAddress.getByName(host), port); + } catch (ConnectException e) { + String msg = "Cannot connect to "; + if (proxy != null) + msg = msg + "proxy server "; + msg = msg + host; + if (port != 80) + msg = msg + " on port " + Integer.toString(port); + throw new Utils.UserException(msg + "."); + } + try { + this.serverIn = this.serverSocket.getInputStream(); + this.serverOut = this.serverSocket.getOutputStream(); + } catch (Throwable e) { + this.serverSocket.close(); + this.serverSocket = null; + throw e; + } + } + + private String stripProxyInfoFromRequestHeader() + throws MalformedURLException + { + String res = ""; + String origUrl = this.header.url; + URL url = new URL(origUrl); + this.header.url = url.getFile(); + res = this.header.toString(); + this.header.url = origUrl; + return res; + } + + public void run() + { + try + { + try + { + int rs = this.clientSocket.getReceiveBufferSize(); + int ss = this.clientSocket.getSendBufferSize(); + int BUF_SIZE = rs < ss ? ss : rs; + + byte[] buf = new byte[BUF_SIZE]; + + initClientServerConnections(this.clientSocket); + String headerStr; + if (this.config.getProxySettings() == null) + headerStr = stripProxyInfoFromRequestHeader(); + else + headerStr = this.header.toString(); + log.trace("read request header"); + + byte[] bytes = headerStr.getBytes(); + this.serverOut.write(bytes, 0, bytes.length); + + log.trace("wrote request header"); + byte[] requestBody; + if (this.header.contentLength > 0) { + this.buffer.reset(); + int len = 0; + int num = 0; + while (num < this.header.contentLength) { + try { + len = this.clientIn.read(buf, 0, buf.length); + } + catch (SocketException e) + { + log.info("truncated request from browser: " + + e.getMessage()); + throw new Utils.SilentException(); + } + if (len == 0) + break; + log.trace("read " + Integer.toString(len) + " bytes"); + this.serverOut.write(buf, 0, len); + this.buffer.write(buf, 0, len); + log.trace("wrote " + Integer.toString(len) + " bytes"); + num += len; + } + requestBody = this.buffer.toByteArray(); + log.trace("transferred rest of request body"); + } else { + requestBody = new byte[0]; + log.trace("no request body"); + } + + this.clientSocket.shutdownInput(); + + this.serverSocket.shutdownOutput(); + + synchronized (mutex) + { + this.proxyServer.processRequest(this.header, requestBody); + log.trace("processed request"); + + this.buffer.reset(); + int len; + while ((len = this.serverIn.read(buf, 0, buf.length)) > 0) + { + log.trace("read " + Integer.toString(len)); + try { + this.clientOut.write(buf, 0, len); + } + catch (SocketException e) + { + log.info("browser stopped listening: " + + e.getMessage()); + throw new Utils.SilentException(); + } + this.buffer.write(buf, 0, len); + } + log.trace("transferred response"); + + this.proxyServer.processResponse(this.header, this.buffer.toByteArray()); + log.trace("processed response"); + } + + } + finally + { + if (this.serverSocket != null) { + this.serverSocket.close(); + log.trace("closed server socket"); + } + + this.clientSocket.close(); + log.trace("closed client socket"); + } + if (this.serverSocket != null) { + this.serverSocket.close(); + log.trace("closed server socket"); + } + + this.clientSocket.close(); + log.trace("closed client socket"); + } + catch (Throwable localThrowable) + { + } + } + +} diff --git a/src/main/java/org/bench4q/master/entity/httpcapture/Test.java b/src/main/java/org/bench4q/master/entity/httpcapture/Test.java new file mode 100644 index 00000000..0b422d50 --- /dev/null +++ b/src/main/java/org/bench4q/master/entity/httpcapture/Test.java @@ -0,0 +1,148 @@ +package org.bench4q.master.entity.httpcapture; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.io.FileWriter; +import java.io.IOException; +import java.io.PrintWriter; +import org.bench4q.master.entity.httpcapture.generator.GeneratorFactory; +import org.bench4q.master.entity.httpcapture.generator.IScriptGenerator; + + +public class Test { + private IScriptGenerator generator; + private IScriptAdapter scriptAdapter; + private boolean isRecording; + private File testFile; + private String testName; + ProxyServer proxyServer; + + public Test(ProxyServer proxy, IScriptAdapter adapter, String generatorClass) + { + this.proxyServer = proxy; + this.scriptAdapter = adapter; + adapter.setText(""); + this.generator = GeneratorFactory.newGenerator(generatorClass, adapter); + this.generator.doNew(); + } + + public Test(ProxyServer proxy, IScriptAdapter adapter, File file) + throws IOException, Utils.UserException + { + this.proxyServer = proxy; + this.scriptAdapter = adapter; + this.testFile = file; + + StringBuffer buffer = new StringBuffer(); + BufferedReader r = new BufferedReader(new FileReader(this.testFile)); + String line = r.readLine(); + while (line != null) { + buffer.append(line); + buffer.append(IScriptGenerator.EOL); + line = r.readLine(); + } + r.close(); + String script = buffer.toString(); + + String generatorClass = null; + String[] classes = GeneratorFactory.getClasses(); + + for (int i = 0; i < classes.length; i++) { + if (script.indexOf(classes[i]) != -1) { + generatorClass = classes[i]; + break; + } + } + if (generatorClass == null) { + throw new Utils.UserException("Your file does not appear to have been generated by MaxQ.\n\n(MaxQ expects to find the class name of the generator somewhere in the script.\nPerhaps you have mistakenly deleted it?)"); + } + + adapter.setText(script); + this.generator = GeneratorFactory.newGenerator(generatorClass, adapter); + this.generator.doLoad(); + this.testName = this.generator.parseTestName(); + } + + public String getTestName() + { + return this.testName; + } + + public File getTestFile() + { + return this.testFile; + } + + public void setTestFile(File file) + { + this.testFile = file; + } + + public String getCurrentPath() + { + if (this.testFile == null) { + return System.getProperty("user.dir"); + } + return stripFileName(this.testFile.getAbsolutePath()); + } + + public String[] getvalidTestFileExtensions() + { + return this.generator.getValidFileExtensions(); + } + + public boolean isRecording() + { + return this.isRecording; + } + + public void stopRecording() + { + this.proxyServer.removeObserver(this.generator); + assert (this.isRecording); + this.generator.doStopRecording(); + this.isRecording = false; + } + + public void startRecording() + { + assert (!this.isRecording); + this.proxyServer.addObserver(this.generator); + this.isRecording = true; + this.generator.doStartRecording(); + } + + public void save() throws IOException + { + this.generator.doSave(stripFileName(this.testFile.getAbsolutePath()), this.testFile.getName()); + + PrintWriter writer = new PrintWriter(new FileWriter(this.testFile)); + String str = this.scriptAdapter.getText(); + str = Utils.replace(str, "\r\n", "\n"); + str = Utils.replace(str, "\n", IScriptGenerator.EOL); + writer.println(str); + writer.close(); + } + + private String stripFileName(String absolutePath) + { + int index = absolutePath.lastIndexOf(System.getProperty("file.separator")); + if (index == -1) { + return absolutePath; + } + return absolutePath.substring(0, index); + } + + public void close() + { + if (this.isRecording) + this.proxyServer.removeObserver(this.generator); + this.generator.close(); + } + + public IScriptGenerator getGenerator() + { + return this.generator; + } +} diff --git a/src/main/java/org/bench4q/master/entity/httpcapture/Utils.java b/src/main/java/org/bench4q/master/entity/httpcapture/Utils.java new file mode 100644 index 00000000..4b37230b --- /dev/null +++ b/src/main/java/org/bench4q/master/entity/httpcapture/Utils.java @@ -0,0 +1,122 @@ +package org.bench4q.master.entity.httpcapture; + +import java.io.File; +import java.io.FileWriter; +import java.io.PrintWriter; +import java.util.ArrayList; +import java.util.List; +import java.util.StringTokenizer; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.bench4q.master.entity.httpcapture.Param; + +public class Utils { + public static final String SPACE = " "; + private static final Log log = LogFactory.getLog(Utils.class); + + public static File saveHTML(String htmlFileName, String str, String dir_str) + { + if (str == null) { + log.error("Argument is null: EditorPane.saveHTML()"); + return null; + } + File dir, htmlFile; + if (dir_str == null){ + dir = new File("Tempfiles"); + } + else { + dir = new File(dir_str); + } + dir.mkdir(); + try + { + htmlFile = new File(dir, htmlFileName); + if (htmlFile.exists()) { + htmlFile.delete(); + log.warn("deleting duplicated file: " + htmlFileName); + } + htmlFile.createNewFile(); + PrintWriter writer = new PrintWriter(new FileWriter(htmlFile)); + writer.print(str); + writer.close(); + } catch (Exception e) { + e.printStackTrace(); + return null; + } + + return htmlFile; + } + + public static String[] splitString(String str, String delim) + { + StringTokenizer st = new StringTokenizer(str, delim); + String[] res = new String[st.countTokens()]; + int i = 0; + while (st.hasMoreTokens()) { + res[i] = st.nextToken(); + i++; + } + return res; + } + + public static String replace(String str, String search, String replace) + { + int pos = str.indexOf(search); + if (pos == -1) return str; + StringBuffer buff = new StringBuffer(str.length() + 32); + int start = 0; + while ((pos != -1) && (start < str.length())) { + buff.append(str.substring(start, pos)); + buff.append(replace); + + start = pos + search.length(); + if (start < str.length()) pos = str.indexOf(search, start); + } + if (start < str.length()) buff.append(str.substring(start)); + + return buff.toString(); + } + + public static List getParams(String query) + { + List paramList = new ArrayList(); + if (query != null) { + query = query.trim(); + log.debug(" parsing: " + query); + String[] items = splitString(query, "&"); + for (int i = 0; i < items.length; i++) { + int pos = items[i].indexOf("="); + if (pos != -1) { + Param p = new Param(); + paramList.add(p); + p.name = items[i].substring(0, pos); + if (pos < items[i].length() - 1) + p.value = items[i].substring(pos + 1); + else + p.value = ""; + } + } + } + return paramList; + } + + public static class SilentException extends Exception + { + private static final long serialVersionUID = 3172942039967787899L; + + public SilentException() + { + super(); + } + } + + public static class UserException extends Exception + { + private static final long serialVersionUID = -7337004995296463936L; + + public UserException(String s) + { + super(); + } + } +} diff --git a/src/main/resources/hibernate.cfg.xml b/src/main/resources/hibernate.cfg.xml index 2cdad0b1..64ae3039 100644 --- a/src/main/resources/hibernate.cfg.xml +++ b/src/main/resources/hibernate.cfg.xml @@ -16,12 +16,11 @@ update - - - - - - - + + + + + + \ No newline at end of file From 848bad0a22564de2dd23c318aecf6367704a472d Mon Sep 17 00:00:00 2001 From: coderfengyun Date: Tue, 9 Jul 2013 19:29:21 +0800 Subject: [PATCH 047/684] =?UTF-8?q?HttpCapture=E5=AE=8C=E7=BB=93?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pom.xml | 6 + .../master/api/RecordPortController.java | 15 +- .../master/api/RecordScriptController.java | 4 +- .../org/bench4q/master/entity/Constant.java | 2 +- .../bench4q/master/entity/ScriptCapturer.java | 4 +- .../master/entity/httpcapture/Action.java | 209 +++++++ .../master/entity/httpcapture/DBUtil.java | 113 ++++ .../entity/httpcapture/HeaderValue.java | 78 +++ .../entity/httpcapture/HttpCapture.java | 1 - .../entity/httpcapture/HttpTestCase.java | 333 ++++++++++ .../master/entity/httpcapture/Validator.java | 38 ++ .../generator/AbstractCodeGenerator.java | 570 ++++++++++++++++++ .../generator/GeneratorFactory.java | 3 +- .../httpcapture/generator/HttpStatusMap.java | 63 ++ .../generator/HttpUnitTemplateLogic.java | 245 ++++++++ .../httpcapture/generator/Interchange.java | 332 ++++++++++ .../generator/IsacCodeGenerator.java | 298 +++++++++ .../httpcapture/generator/TemplateLogic.java | 54 ++ 18 files changed, 2355 insertions(+), 13 deletions(-) create mode 100644 src/main/java/org/bench4q/master/entity/httpcapture/Action.java create mode 100644 src/main/java/org/bench4q/master/entity/httpcapture/DBUtil.java create mode 100644 src/main/java/org/bench4q/master/entity/httpcapture/HeaderValue.java create mode 100644 src/main/java/org/bench4q/master/entity/httpcapture/HttpTestCase.java create mode 100644 src/main/java/org/bench4q/master/entity/httpcapture/Validator.java create mode 100644 src/main/java/org/bench4q/master/entity/httpcapture/generator/AbstractCodeGenerator.java create mode 100644 src/main/java/org/bench4q/master/entity/httpcapture/generator/HttpStatusMap.java create mode 100644 src/main/java/org/bench4q/master/entity/httpcapture/generator/HttpUnitTemplateLogic.java create mode 100644 src/main/java/org/bench4q/master/entity/httpcapture/generator/Interchange.java create mode 100644 src/main/java/org/bench4q/master/entity/httpcapture/generator/IsacCodeGenerator.java create mode 100644 src/main/java/org/bench4q/master/entity/httpcapture/generator/TemplateLogic.java diff --git a/pom.xml b/pom.xml index f965b883..915a0eec 100644 --- a/pom.xml +++ b/pom.xml @@ -78,6 +78,12 @@ jython 2.7-b1 + + commons-httpclient + commons-httpclient + 3.1 + + bench4q-master diff --git a/src/main/java/org/bench4q/master/api/RecordPortController.java b/src/main/java/org/bench4q/master/api/RecordPortController.java index 965975bf..87b45ecb 100644 --- a/src/main/java/org/bench4q/master/api/RecordPortController.java +++ b/src/main/java/org/bench4q/master/api/RecordPortController.java @@ -1,31 +1,36 @@ package org.bench4q.master.api; import org.bench4q.master.api.model.OrganizeRecordPortResponseModel; -import org.bench4q.master.entity.AgentInfo; import org.bench4q.master.entity.Constant; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.ResponseBody; @Controller -@RequestMapping("/RecordScript") +@RequestMapping("/RecordPort") public class RecordPortController extends BaseController { @RequestMapping(value = "/AddPortToPortPool", method = RequestMethod.GET) + @ResponseBody public OrganizeRecordPortResponseModel AddPortToPortPool(@RequestParam int port, @RequestParam String accessToken) { OrganizeRecordPortResponseModel organizeRecordPortResponseModel = new OrganizeRecordPortResponseModel(); - if(!this.checkScope(Constant.SUPER_AUTHENTICATION)) + /*if(!this.checkScope(Constant.SUPER_AUTHENTICATION)) { organizeRecordPortResponseModel.setSuccess(false); organizeRecordPortResponseModel.setFailCauseString("you don't hava the power to add port to pool!"); return organizeRecordPortResponseModel; - } + }*/ if (Constant.ScriptPortPool.contains(port)) { - + organizeRecordPortResponseModel.setSuccess(false); + organizeRecordPortResponseModel.setFailCauseString("The pot you add already exists in the port popl!"); + return organizeRecordPortResponseModel; } + Constant.ScriptPortPool.add(port); + organizeRecordPortResponseModel.setSuccess(true); organizeRecordPortResponseModel.setFailCauseString("add port " + port +" to ScriptPortPool sucessfully!"); return organizeRecordPortResponseModel; diff --git a/src/main/java/org/bench4q/master/api/RecordScriptController.java b/src/main/java/org/bench4q/master/api/RecordScriptController.java index b0551d94..cd7b9088 100644 --- a/src/main/java/org/bench4q/master/api/RecordScriptController.java +++ b/src/main/java/org/bench4q/master/api/RecordScriptController.java @@ -61,14 +61,14 @@ public class RecordScriptController extends BaseController { //String pathString = this.getClass().getResource("/").getPath(); //scriptCapturer = new ScriptCapturer(portForRecord, "C:\\Script\\", //this.getPrincipal().getUserName()); - scriptCapturer = new ScriptCapturer(portForRecord, "C:\\Script\\", + scriptCapturer = new ScriptCapturer(this.getPortForRecord(), "C:\\Script\\", "Chen"); scriptCapturer.startCurrentRecord(); System.out.println("server started and begin to wait!"); return returnResponseModel(true, "you should set you agent server now, please use IP address: " + scriptCapturer.getIpHttpCaptureServerAdress() +" and port number : " - + scriptCapturer.getIpHttpCaptureServerAdress() + "!"); + + scriptCapturer.getPortForRecord() + "!"); } @RequestMapping(value = "/stopScriptRecordServer", method = RequestMethod.GET) diff --git a/src/main/java/org/bench4q/master/entity/Constant.java b/src/main/java/org/bench4q/master/entity/Constant.java index bd9b0455..32a3d760 100644 --- a/src/main/java/org/bench4q/master/entity/Constant.java +++ b/src/main/java/org/bench4q/master/entity/Constant.java @@ -12,6 +12,6 @@ public class Constant { public static Integer getPortLock = 0; public static Vector AgentPool = new Vector(); public static Vector ScriptPortPool = new Vector(); - public static String HTTPCAPTUREGENERATOR = "maxq.generator.IsacCodeGenerator"; + public static String HTTPCAPTUREGENERATOR = "org.bench4q.master.entity.httpcapture.generator.IsacCodeGenerator"; } diff --git a/src/main/java/org/bench4q/master/entity/ScriptCapturer.java b/src/main/java/org/bench4q/master/entity/ScriptCapturer.java index cfc00765..66192793 100644 --- a/src/main/java/org/bench4q/master/entity/ScriptCapturer.java +++ b/src/main/java/org/bench4q/master/entity/ScriptCapturer.java @@ -21,9 +21,9 @@ public class ScriptCapturer { public ScriptCapturer(int portForRecord, String scriptParentPath, String userName) { this.setPortForRecord(portForRecord); - this.setScriptPath(scriptParentPath + userName + "\\Script_test.xml"); + this.setScriptPath(scriptParentPath + userName); //TODO get the machine's ipAdress - this.setIpHttpCaptureServerAdress(""); + this.setIpHttpCaptureServerAdress(Constant.TESTIPADRESS); } public boolean isRecording() { diff --git a/src/main/java/org/bench4q/master/entity/httpcapture/Action.java b/src/main/java/org/bench4q/master/entity/httpcapture/Action.java new file mode 100644 index 00000000..8efd9e65 --- /dev/null +++ b/src/main/java/org/bench4q/master/entity/httpcapture/Action.java @@ -0,0 +1,209 @@ +package org.bench4q.master.entity.httpcapture; + +import java.util.Vector; + +public class Action { + private static String LINE_SEP = System.getProperty("line.separator"); + private String url; + private String method; + private String expected_result; + private int delayTime; + private int expected_size; + private int timeout; + private Vector headers; + private Vector queryStringParams; + private Vector bodyParams; + private String multiPartData; + + public Action() + { + this.headers = new Vector(); + this.queryStringParams = new Vector(); + this.bodyParams = new Vector(); + this.expected_result = ""; + this.multiPartData = ""; + } + + public void setUrl(String url) + { + this.url = url; + } + + public String getUrl() + { + return this.url; + } + + public void setMethod(String method) + { + this.method = method; + } + + public String getMethod() + { + return this.method; + } + + public void setExpectedResult(String str) + { + this.expected_result = str; + } + + public String getExpectedResult() + { + return this.expected_result; + } + + public void setDelayTime(int seconds) + { + this.delayTime = seconds; + } + + public int getDelayTime() + { + return this.delayTime; + } + + public void setExpectedSize(int bytes) + { + this.expected_size = bytes; + } + + public int getExpectedSize() + { + return this.expected_size; + } + + public void setTimeout(int seconds) + { + this.timeout = seconds; + } + + public int getTimeout() + { + return this.timeout; + } + + public int getHeaderCount() + { + return this.headers.size(); + } + + public HeaderValue[] getHeaders() + { + HeaderValue[] list = new HeaderValue[this.headers.size()]; + this.headers.copyInto(list); + return list; + } + + public void addHeader(HeaderValue p) + { + this.headers.addElement(p); + } + + public void removeHeader(HeaderValue p) + { + this.headers.removeElement(p); + } + + public int getParamsCount() + { + return getParams().length; + } + + public int getQueryStringParamCount() + { + return this.queryStringParams.size(); + } + + public int getBodyParamCount() + { + return this.bodyParams.size(); + } + + public Param[] getQueryStringParams() + { + Param[] list = new Param[this.queryStringParams.size()]; + this.queryStringParams.copyInto(list); + return list; + } + + public Param[] getBodyParams() + { + Param[] list = new Param[this.bodyParams.size()]; + this.bodyParams.copyInto(list); + return list; + } + + public Param[] getParams() + { + @SuppressWarnings("unchecked") + Vector v = (Vector)this.queryStringParams.clone(); + v.addAll(this.bodyParams); + Param[] list = new Param[v.size()]; + v.copyInto(list); + return list; + } + + public void addQueryStringParam(Param p) + { + this.queryStringParams.addElement(p); + } + + public void addBodyParam(Param p) + { + this.bodyParams.addElement(p); + } + + public void removeQueryStringParam(Param p) + { + this.queryStringParams.removeElement(p); + } + + public void removeBodyParam(Param p) + { + this.bodyParams.removeElement(p); + } + + public String toXML() + { + StringBuffer str = new StringBuffer(1024); + str.append(" "); + str.append(""); + Param[] params = getQueryStringParams(); + for (int i = 0; i < params.length; ++i) { + str.append(LINE_SEP).append(" "); + str.append(""); + } + params = getBodyParams(); + for (int i = 0; i < params.length; ++i) { + str.append(LINE_SEP).append(" "); + str.append(""); + } + str.append(LINE_SEP); + str.append(" "); + return str.toString(); + } + + public void setMultiPartData(String multiPartData) + { + this.multiPartData = multiPartData; + } + + public String getMultiPartData() + { + return this.multiPartData; + } +} diff --git a/src/main/java/org/bench4q/master/entity/httpcapture/DBUtil.java b/src/main/java/org/bench4q/master/entity/httpcapture/DBUtil.java new file mode 100644 index 00000000..dc620684 --- /dev/null +++ b/src/main/java/org/bench4q/master/entity/httpcapture/DBUtil.java @@ -0,0 +1,113 @@ +package org.bench4q.master.entity.httpcapture; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.ResultSet; +import java.sql.ResultSetMetaData; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Properties; + +public class DBUtil { + private Connection conn; + + public DBUtil(String driver, String url, String username, String pw) + throws Exception + { + Class.forName(driver); + this.conn = DriverManager.getConnection(url, username, pw); + } + + public DBUtil(String driver, String url, Properties props) + throws Exception + { + Class.forName(driver); + this.conn = DriverManager.getConnection(url, props); + } + + public Connection getConnection() + { + return this.conn; + } + + public int execute(String sql) + throws Exception + { + Statement stmt = this.conn.createStatement(); + int rows = stmt.executeUpdate(sql); + stmt.close(); + + return rows; + } + + public ArrayList> loadRows(String sql) + throws Exception + { + Statement stmt = this.conn.createStatement(); + ResultSet rs = stmt.executeQuery(sql); + ArrayList> list = new ArrayList>(); + ResultSetMetaData meta = rs.getMetaData(); + int cols = meta.getColumnCount(); + while (rs.next()) { + HashMap map = rsToMap(rs, meta, cols); + list.add(map); + } + rs.close(); + stmt.close(); + + return list; + } + + public HashMap loadRow(String sql) + throws Exception + { + Statement stmt = this.conn.createStatement(); + ResultSet rs = stmt.executeQuery(sql); + HashMap map = null; + + ResultSetMetaData meta = rs.getMetaData(); + int cols = meta.getColumnCount(); + if (rs.next()) + map = rsToMap(rs, meta, cols); + + rs.close(); + stmt.close(); + + return map; + } + + public String loadVal(String sql) + throws Exception + { + Statement stmt = this.conn.createStatement(); + ResultSet rs = stmt.executeQuery(sql); + String str = null; + + if (rs.next()) + str = rs.getString(1); + + rs.close(); + stmt.close(); + + return str; + } + + public void close() + throws Exception + { + this.conn.close(); + } + + private HashMap rsToMap(ResultSet rs, ResultSetMetaData meta, int cols) + throws Exception + { + HashMap map = new HashMap(); + for (int i = 0; i < cols; ++i) { + int c = i + 1; + map.put(meta.getColumnName(c), rs.getString(c)); + } + + return map; + } +} diff --git a/src/main/java/org/bench4q/master/entity/httpcapture/HeaderValue.java b/src/main/java/org/bench4q/master/entity/httpcapture/HeaderValue.java new file mode 100644 index 00000000..4b68aeb6 --- /dev/null +++ b/src/main/java/org/bench4q/master/entity/httpcapture/HeaderValue.java @@ -0,0 +1,78 @@ +package org.bench4q.master.entity.httpcapture; + +public class HeaderValue { + public static final String GENERAL_CACHE_CONTROL = "Cache-Control"; + public static final String GENERAL_CONNECTION = "Connection"; + public static final String GENERAL_DATE = "Date"; + public static final String GENERAL_PRAGMA = "Pragma"; + public static final String GENERAL_TRAILER = "Trailer"; + public static final String GENERAL_TRANSFER_ENC = "Transfer-Encoding"; + public static final String GENERAL_UPGRADE = "Upgrade"; + public static final String GENERAL_VIA = "Via"; + public static final String GENERAL_WARNING = "Warning"; + public static final String REQUEST_ACCEPT = "Accept"; + public static final String REQUEST_ACCEPT_CHARSET = "Accept-Charset"; + public static final String REQUEST_ACCEPT_ENCODING = "Accept-Encoding"; + public static final String REQUEST_ACCEPT_LANGUAGE = "Accept-Language"; + public static final String REQUEST_AUTHORIZATION = "Authorization"; + public static final String REQUEST_EXPECT = "Expect"; + public static final String REQUEST_FROM = "From"; + public static final String REQUEST_HOST = "Host"; + public static final String REQUEST_IF_MATCH = "If-Match"; + public static final String REQUEST_IF_MODIFIED_SINCE = "If-Modified-Since"; + public static final String REQUEST_IF_NONE_MATCH = "If-None-Match"; + public static final String REQUEST_IF_RANGE = "If-Range"; + public static final String REQUEST_IF_UNMODIFIED_SINCE = "If-Unmodified-Since"; + public static final String REQUEST_MAX_FORWARDS = "Max-Forwards"; + public static final String REQUEST_PROXY_AUTHORIZATION = "Proxy-Authorization"; + public static final String REQUEST_RANGE = "Range"; + public static final String REQUEST_REFERER = "Referer"; + public static final String REQUEST_TE = "TE"; + public static final String REQUEST_USER_AGENT = "User-Agent"; + public static final String RESPONSE_AGE = "Age"; + public static final String RESPONSE_ETAG = "ETag"; + public static final String RESPONSE_LOCATION = "Location"; + public static final String RESPONSE_PROXY_AUTHENTICATE = "Proxy-Authenticate"; + public static final String RESPONSE_RETRY_AFTER = "Retry-After"; + public static final String RESPONSE_SERVER = "Server"; + public static final String RESPONSE_VARY = "Vary"; + public static final String RESPONSE_WWW_AUTHENTICATE = "WWW-Authenticate"; + public static final String ENTITY_ALLOW = "Allow"; + public static final String ENTITY_CONTENT_ENCODING = "Content-Encoding"; + public static final String ENTITY_CONTENT_LANGUAGE = "Content-Language"; + public static final String ENTITY_CONTENT_LENGHT = "Content-Length"; + public static final String ENTITY_CONTENT_LOCATION = "Content-Location"; + public static final String ENTITY_CONTENT_MD5 = "Content-MD5"; + public static final String ENTITY_CONTENT_RANGE = "Content-Range"; + public static final String ENTITY_CONTENT_TYPE = "Content-Type"; + public static final String ENTITY_EXPIRES = "Expires"; + public static final String ENTITY_LAST_MODIFIED = "Last-Modified"; + private String header; + private String value; + + public HeaderValue(String header, String value) + { + this.header = header; + this.value = value; + } + + public String getHeader() + { + return this.header; + } + + public void setHeader(String header) + { + this.header = header; + } + + public String getValue() + { + return this.value; + } + + public void setValue(String value) + { + this.value = value; + } +} diff --git a/src/main/java/org/bench4q/master/entity/httpcapture/HttpCapture.java b/src/main/java/org/bench4q/master/entity/httpcapture/HttpCapture.java index a7bf0c6f..58ea9134 100644 --- a/src/main/java/org/bench4q/master/entity/httpcapture/HttpCapture.java +++ b/src/main/java/org/bench4q/master/entity/httpcapture/HttpCapture.java @@ -2,7 +2,6 @@ package org.bench4q.master.entity.httpcapture; import java.io.File; import java.io.IOException; -import java.net.ServerSocket; import javax.swing.JTextArea; public class HttpCapture { diff --git a/src/main/java/org/bench4q/master/entity/httpcapture/HttpTestCase.java b/src/main/java/org/bench4q/master/entity/httpcapture/HttpTestCase.java new file mode 100644 index 00000000..2b6be756 --- /dev/null +++ b/src/main/java/org/bench4q/master/entity/httpcapture/HttpTestCase.java @@ -0,0 +1,333 @@ +package org.bench4q.master.entity.httpcapture; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.util.HashMap; + +import javax.swing.JOptionPane; + +import junit.framework.TestCase; + +import org.apache.commons.httpclient.Header; +import org.apache.commons.httpclient.HostConfiguration; +import org.apache.commons.httpclient.HttpClient; +import org.apache.commons.httpclient.HttpMethod; +import org.apache.commons.httpclient.NameValuePair; +import org.apache.commons.httpclient.URIException; +import org.apache.commons.httpclient.methods.GetMethod; +import org.apache.commons.httpclient.methods.MultipartPostMethod; +import org.apache.commons.httpclient.methods.PostMethod; +import org.apache.commons.httpclient.methods.multipart.StringPart; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.python.core.PyDictionary; +import org.python.core.PyString; +import org.python.core.PyTuple; + +public class HttpTestCase extends TestCase { + private static final Log log = LogFactory.getLog(HttpTestCase.class); + private Config config = Config.getConfig(); + private HashMap connections = new HashMap(); + protected HttpMethod method = null; + protected HttpClient client = new HttpClient(); + protected String data; + private boolean followRedirects = false; + private static String urlSearch; + private static String urlReplace; + private String charset; + + public void setCharset(String cs) + { + this.charset = cs; + } + + public static String getUrlReplace() + { + return urlReplace; + } + + public static String getUrlSearch() + { + return urlSearch; + } + + public static void setURLReplace(String search, String replace) + { + if (urlSearch == null) { + urlSearch = search.trim(); + urlReplace = replace.trim(); + } + log.debug("Ignoring setURLReplace call: search: " + search + " replace: " + replace); + } + + public static String replaceURL(String url) + { + if ((urlSearch == null) || (urlReplace == null)) + return url; + + int pos = url.indexOf(urlSearch); + if (pos == -1) + return url; + + String str = url.substring(0, pos) + urlReplace + + url.substring(pos + urlSearch.length()); + return str; + } + + public HttpTestCase(String name) + { + super(name); + Config.ProxySettings proxy = this.config.getProxySettings(); + if (proxy != null) { + HostConfiguration hc = this.client.getHostConfiguration(); + hc.setProxy(proxy.host, proxy.port); + } + } + + public void Run() + throws Throwable + { + setUp(); + runTest(); + tearDown(); + } + + public HttpMethod getMethod() + { + return this.method; + } + + @SuppressWarnings("deprecation") + private void cleanupMethod() + { + if (this.method != null) { + this.method.releaseConnection(); + this.method.recycle(); + this.method = null; + } + } + + public void get(String url) throws IOException + { + get(url, null); + } + + public void get(String url, Object[] args) throws IOException + { + cleanupMethod(); + + url = replaceURL(url); + this.method = new GetMethod(url); + + if (args != null) { + this.method.setQueryString(paramsToNV(args)); + } + + this.method.setFollowRedirects(this.followRedirects); + this.client.executeMethod(this.method); + } + + public void post(String url) throws IOException + { + post(url, null); + } + + public void post(String url, Object[] args) throws IOException + { + cleanupMethod(); + url = replaceURL(url); + PostMethod post = new PostMethod(url); + + if (this.charset != null) { + post.setRequestHeader("Content-Type", + "application/x-www-form-urlencoded; charset=" + + this.charset); + } + + if (args != null) { + post.setRequestBody(paramsToNV(args)); + } + + this.method = post; + this.method.setFollowRedirects(this.followRedirects); + this.client.executeMethod(this.method); + } + + public void postMultiPart(String url, String data, int contLen) + throws IOException + { + postMultiPart(url, data, contLen, null); + } + + @SuppressWarnings("deprecation") + public void postMultiPart(String url, String data, int contLen, Object[] args) + throws IOException + { + cleanupMethod(); + url = replaceURL(url); + + MultipartPostMethod multipartPost = new MultipartPostMethod(url); + multipartPost.addPart(new StringPart("data", data)); + if (args != null) { + multipartPost.setQueryString(paramsToNV(args)); + } + + this.method = multipartPost; + this.method.setFollowRedirects(this.followRedirects); + this.client.executeMethod(this.method); + } + + public void setConnections(HttpTestCase test) + { + test.connections = this.connections; + } + + public NameValuePair[] paramsToNV(Object[] params) + { + NameValuePair[] res = new NameValuePair[params.length]; + for (int i = 0; i < params.length; ++i) { + Object param = params[i]; + if (param instanceof PyTuple) { + PyTuple pyParam = (PyTuple)param; + res[i] = + new NameValuePair(pyParam.__getitem__(0).toString(), + pyParam.__getitem__(1).toString()); + } + else if (param instanceof NameValuePair) { + res[i] = ((NameValuePair)param); } + } + return res; + } + + public String urlDecode(String s) + { + return staticUrlDecode(s); + } + + public static String staticUrlDecode(String s) + { + ByteArrayOutputStream out = new ByteArrayOutputStream(s.length()); + for (int count = 0; count < s.length(); ++count) + if (s.charAt(count) == '%') { + ++count; + if (count < s.length()) { + int a = Character.digit(s.charAt(count++), 16); + a <<= 4; + int b = Character.digit(s.charAt(count), 16); + + if ((a + b == 39) || (a + b == 132)) out.write(92); + out.write(a + b); + } + else + { + out.write(37); + } + } + else if (s.charAt(count) == '+') { + out.write(32); + } else { + out.write(s.charAt(count)); + } + + + return out.toString(); + } + + protected void responseOK() + throws URIException + { + int status = getResponseCode(); + assertTrue("Invalid HTTP response: " + this.method + " for URI: " + + this.method.getURI(), + (status == 200) || (status == 302) || (status == 304)); + } + + protected boolean responseContainsURI(String uri) + throws URIException + { + return ((this.method != null) && + (this.method.getURI().getPath().indexOf(uri) != -1)); + } + + protected boolean responseContains(String text) + { + try { + if ((this.method == null) || (this.method.getResponseBody() == null)) return false; + + this.data = this.method.getResponseBodyAsString(); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + + return (this.data.indexOf(text) != -1); + } + + protected void printResponse() + { + try { + System.err.println(new String(this.method.getResponseBody())); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } + + public String getResponse() throws IOException + { + return this.method.getResponseBodyAsString(); + } + + public byte[] getResponseAsBytes() throws IOException + { + return this.method.getResponseBody(); + } + + public int getResponseCode() + { + return getMethod().getStatusCode(); + } + + public PyDictionary getResponseHeader() + { + PyDictionary dict = new PyDictionary(); + Header[] headers = this.method.getResponseHeaders(); + + for (int i = 0; i < headers.length; ++i) + dict.__setitem__(new PyString(headers[i].getName()), + new PyString(headers[i].getValue())); + return dict; + } + + public String getScriptArg() + { + return this.config.getScriptArg(); + } + + public boolean userConfirm(String msg) + { + int rc = JOptionPane.showConfirmDialog(null, msg, "HttpCapture", + 2); + return (rc == 0); + } + + public String userInput(String msg) + { + return JOptionPane.showInputDialog(null, msg, "HttpCapture", + 3); + } + + public String getStrutsToken() throws IOException + { + String responseString = new String(this.method.getResponseBodyAsString()); + + String strutsToken = null; + + int tokenIDIndex = responseString.toLowerCase().indexOf("org.apache.struts.taglib.html.TOKEN".toLowerCase()); + int nextValue = responseString.toLowerCase().indexOf("value=\"".toLowerCase(), tokenIDIndex); + + strutsToken = responseString.substring(nextValue + "value=\"".length(), nextValue + "value=\"".length() + 32); + return strutsToken; + } +} diff --git a/src/main/java/org/bench4q/master/entity/httpcapture/Validator.java b/src/main/java/org/bench4q/master/entity/httpcapture/Validator.java new file mode 100644 index 00000000..62bf0d4b --- /dev/null +++ b/src/main/java/org/bench4q/master/entity/httpcapture/Validator.java @@ -0,0 +1,38 @@ +package org.bench4q.master.entity.httpcapture; + +import java.io.IOException; +import java.util.regex.Pattern; + +import org.apache.commons.httpclient.HttpMethod; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +public class Validator { + private static final Log log = LogFactory.getLog(Validator.class); + private static String[] stdRspErrTags = new String[0]; + private static String[] stdRspErrPats = new String[0]; + + public static void validateResponse(HttpTestCase test, HttpMethod httpMethod, String url, Object[] params) throws IOException + { + log.debug("------Validator.validateResponse: method: " + httpMethod.getName() + " url: " + url + " params: " + params); + + String response = httpMethod.getResponseBodyAsString(); + + for (int i = 0; i < stdRspErrTags.length; ++i) { + HttpTestCase.assertEquals("Standard invariant tag found in response: " + + stdRspErrTags[i], -1, response.indexOf(stdRspErrTags[i])); + } + + for (int i = 0; i < stdRspErrPats.length; ++i) { + Pattern re = Pattern.compile(stdRspErrPats[i], 32); + HttpTestCase.assertFalse("Standard invariant pattern found in response: " + + stdRspErrPats[i], re.matcher(response).find()); + } + } + + public static void validateRequest(HttpTestCase test, HttpMethod httpMethod, String method, String url, Object[] params) + { + log.debug("------Validator.validateRequest: method: " + method + + " url: " + url + " params: " + params); + } +} diff --git a/src/main/java/org/bench4q/master/entity/httpcapture/generator/AbstractCodeGenerator.java b/src/main/java/org/bench4q/master/entity/httpcapture/generator/AbstractCodeGenerator.java new file mode 100644 index 00000000..4aa0552b --- /dev/null +++ b/src/main/java/org/bench4q/master/entity/httpcapture/generator/AbstractCodeGenerator.java @@ -0,0 +1,570 @@ +package org.bench4q.master.entity.httpcapture.generator; + +import java.util.Date; +import java.util.HashMap; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; +import java.util.StringTokenizer; +import java.util.Vector; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.bench4q.master.entity.httpcapture.Action; +import org.bench4q.master.entity.httpcapture.Config; +import org.bench4q.master.entity.httpcapture.HeaderValue; +import org.bench4q.master.entity.httpcapture.HttpRequestHeader; +import org.bench4q.master.entity.httpcapture.HttpTestCase; +import org.bench4q.master.entity.httpcapture.IScriptAdapter; +import org.bench4q.master.entity.httpcapture.Param; +import org.bench4q.master.entity.httpcapture.ProxyServer; +import org.bench4q.master.entity.httpcapture.Utils; + +public abstract class AbstractCodeGenerator +implements IScriptGenerator, ProxyServer.Observer, Runnable +{ + private Config config = Config.getConfig(); + private static final Log log; + private static String cpRspTo; + private static boolean cpRspToStdout; + private static boolean cpRspToFile; + private static final String[] MIME_DEFAULTS; + private static HashMap mimeTypes; + protected static final String END_STATEMENT; + protected static String jtidyConfigFile; + protected long assertNumber = 0L; + protected boolean headersExist = false; + private IScriptAdapter scriptAdapter; + private String testName; + private String defaultTestName; + private String testPath; + private boolean ignoreNextResponse; + private Pattern[] namePatterns; + private LinkedList outstandingInserts; + private Thread insertThread; + private String charset; + private final Pattern insertMarkerRE = Pattern.compile("(^[ \\t]*" + EOL + ")?" + ".*\\^\\^\\^ Insert new recording.*", 8); + private long timeElapsedSinceLastestRequest = 0L; + private Date latestRequestDate = new Date(); + private boolean isFirstRequest = true; + static final boolean $assertionsDisabled = !(AbstractCodeGenerator.class.desiredAssertionStatus()); + + public static boolean isCpRspToStdout() + { + return cpRspToStdout; + } + + public static boolean isCpRspToFile() + { + return cpRspToFile; + } + + public AbstractCodeGenerator(IScriptAdapter adapter, String[] nameRegExps) + { + this.scriptAdapter = adapter; + + this.namePatterns = new Pattern[nameRegExps.length]; + for (int i = 0; i < nameRegExps.length; ++i) + this.namePatterns[i] = Pattern.compile(nameRegExps[i], 8); + + this.testName = this.config.getProperty("test.default_testname", "MaxQTest"); + this.defaultTestName = this.testName; + + this.insertThread = new Thread(this); + this.insertThread.start(); + } + + public String getDefaultTestName() + { + return this.defaultTestName; + } + + public void setDefaultTestName(String defaultTestName) + { + this.defaultTestName = defaultTestName; + } + + public IScriptAdapter getScriptAdapter() + { + return this.scriptAdapter; + } + + public String getTestName() + { + return this.testName; + } + + public void setTestName(String testName) + { + this.testName = testName; + } + + public String getTestPath() + { + return this.testPath; + } + + public void setTestPath(String testPath) + { + this.testPath = testPath; + } + + public long getTimeElapsedSinceLastestRequest() + { + return this.timeElapsedSinceLastestRequest; + } + + public boolean isFirstRequest() { + return this.isFirstRequest; + } + + public String parseTestName() + { + Matcher m = this.namePatterns[0].matcher(getScript()); + if (!(m.find())) + throw new IllegalArgumentException("You have fiddled with the formatting of the name of the test embedded in this file. I can no longer understand it."); + + return m.group(1); + } + + public void doSave(String path, String fileName) + { + String name = fileName; + int dotPos = fileName.indexOf("."); + if (dotPos > -1) + name = fileName.substring(0, dotPos); + setTestName(name); + setTestPath(path); + + for (int i = 0; i < this.namePatterns.length; ++i) { + Matcher m = this.namePatterns[i].matcher(getScript()); + if (!(m.find())) + throw new IllegalArgumentException("Regular expression (\"" + this.namePatterns[i].pattern() + "\") provided to constructor cannot match the contents of the script"); + this.scriptAdapter.replace(name, m.start(1), m.end(1)); + } + } + + public void doLoad() + { + setTestName(parseTestName()); + } + + public void close() + { + this.insertThread.interrupt(); + } + + public void processRequest(HttpRequestHeader header, byte[] requestBody) + throws Exception + { + Param[] params; + int i; + String name; + String value; + Date d = new Date(); + this.timeElapsedSinceLastestRequest = (d.getTime() - this.latestRequestDate.getTime()); + this.latestRequestDate = d; + + if ((header.method.toLowerCase().equals("get")) && (urlIgnored(header.url))) { + log.debug("Ignoring GET request: \"" + header.url + "\""); + this.ignoreNextResponse = true; + return; + } + + boolean isMultiPartRequest = header.contentType.startsWith("multipart/form-data"); + boolean isFormRequest = header.contentType.startsWith("application/x-www-form-urlencoded"); + Action action = new Action(); + + String newCharset = null; + Matcher charsetParser = Pattern.compile("charset=([a-z0-9_\\-]+)", 2).matcher(header.contentType); + if (charsetParser.matches()) { + newCharset = charsetParser.group(); + if (!(newCharset.equals(this.charset))) { + doSetCharset(newCharset); + } + else if (this.charset != null) { + doSetCharset(null); + } + + } + + doHeaders(createHeaders(header)); + + String url = header.url; + log.debug(" recording url: " + url); + + String method = header.method.toLowerCase(); + + int pos = url.indexOf("?"); + if ((pos != -1) && (url.length() > pos + 1)) { + setQueryStringParams(action, url.substring(pos + 1)); + action.setUrl(HttpTestCase.replaceURL(url.substring(0, pos))); + } else { + action.setUrl(HttpTestCase.replaceURL(url)); + } + if (requestBody.length > 0) { + if (isMultiPartRequest) + { + setMultiPartData(action, header, requestBody); + } else if (!(isFormRequest)) { + if (newCharset != null) + doSetData(new String(requestBody, newCharset)); + else + doSetData(new String(requestBody)); + + } + else if (newCharset != null) + setBodyParams(action, new String(requestBody, newCharset)); + else { + setBodyParams(action, new String(requestBody)); + } + + } + + if (action.getParamsCount() > 0) { + params = action.getParams(); + + for (i = 0; i < params.length; ++i) { + name = params[i].name; + value = params[i].value; + if ((name.indexOf("+") != -1) || (name.indexOf("%") != -1)) + params[i].name = HttpTestCase.staticUrlDecode(name); + if ((value.indexOf("+") != -1) || (value.indexOf("%") != -1)) + params[i].value = HttpTestCase.staticUrlDecode(value); + } + doParameterList(params); + } + + if (action.getQueryStringParamCount() > 0) { + params = action.getQueryStringParams(); + + for (i = 0; i < params.length; ++i) { + name = params[i].name; + value = params[i].value; + if ((name.indexOf("+") != -1) || (name.indexOf("%") != -1)) + params[i].name = HttpTestCase.staticUrlDecode(name); + if ((value.indexOf("+") != -1) || (value.indexOf("%") != -1)) + params[i].value = HttpTestCase.staticUrlDecode(value); + } + doQueryStringParameterList(params); + } + + if (action.getBodyParamCount() > 0) { + params = action.getBodyParams(); + + for (i = 0; i < params.length; ++i) { + name = params[i].name; + value = params[i].value; + if ((name.indexOf("+") != -1) || (name.indexOf("%") != -1)) + params[i].name = HttpTestCase.staticUrlDecode(name); + if ((value.indexOf("+") != -1) || (value.indexOf("%") != -1)) + params[i].value = HttpTestCase.staticUrlDecode(value); + } + doBodyParameterList(params); + } + + String url_str = header.url; + if (requestBody.length > 0) { + url_str = url_str + '?' + new String(requestBody); + } + + if (!(isMultiPartRequest)) { + doTestUrlMessage(HttpTestCase.staticUrlDecode(url_str).trim()); + } + + String data_str = ""; + String cont_len_str = ""; + + if (isMultiPartRequest) { + method = method + "MultiPart"; + data_str = ", data"; + cont_len_str = ", " + header.contentLength; + + doSetData(action.getMultiPartData()); + } + + doCallUrl(action.getUrl(), method, data_str, cont_len_str); + } + + private HeaderValue[] createHeaders(HttpRequestHeader header) + { + Vector v = new Vector(); + if (header.contentType.length() > 0) + v.add(new HeaderValue("Content-Type", header.contentType)); + if (header.accept.length() > 0) + v.add(new HeaderValue("Accept", header.accept)); + if (header.referer.length() > 0) + v.add(new HeaderValue("Referer", header.referer)); + if (header.pragmaNoCache) + v.add(new HeaderValue("Cache-Control", "no-cache")); + HeaderValue[] hv = new HeaderValue[v.size()]; + return ((HeaderValue[])(HeaderValue[])v.toArray(hv)); + } + + public void processResponse(HttpRequestHeader header, byte[] response) + throws Exception + { + if (this.ignoreNextResponse) { + log.debug("Ignoring response"); + this.ignoreNextResponse = false; + return; + } + + String respStr = new String(response).toLowerCase(); + + String respCode = parseResponseCode(respStr); + String contentType = parseContentType(respStr); + + doAssertResponse(respCode); + + if ((contentType != null) && (mimeTypes.get(contentType) != null) && (respCode != null)) { + if (respCode.startsWith("200")) { + if (respStr.indexOf("org.apache.struts.taglib.html.token") > 0) + setStruts(true); + else + setStruts(false); + + if (contentType.toLowerCase().compareTo("text/html") == 0) { + doTidyCode(HttpTestCase.staticUrlDecode(header.url)); + if (cpRspToStdout) + doResponseForStdOut(HttpTestCase.staticUrlDecode(header.url).trim()); + else if (cpRspToFile) + doResponseForFile(); + } + } + + doEndTransaction(); + } else { + log.debug("Ignoring response because content type is not known: " + contentType); + } + + if (isFirstRequest()) + this.isFirstRequest = false; + } + + public void run() + { + this.outstandingInserts = new LinkedList(); + try { + if (!(Thread.interrupted())) + try + { + synchronized (this.outstandingInserts) + { + this.outstandingInserts.wait(); + StringBuffer sb = new StringBuffer(); + while (this.outstandingInserts.size() > 0) { + sb.append((String)this.outstandingInserts.removeFirst()); + } + + Matcher m = this.insertMarkerRE.matcher(getScriptAdapter().getText()); + if (!(m.find())) + throw new Utils.UserException("You have altered your script and it no longer includes the lines that you were told not to alter."); + getScriptAdapter().insert(sb.toString(), m.start(0)); + } + } catch (Utils.UserException e) { + e.printStackTrace(); + } + } + catch (InterruptedException e) { + log.trace("Thread dead"); + } + } + + public abstract void doAssertResponse(String paramString) + throws Utils.UserException; + + public abstract void doCallUrl(String paramString1, String paramString2, String paramString3, String paramString4) + throws Utils.UserException; + + public abstract void doEndTransaction() + throws Utils.UserException; + + public abstract void setStruts(boolean paramBoolean); + + public abstract void doSetCharset(String paramString) + throws Utils.UserException; + + public abstract void doParameterList(Param[] paramArrayOfParam) + throws Utils.UserException; + + public abstract void doQueryStringParameterList(Param[] paramArrayOfParam) + throws Utils.UserException; + + public abstract void doBodyParameterList(Param[] paramArrayOfParam) + throws Utils.UserException; + + public abstract void doResponseForFile() + throws Utils.UserException; + + public abstract void doResponseForStdOut(String paramString) + throws Utils.UserException; + + public abstract void doSetData(String paramString) + throws Utils.UserException; + + public abstract void doTestUrlMessage(String paramString) + throws Utils.UserException; + + public abstract void doTidyCode(String paramString) + throws Utils.UserException; + + public abstract void doHeaders(HeaderValue[] paramArrayOfHeaderValue); + + protected String getScript() + { + return this.scriptAdapter.getText(); + } + + protected void insert(String s) + throws Utils.UserException + { + synchronized (this.outstandingInserts) + { + this.outstandingInserts.add(s); + this.outstandingInserts.notifyAll(); + } + } + + private String parseContentType(String response) + { + String contentType = null; + + int pos = response.indexOf("content-type:"); + if (pos > -1) { + pos += 14; + int end = response.indexOf("\r\n", pos); + int end2 = response.indexOf(";", pos); + if ((end2 > -1) && (end2 < end)) end = end2; + if (end > -1) + contentType = response.substring(pos, end).trim(); + + log.debug(" Content-Type: " + contentType); + } else { + log.debug(" No content-type header! First few lines:"); + StringTokenizer st = new StringTokenizer(response, "\n"); + int i = 0; + while ((st.hasMoreTokens()) && (i < 5)) { + log.debug(st.nextToken()); + ++i; + } + } + return contentType; + } + + private String parseResponseCode(String response) + { + String respCode = null; + int pos = response.indexOf(" "); + if (pos != -1) { + int end = response.indexOf(" ", pos + 1); + + int end2 = response.indexOf("\n", pos + 1); + if ((end2 != -1) && (end2 < end)) end = end2; + if (end != -1) respCode = response.substring(pos + 1, end).trim(); + } + + log.debug("HTTP response code: " + respCode); + return respCode; + } + + private void setMultiPartData(Action action, HttpRequestHeader header, byte[] strarray) + { + String str = new String(strarray); + int begin = header.contentType.indexOf("boundary="); + int end = header.contentType.indexOf("; ", begin); + if (end == -1) + end = header.contentType.length(); + String boundary = header.contentType.substring(begin + 9, end); + + String[] parts = str.split("--" + boundary); + if ((!($assertionsDisabled)) && (!(parts[0].equals("")))) throw new AssertionError(); + + Pattern re = Pattern.compile("\r\nContent-Disposition: form-data; name=\"([^\"]+)\"[^\r\n]*\r\n\r\n(.*)\r\n", 32); + for (int i = 1; i < parts.length - 1; ++i) { + Matcher m = re.matcher(parts[i]); + boolean ok = m.matches(); + if ((!($assertionsDisabled)) && (!(ok))) throw new AssertionError(); + Param p = new Param(); + p.name = m.group(1); + p.value = m.group(2); + action.addBodyParam(p); + } + + if ((!($assertionsDisabled)) && (!(parts[(parts.length - 1)].equals("--\r\n")))) throw new AssertionError(); + } + + private void setQueryStringParams(Action action, String str) + { + List params = Utils.getParams(str); + Iterator iter = params.iterator(); + while (iter.hasNext()) + action.addQueryStringParam((Param)iter.next()); + } + + private void setBodyParams(Action action, String str) + { + List params = Utils.getParams(str); + Iterator iter = params.iterator(); + while (iter.hasNext()) + action.addBodyParam((Param)iter.next()); + } + + private boolean urlIgnored(String str) + { + boolean ignore = false; + + List incPats = this.config.getIncludePatterns(); + List excPats = this.config.getExcludePatterns(); + if ((!(ignore)) && (incPats.size() != 0)) { + log.debug("urlIgnored: checking for include matches"); + ignore = checkMatch(incPats.iterator(), str, false, true); + } + if ((!(ignore)) && (excPats.size() != 0)) { + log.debug("urlIgnored: checking for exclude matches"); + ignore = checkMatch(excPats.iterator(), str, true, ignore); + } + return ignore; + } + + private boolean checkMatch(Iterator iter, String str, boolean res, boolean def) + { + while (iter.hasNext()) { + Matcher m = ((Pattern)iter.next()).matcher(str); + log.debug("checkMatch: for \"" + str + "\" with pattern: \"" + m.pattern().pattern() + "\""); + if (m.find()) { + log.debug("checkMatch: Found match, returning: " + res); + return res; + } + } + log.debug("checkMatch: Didn't find match, returning: " + def); + return def; + } + + static + { + log = LogFactory.getLog(AbstractCodeGenerator.class); + + cpRspTo = System.getProperty("http.cpRspTo"); + + cpRspToFile = false; + MIME_DEFAULTS = new String[] { "text/plain", "text/html", "text/comma-separated-values" }; + + END_STATEMENT = ";" + EOL; + + jtidyConfigFile = System.getProperty("jtidy.config"); + + if (cpRspTo != null) + if (cpRspTo.toLowerCase().compareTo("stdout") == 0) + cpRspToStdout = true; + else if (cpRspTo.toLowerCase().compareTo("file") == 0) + cpRspToFile = true; + + + mimeTypes = new HashMap(); + for (int i = 0; i < MIME_DEFAULTS.length; ++i) + mimeTypes.put(MIME_DEFAULTS[i], MIME_DEFAULTS[i]); + } +} diff --git a/src/main/java/org/bench4q/master/entity/httpcapture/generator/GeneratorFactory.java b/src/main/java/org/bench4q/master/entity/httpcapture/generator/GeneratorFactory.java index 37da1ad3..ae658c63 100644 --- a/src/main/java/org/bench4q/master/entity/httpcapture/generator/GeneratorFactory.java +++ b/src/main/java/org/bench4q/master/entity/httpcapture/generator/GeneratorFactory.java @@ -4,7 +4,6 @@ import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import org.bench4q.master.entity.httpcapture.Config; -import org.bench4q.master.entity.httpcapture.ProxyServer.Observer; import org.bench4q.master.entity.httpcapture.Utils; import org.bench4q.master.entity.httpcapture.IScriptAdapter; @@ -34,7 +33,7 @@ public class GeneratorFactory { return className; } - return (String)getGenDesc.invoke(null, null); + return (String)getGenDesc.invoke((Object)null, (Object)null); } public static IScriptGenerator newGenerator(String className, IScriptAdapter adapter) diff --git a/src/main/java/org/bench4q/master/entity/httpcapture/generator/HttpStatusMap.java b/src/main/java/org/bench4q/master/entity/httpcapture/generator/HttpStatusMap.java new file mode 100644 index 00000000..fb03dfb9 --- /dev/null +++ b/src/main/java/org/bench4q/master/entity/httpcapture/generator/HttpStatusMap.java @@ -0,0 +1,63 @@ +package org.bench4q.master.entity.httpcapture.generator; + +import java.util.HashMap; + +public class HttpStatusMap { + private static final HashMap codes = new HashMap(); + + static + { + codes.put(new Integer(202), "HttpStatus.SC_ACCEPTED"); + codes.put(new Integer(502), "HttpStatus.SC_BAD_GATEWAY"); + codes.put(new Integer(400), "HttpStatus.SC_BAD_REQUEST"); + codes.put(new Integer(409), "HttpStatus.SC_CONFLICT"); + codes.put(new Integer(100), "HttpStatus.SC_CONTINUE"); + codes.put(new Integer(201), "HttpStatus.SC_CREATED"); + codes.put(new Integer(417), "HttpStatus.SC_EXPECTATION_FAILED"); + codes.put(new Integer(424), "HttpStatus.SC_FAILED_DEPENDENCY"); + codes.put(new Integer(403), "HttpStatus.SC_FORBIDDEN"); + codes.put(new Integer(504), "HttpStatus.SC_GATEWAY_TIMEOUT"); + codes.put(new Integer(410), "HttpStatus.SC_GONE"); + codes.put(new Integer(505), "HttpStatus.SC_HttP_VERSION_NOT_SUPPORTED"); + codes.put(new Integer(419), "HttpStatus.SC_INSUFFICIENT_SPACE_ON_RESOURCE"); + codes.put(new Integer(507), "HttpStatus.SC_INSUFFICIENT_STORAGE"); + codes.put(new Integer(500), "HttpStatus.SC_INTERNAL_SERVER_ERROR"); + codes.put(new Integer(411), "HttpStatus.SC_LENGTH_REQUIRED"); + codes.put(new Integer(423), "HttpStatus.SC_LOCKED"); + codes.put(new Integer(420), "HttpStatus.SC_METHOD_FAILURE"); + codes.put(new Integer(405), "HttpStatus.SC_METHOD_NOT_ALLOWED"); + codes.put(new Integer(301), "HttpStatus.SC_MOVED_PERMANENTLY"); + codes.put(new Integer(302), "HttpStatus.SC_MOVED_TEMPORARILY"); + codes.put(new Integer(207), "HttpStatus.SC_MULTI_STATUS"); + codes.put(new Integer(300), "HttpStatus.SC_MULTIPLE_CHOICES"); + codes.put(new Integer(203), "HttpStatus.SC_NON_AUTHORITATIVE_INFORMATION"); + codes.put(new Integer(204), "HttpStatus.SC_NO_CONTENT"); + codes.put(new Integer(406), "HttpStatus.SC_NOT_ACCEPTABLE"); + codes.put(new Integer(404), "HttpStatus.SC_NOT_FOUND"); + codes.put(new Integer(501), "HttpStatus.SC_NOT_IMPLEMENTED"); + codes.put(new Integer(304), "HttpStatus.SC_NOT_MODIFIED"); + codes.put(new Integer(200), "HttpStatus.SC_OK"); + codes.put(new Integer(206), "HttpStatus.SC_PARTIAL_CONTENT"); + codes.put(new Integer(402), "HttpStatus.SC_PAYMENT_REQUIRED"); + codes.put(new Integer(412), "HttpStatus.SC_PRECONDITION_FAILED"); + codes.put(new Integer(102), "HttpStatus.SC_PROCESSING"); + codes.put(new Integer(407), "HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED"); + codes.put(new Integer(408), "HttpStatus.SC_REQUEST_TIMEOUT"); + codes.put(new Integer(413), "HttpStatus.SC_REQUEST_TOO_LONG"); + codes.put(new Integer(414), "HttpStatus.SC_REQUEST_URI_TOO_LONG"); + codes.put(new Integer(416), "HttpStatus.SC_REQUESTED_RANGE_NOT_SATISFIABLE"); + codes.put(new Integer(205), "HttpStatus.SC_RESET_CONTENT"); + codes.put(new Integer(303), "HttpStatus.SC_SEE_OTHER"); + codes.put(new Integer(503), "HttpStatus.SC_SERVICE_UNAVAILABLE"); + codes.put(new Integer(101), "HttpStatus.SC_SWITCHING_PROTOCOLS"); + codes.put(new Integer(307), "HttpStatus.SC_TEMPORARY_REDIRECT"); + codes.put(new Integer(401), "HttpStatus.SC_UNAUTHORIZED"); + codes.put(new Integer(422), "HttpStatus.SC_UNPROCESSABLE_ENTITY"); + codes.put(new Integer(215), "HttpStatus.SC_UNSUPPORTED_MEDIA_TYPE"); + codes.put(new Integer(305), "HttpStatus.SC_USE_PROXY"); + } + + public static String getHttpStatus(int code) { + return ((String)codes.get(new Integer(code))); + } +} diff --git a/src/main/java/org/bench4q/master/entity/httpcapture/generator/HttpUnitTemplateLogic.java b/src/main/java/org/bench4q/master/entity/httpcapture/generator/HttpUnitTemplateLogic.java new file mode 100644 index 00000000..62814f30 --- /dev/null +++ b/src/main/java/org/bench4q/master/entity/httpcapture/generator/HttpUnitTemplateLogic.java @@ -0,0 +1,245 @@ +package org.bench4q.master.entity.httpcapture.generator; + +import java.io.IOException; +import java.net.MalformedURLException; +import java.net.URL; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +import org.xml.sax.SAXException; + +import com.meterware.httpunit.Button; +import com.meterware.httpunit.FrameSelector; +import com.meterware.httpunit.HTMLElementPredicate; +import com.meterware.httpunit.HTMLSegment; +import com.meterware.httpunit.SubmitButton; +import com.meterware.httpunit.WebClient; +import com.meterware.httpunit.WebConversation; +import com.meterware.httpunit.WebForm; +import com.meterware.httpunit.WebLink; +import com.meterware.httpunit.WebResponse; + +public class HttpUnitTemplateLogic { + private final WebClient webClient = new WebConversation(); + private static final HTMLElementPredicate MATCH_URL_STRING_INVERSE = new HTMLElementPredicate() { + public boolean matchesCriteria(Object htmlElement, Object criteria) { + return ((String)criteria).endsWith(((WebLink)htmlElement).getURLString()); + } + }; + + public HTMLSegment parsePage(String url, String content) + throws MalformedURLException + { + return new InPlaceResponse(this.webClient, new URL(url), content); + } + + private WebLink[] getLinksByUrl(HTMLSegment page, String url) + throws SAXException + { + WebLink[] links = page.getMatchingLinks( + MATCH_URL_STRING_INVERSE, url); + return links; + } + + public List getLinkIds(HTMLSegment page, String url) + throws SAXException + { + WebLink[] links = getLinksByUrl(page, url); + List result = new ArrayList(links.length); + for (int i = 0; i < links.length; ++i) + if ((links[i].getID() != null) && (links[i].getID().length() > 0)) + result.add(links[i].getID()); + + return result; + } + + public List getLinkTexts(HTMLSegment page, String url) + throws SAXException + { + WebLink[] links = getLinksByUrl(page, url); + List result = new ArrayList(links.length); + for (int i = 0; i < links.length; ++i) + result.add(links[i].getText()); + + return result; + } + + public List getForms(HTMLSegment page) + throws SAXException + { + return Arrays.asList(page.getForms()); + } + + public WebForm getFormByParameterNames(HTMLSegment page, Map requestParameters) + throws SAXException + { + WebForm[] forms = page.getForms(); + for (int i = 0; i < forms.length; ++i) { + Collection formParameters = Arrays.asList(forms[i] + .getParameterNames()); + if (formParameters.containsAll(requestParameters.keySet())) + return forms[i]; + } + + return null; + } + + public SubmitButton getPostSubmitButton(WebForm form, Map parameters) + throws SAXException + { + SubmitButton[] submits = form.getSubmitButtons(); + for (int j = 0; j < submits.length; ++j) + if (submits[j].getValue().equals(parameters.get(submits[j].getName()))) + return submits[j]; + + return null; + } + + private List numbers(int max) + { + List result = new ArrayList(max); + for (int i = 0; i < max; ++i) + result.add(new Integer(i)); + return result; + } + + public List getPostSubmitButtonIndices(WebForm form) + { + SubmitButton[] submitButtons = form.getSubmitButtons(); + if (submitButtons[0].isFake()) + return null; + + return numbers(submitButtons.length); + } + + private List