refactor the way of send a http request

This commit is contained in:
coderfengyun 2014-01-15 15:16:17 +08:00
parent b24a6585c3
commit 8bb434c8a6
6 changed files with 927 additions and 385 deletions

View File

@ -1 +1,41 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?><runScenario><batches><batches><behaviors><behaviors><id>1</id><name>Get</name><parameters><parameter><key>url</key><value>http://localhost:8080/Bench4QTestCase/testcase.html</value></parameter><parameter><key>parameters</key><value></value></parameter></parameters><use>http</use></behaviors></behaviors><childId>-1</childId><id>0</id><parentId>-1</parentId></batches></batches><poolSize>0</poolSize><usePlugins><usePlugin><id>http</id><name>Http</name><parameters/></usePlugin><usePlugin><id>timer</id><name>ConstantTimer</name><parameters/></usePlugin></usePlugins></runScenario>
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<runScenario>
<batches>
<batches>
<behaviors>
<behaviors>
<id>1</id>
<name>Get</name>
<parameters>
<parameter>
<key>url</key>
<value>http://www.baidu.com
</value>
</parameter>
<parameter>
<key>parameters</key>
<value></value>
</parameter>
</parameters>
<use>http</use>
</behaviors>
</behaviors>
<childId>-1</childId>
<id>0</id>
<parentId>-1</parentId>
</batches>
</batches>
<poolSize>0</poolSize>
<usePlugins>
<usePlugin>
<id>http</id>
<name>Http</name>
<parameters />
</usePlugin>
<usePlugin>
<id>timer</id>
<name>ConstantTimer</name>
<parameters />
</usePlugin>
</usePlugins>
</runScenario>

View File

@ -1 +1,234 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?><runScenario><pages><page><batches><batch><behaviors><behaviorModel><id>0</id><name>Get</name><parameters><parameter><key>url</key><value>http://133.133.12.3:8080/Bench4QTestCase/testcase.html</value></parameter><parameter><key>parameters</key><value></value></parameter></parameters><type>USERBEHAVIOR</type><use>http</use></behaviorModel></behaviors><childId>2</childId><id>0</id><parentId>-1</parentId></batch><batch><behaviors><behaviorModel><id>0</id><name>Sleep</name><parameters><parameter><key>time</key><value>230</value></parameter></parameters><type>TIMERBEHAVIOR</type><use>timer</use></behaviorModel></behaviors><childId>-1</childId><id>1</id><parentId>-1</parentId></batch><batch><behaviors><behaviorModel><id>1</id><name>Get</name><parameters><parameter><key>url</key><value>http://133.133.12.3:8080/Bench4QTestCase/script/agentTable.js</value></parameter><parameter><key>parameters</key><value></value></parameter></parameters><type>USERBEHAVIOR</type><use>http</use></behaviorModel><behaviorModel><id>2</id><name>Get</name><parameters><parameter><key>url</key><value>http://133.133.12.3:8080/Bench4QTestCase/images/3.jpg</value></parameter><parameter><key>parameters</key><value></value></parameter></parameters><type>USERBEHAVIOR</type><use>http</use></behaviorModel><behaviorModel><id>3</id><name>Get</name><parameters><parameter><key>url</key><value>http://133.133.12.3:8080/Bench4QTestCase/script/base.js</value></parameter><parameter><key>parameters</key><value></value></parameter></parameters><type>USERBEHAVIOR</type><use>http</use></behaviorModel><behaviorModel><id>4</id><name>Get</name><parameters><parameter><key>url</key><value>http://133.133.12.3:8080/Bench4QTestCase/images/1.jpg</value></parameter><parameter><key>parameters</key><value></value></parameter></parameters><type>USERBEHAVIOR</type><use>http</use></behaviorModel><behaviorModel><id>5</id><name>Get</name><parameters><parameter><key>url</key><value>http://133.133.12.3:8080/Bench4QTestCase/images/2.jpg</value></parameter><parameter><key>parameters</key><value></value></parameter></parameters><type>USERBEHAVIOR</type><use>http</use></behaviorModel></behaviors><childId>-1</childId><id>2</id><parentId>0</parentId></batch><batch><behaviors><behaviorModel><id>0</id><name>Sleep</name><parameters><parameter><key>time</key><value>96</value></parameter></parameters><type>TIMERBEHAVIOR</type><use>timer</use></behaviorModel></behaviors><childId>-1</childId><id>3</id><parentId>-1</parentId></batch><batch><behaviors><behaviorModel><id>0</id><name>Sleep</name><parameters><parameter><key>time</key><value>3</value></parameter></parameters><type>TIMERBEHAVIOR</type><use>timer</use></behaviorModel></behaviors><childId>-1</childId><id>4</id><parentId>-1</parentId></batch><batch><behaviors><behaviorModel><id>0</id><name>Sleep</name><parameters><parameter><key>time</key><value>10</value></parameter></parameters><type>TIMERBEHAVIOR</type><use>timer</use></behaviorModel></behaviors><childId>-1</childId><id>5</id><parentId>-1</parentId></batch><batch><behaviors><behaviorModel><id>0</id><name>Sleep</name><parameters><parameter><key>time</key><value>6</value></parameter></parameters><type>TIMERBEHAVIOR</type><use>timer</use></behaviorModel></behaviors><childId>-1</childId><id>6</id><parentId>-1</parentId></batch></batches></page></pages><poolSize>0</poolSize><usePlugins><usePlugin><id>http</id><name>Http</name><parameters/></usePlugin><usePlugin><id>timer</id><name>ConstantTimer</name><parameters/></usePlugin></usePlugins></runScenario>
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<runScenario>
<pages>
<page>
<batches>
<batch>
<behaviors>
<behaviorModel>
<id>0</id>
<name>Get</name>
<parameters>
<parameter>
<key>url</key>
<value>
http://133.133.12.3:8080/Bench4QTestCase/testcase.html
</value>
</parameter>
<parameter>
<key>parameters</key>
<value></value>
</parameter>
</parameters>
<type>USERBEHAVIOR</type>
<use>http</use>
</behaviorModel>
</behaviors>
<childId>2</childId>
<id>0</id>
<parentId>-1</parentId>
</batch>
<batch>
<behaviors>
<behaviorModel>
<id>0</id>
<name>Sleep</name>
<parameters>
<parameter>
<key>time</key>
<value>230</value>
</parameter>
</parameters>
<type>TIMERBEHAVIOR</type>
<use>timer</use>
</behaviorModel>
</behaviors>
<childId>-1</childId>
<id>1</id>
<parentId>-1</parentId>
</batch>
<batch>
<behaviors>
<behaviorModel>
<id>1</id>
<name>Get</name>
<parameters>
<parameter>
<key>url</key>
<value>http://133.133.12.3:8080/Bench4QTestCase/script/agentTable.js
</value>
</parameter>
<parameter>
<key>parameters</key>
<value></value>
</parameter>
</parameters>
<type>USERBEHAVIOR</type>
<use>http</use>
</behaviorModel>
<behaviorModel>
<id>2</id>
<name>Get</name>
<parameters>
<parameter>
<key>url</key>
<value>http://133.133.12.3:8080/Bench4QTestCase/images/3.jpg
</value>
</parameter>
<parameter>
<key>parameters</key>
<value></value>
</parameter>
</parameters>
<type>USERBEHAVIOR</type>
<use>http</use>
</behaviorModel>
<behaviorModel>
<id>3</id>
<name>Get</name>
<parameters>
<parameter>
<key>url</key>
<value>http://133.133.12.3:8080/Bench4QTestCase/script/base.js
</value>
</parameter>
<parameter>
<key>parameters</key>
<value></value>
</parameter>
</parameters>
<type>USERBEHAVIOR</type>
<use>http</use>
</behaviorModel>
<behaviorModel>
<id>4</id>
<name>Get</name>
<parameters>
<parameter>
<key>url</key>
<value>http://133.133.12.3:8080/Bench4QTestCase/images/1.jpg
</value>
</parameter>
<parameter>
<key>parameters</key>
<value></value>
</parameter>
</parameters>
<type>USERBEHAVIOR</type>
<use>http</use>
</behaviorModel>
<behaviorModel>
<id>5</id>
<name>Get</name>
<parameters>
<parameter>
<key>url</key>
<value>http://133.133.12.3:8080/Bench4QTestCase/images/2.jpg
</value>
</parameter>
<parameter>
<key>parameters</key>
<value></value>
</parameter>
</parameters>
<type>USERBEHAVIOR</type>
<use>http</use>
</behaviorModel>
</behaviors>
<childId>-1</childId>
<id>2</id>
<parentId>0</parentId>
</batch>
<batch>
<behaviors>
<behaviorModel>
<id>0</id>
<name>Sleep</name>
<parameters>
<parameter>
<key>time</key>
<value>96</value>
</parameter>
</parameters>
<type>TIMERBEHAVIOR</type>
<use>timer</use>
</behaviorModel>
</behaviors>
<childId>-1</childId>
<id>3</id>
<parentId>-1</parentId>
</batch>
<batch>
<behaviors>
<behaviorModel>
<id>0</id>
<name>Sleep</name>
<parameters>
<parameter>
<key>time</key>
<value>3</value>
</parameter>
</parameters>
<type>TIMERBEHAVIOR</type>
<use>timer</use>
</behaviorModel>
</behaviors>
<childId>-1</childId>
<id>4</id>
<parentId>-1</parentId>
</batch>
<batch>
<behaviors>
<behaviorModel>
<id>0</id>
<name>Sleep</name>
<parameters>
<parameter>
<key>time</key>
<value>10</value>
</parameter>
</parameters>
<type>TIMERBEHAVIOR</type>
<use>timer</use>
</behaviorModel>
</behaviors>
<childId>-1</childId>
<id>5</id>
<parentId>-1</parentId>
</batch>
<batch>
<behaviors>
<behaviorModel>
<id>0</id>
<name>Sleep</name>
<parameters>
<parameter>
<key>time</key>
<value>6</value>
</parameter>
</parameters>
<type>TIMERBEHAVIOR</type>
<use>timer</use>
</behaviorModel>
</behaviors>
<childId>-1</childId>
<id>6</id>
<parentId>-1</parentId>
</batch>
</batches>
</page>
</pages>
<poolSize>0</poolSize>
<usePlugins>
<usePlugin>
<id>http</id>
<name>Http</name>
<parameters />
</usePlugin>
<usePlugin>
<id>timer</id>
<name>ConstantTimer</name>
<parameters />
</usePlugin>
</usePlugins>
</runScenario>

View File

@ -1,162 +1,206 @@
package org.bench4q.agent.plugin.basic;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import org.apache.log4j.Logger;
import org.bench4q.agent.plugin.Behavior;
import org.bench4q.agent.plugin.Parameter;
import org.bench4q.agent.plugin.Plugin;
import org.bench4q.agent.plugin.result.HttpReturn;
import org.bench4q.agent.share.DealWithLog;
@Plugin("Http")
public class HttpPlugin {
private Logger logger = Logger.getLogger(HttpPlugin.class);
public HttpPlugin() {
}
@Behavior("Get")
public HttpReturn get(@Parameter("url") String url) {
HttpURLConnection httpURLConnection = null;
StringBuffer stringBuffer = null;
String requestMethod = "GET";
try {
httpURLConnection = getRequestURLConnection(url, requestMethod);
stringBuffer = readConnectionInputStream(httpURLConnection);
return new HttpReturn(true, httpURLConnection.getResponseCode(),
stringBuffer.length() * 2,
httpURLConnection.getContentType());
} catch (MalformedURLException e) {
logger.info(DealWithLog.getExceptionStackTrace(e));
return new HttpReturn(false, 400, 0, "");
} catch (IOException e) {
logger.info(DealWithLog.getExceptionStackTrace(e));
return new HttpReturn(false, 404, 0, "");
}
}
private HttpURLConnection getRequestURLConnection(String url, String method)
throws MalformedURLException, IOException {
HttpURLConnection httpURLConnection;
URL target = new URL(url);
httpURLConnection = (HttpURLConnection) target.openConnection();
if (method.equals("GET")) {
httpURLConnection.setDoOutput(false);
} else {
httpURLConnection.setDoOutput(true);
}
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
httpURLConnection.setUseCaches(false);
httpURLConnection.setRequestMethod(method);
return httpURLConnection;
}
private StringBuffer readConnectionInputStream(
HttpURLConnection httpURLConnection) throws IOException {
StringBuffer stringBuffer = new StringBuffer();
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(httpURLConnection.getInputStream()));
int temp = -1;
while ((temp = bufferedReader.read()) != -1) {
stringBuffer.append((char) temp);
}
bufferedReader.close();
return stringBuffer;
}
private void writeContentToConnectOutputSteam(String content,
HttpURLConnection httpURLConnection) throws IOException {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(
httpURLConnection.getOutputStream());
outputStreamWriter.write(content);
outputStreamWriter.flush();
outputStreamWriter.close();
}
@Behavior("Post")
public HttpReturn post(@Parameter("url") String url,
@Parameter("content") String content,
@Parameter("contentType") String contentType,
@Parameter("accept") String accept) {
HttpURLConnection httpURLConnection = null;
String requestMethod = "POST";
StringBuffer stringBuffer = null;
try {
httpURLConnection = getRequestURLConnection(url, requestMethod);
httpURLConnection.setRequestMethod("POST");
if (contentType != null && contentType.length() > 0) {
httpURLConnection.setRequestProperty("Content-Type",
contentType);
}
if (accept != null && accept.length() > 0) {
httpURLConnection.setRequestProperty("Accept", accept);
}
writeContentToConnectOutputSteam(content, httpURLConnection);
stringBuffer = readConnectionInputStream(httpURLConnection);
return new HttpReturn(true, httpURLConnection.getResponseCode(),
stringBuffer.length() * 2,
httpURLConnection.getContentType());
} catch (MalformedURLException e) {
logger.info(DealWithLog.getExceptionStackTrace(e));
return new HttpReturn(false, 400, 0, "");
} catch (IOException e) {
logger.info(DealWithLog.getExceptionStackTrace(e));
return new HttpReturn(false, 404, 0, "");
}
}
@Behavior("Put")
public HttpReturn put(@Parameter("url") String url,
@Parameter("content") String content) {
StringBuffer stringBuffer = null;
String requestMethod = "PUT";
try {
HttpURLConnection httpURLConnection = this.getRequestURLConnection(
url, requestMethod);
writeContentToConnectOutputSteam(content, httpURLConnection);
stringBuffer = readConnectionInputStream(httpURLConnection);
return new HttpReturn(true, httpURLConnection.getResponseCode(),
stringBuffer.length() * 2,
httpURLConnection.getContentType());
} catch (MalformedURLException e) {
logger.info(DealWithLog.getExceptionStackTrace(e));
return new HttpReturn(false, 400, 0, "");
} catch (IOException e) {
logger.info(DealWithLog.getExceptionStackTrace(e));
return new HttpReturn(false, 404, 0, "");
}
}
@Behavior("Delete")
public HttpReturn delete(@Parameter("url") String url,
@Parameter("content") String content) {
StringBuffer stringBuffer = null;
String requestMethod = "DELETE";
try {
HttpURLConnection httpURLConnection = getRequestURLConnection(url,
requestMethod);
writeContentToConnectOutputSteam(content, httpURLConnection);
stringBuffer = readConnectionInputStream(httpURLConnection);
return new HttpReturn(true, httpURLConnection.getResponseCode(),
stringBuffer.length() * 2,
httpURLConnection.getContentType());
} catch (MalformedURLException e) {
logger.info(DealWithLog.getExceptionStackTrace(e));
return new HttpReturn(false, 400, 0, "");
} catch (IOException e) {
logger.info(DealWithLog.getExceptionStackTrace(e));
return new HttpReturn(false, 404, 0, "");
}
}
}
package org.bench4q.agent.plugin.basic;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Iterator;
import java.util.List;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.log4j.Logger;
import org.bench4q.agent.plugin.Behavior;
import org.bench4q.agent.plugin.Parameter;
import org.bench4q.agent.plugin.Plugin;
import org.bench4q.agent.plugin.result.HttpReturn;
import org.bench4q.agent.scenario.utils.ParameterParser;
import org.bench4q.agent.share.DealWithLog;
@Plugin("Http")
public class HttpPlugin {
private Logger logger = Logger.getLogger(HttpPlugin.class);
private HttpClient httpClient;
private HttpClient getHttpClient() {
return httpClient;
}
private void setHttpClient(HttpClient httpClient) {
this.httpClient = httpClient;
}
public HttpPlugin() {
this.setHttpClient(new HttpClient());
}
@Behavior("Get")
public HttpReturn get(@Parameter("url") String url,
@Parameter("queryParams") String queryParams,
@Parameter("headers") String headers) {
GetMethod method = new GetMethod(url);
if (queryParams != null && queryParams.length() > 0) {
method.setQueryString(queryParams);
}
method.getParams().makeLenient();
setHeaders(method, headers);
int responseCode = -1;
long contentLength = 0;
String contentType = "";
try {
responseCode = this.getHttpClient().executeMethod(method);
method.getStatusLine().toString();
method.getResponseHeaders();
contentLength = method.getResponseContentLength();
if (method.getResponseHeader("Content-Type") != null) {
contentType = method.getResponseHeader("Content-Type")
.getValue();
}
System.out.println(method.getResponseBodyAsString());
return new HttpReturn(responseCode > 0, responseCode,
contentLength, contentType);
} catch (HttpException e) {
e.printStackTrace();
return new HttpReturn(false, 400, contentLength, contentType);
} catch (IOException e) {
e.printStackTrace();
return new HttpReturn(false, 400, contentLength, contentType);
} finally {
method.releaseConnection();
}
}
static void setHeaders(HttpMethod method, String headers) {
if (headers != null) {
List<List<String>> values = ParameterParser.getTable(headers);
Iterator<List<String>> headerIter = values.iterator();
while (headerIter.hasNext()) {
Iterator<String> entryIter = headerIter.next().iterator();
String name = entryIter.next();
method.addRequestHeader(name, entryIter.next());
}
}
}
private HttpURLConnection getRequestURLConnection(String url, String method)
throws MalformedURLException, IOException {
HttpURLConnection httpURLConnection;
URL target = new URL(url);
httpURLConnection = (HttpURLConnection) target.openConnection();
if (method.equals("GET")) {
httpURLConnection.setDoOutput(false);
} else {
httpURLConnection.setDoOutput(true);
}
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
httpURLConnection.setUseCaches(false);
httpURLConnection.setRequestMethod(method);
return httpURLConnection;
}
private StringBuffer readConnectionInputStream(
HttpURLConnection httpURLConnection) throws IOException {
StringBuffer stringBuffer = new StringBuffer();
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(httpURLConnection.getInputStream()));
int temp = -1;
while ((temp = bufferedReader.read()) != -1) {
stringBuffer.append((char) temp);
}
bufferedReader.close();
return stringBuffer;
}
private void writeContentToConnectOutputSteam(String content,
HttpURLConnection httpURLConnection) throws IOException {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(
httpURLConnection.getOutputStream());
outputStreamWriter.write(content);
outputStreamWriter.flush();
outputStreamWriter.close();
}
@Behavior("Post")
public HttpReturn post(@Parameter("url") String url,
@Parameter("content") String content,
@Parameter("contentType") String contentType,
@Parameter("accept") String accept) {
HttpURLConnection httpURLConnection = null;
String requestMethod = "POST";
StringBuffer stringBuffer = null;
try {
httpURLConnection = getRequestURLConnection(url, requestMethod);
httpURLConnection.setRequestMethod("POST");
if (contentType != null && contentType.length() > 0) {
httpURLConnection.setRequestProperty("Content-Type",
contentType);
}
if (accept != null && accept.length() > 0) {
httpURLConnection.setRequestProperty("Accept", accept);
}
writeContentToConnectOutputSteam(content, httpURLConnection);
stringBuffer = readConnectionInputStream(httpURLConnection);
return new HttpReturn(true, httpURLConnection.getResponseCode(),
stringBuffer.length() * 2,
httpURLConnection.getContentType());
} catch (MalformedURLException e) {
logger.info(DealWithLog.getExceptionStackTrace(e));
return new HttpReturn(false, 400, 0, "");
} catch (IOException e) {
logger.info(DealWithLog.getExceptionStackTrace(e));
return new HttpReturn(false, 404, 0, "");
}
}
@Behavior("Put")
public HttpReturn put(@Parameter("url") String url,
@Parameter("content") String content) {
StringBuffer stringBuffer = null;
String requestMethod = "PUT";
try {
HttpURLConnection httpURLConnection = this.getRequestURLConnection(
url, requestMethod);
writeContentToConnectOutputSteam(content, httpURLConnection);
stringBuffer = readConnectionInputStream(httpURLConnection);
return new HttpReturn(true, httpURLConnection.getResponseCode(),
stringBuffer.length() * 2,
httpURLConnection.getContentType());
} catch (MalformedURLException e) {
logger.info(DealWithLog.getExceptionStackTrace(e));
return new HttpReturn(false, 400, 0, "");
} catch (IOException e) {
logger.info(DealWithLog.getExceptionStackTrace(e));
return new HttpReturn(false, 404, 0, "");
}
}
@Behavior("Delete")
public HttpReturn delete(@Parameter("url") String url,
@Parameter("content") String content) {
StringBuffer stringBuffer = null;
String requestMethod = "DELETE";
try {
HttpURLConnection httpURLConnection = getRequestURLConnection(url,
requestMethod);
writeContentToConnectOutputSteam(content, httpURLConnection);
stringBuffer = readConnectionInputStream(httpURLConnection);
return new HttpReturn(true, httpURLConnection.getResponseCode(),
stringBuffer.length() * 2,
httpURLConnection.getContentType());
} catch (MalformedURLException e) {
logger.info(DealWithLog.getExceptionStackTrace(e));
return new HttpReturn(false, 400, 0, "");
} catch (IOException e) {
logger.info(DealWithLog.getExceptionStackTrace(e));
return new HttpReturn(false, 404, 0, "");
}
}
}

View File

@ -0,0 +1,219 @@
/*
* CLIF is a Load Injection Framework
* Copyright (C) 2008, 2009 France Telecom R&D
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Contact: clif@ow2.org
*/
package org.bench4q.agent.scenario.utils;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
/**
*
* @author coderfengyun
*
*/
public abstract class ParameterParser {
static public List<String> getNField(String value) {
List<String> realTokens = getRealTokens(";", value);
for (int i = 0; i < realTokens.size(); ++i) {
realTokens.set(i, unescape(realTokens.get(i)));
}
return realTokens;
}
static public String getRadioGroup(String value) {
List<String> realTokens = getRealTokens(";", value);
if (realTokens.size() == 0) {
return "";
} else {
return unescape(realTokens.get(0));
}
}
static public List<String> getCheckBox(String value) {
return getNField(value);
}
static public String getCombo(String value) {
return getRadioGroup(value);
}
/**
* This method analyzes the value to be set in the table, and remove all
* escape characters
*
* @param value
* The value containing the serialization of all values of the
* table
* @return The vector containing all the entries, each entries is in a
* vector, which contains the string values
*/
static public List<List<String>> getTable(String value) {
List<List<String>> result = new ArrayList<List<String>>();
List<String> tempEntries = getRealTokens(";", value);
// now analyze all entries values, and get the '|' separator
List<List<String>> allValues = new ArrayList<List<String>>();
for (int i = 0; i < tempEntries.size(); i++) {
String tempEntry = tempEntries.get(i);
List<String> values = getRealTokens("|", tempEntry);
allValues.add(values);
}
// now analyze all values, and get the '=' separator
for (int i = 0; i < allValues.size(); i++) {
List<String> resultValues = new ArrayList<String>();
List<String> tempValues = allValues.get(i);
for (int j = 0; j < tempValues.size(); j++) {
String v = tempValues.get(j);
List<String> temp = getRealTokens("=", v);
String res;
if (temp.size() > 1) {
res = temp.get(1);
} else {
res = "";
}
res = unescape(res);
resultValues.add(res);
}
result.add(resultValues);
}
return result;
}
/**
* Get the number of escape character in the end of the string
*
* @param value
* The string to be analyzed
* @return 0 if no escape character was found, else the number
*/
static private int getNumberOfEscapeCharacter(String value) {
int result = 0;
if (value.length() > 0) {
int last = value.lastIndexOf("\\");
if (last == value.length() - 1) {
result = 1 + getNumberOfEscapeCharacter(value
.substring(0, last));
}
}
return result;
}
/**
* Add escape separator before each separator
*
* @param separator
* The separator character
* @param value
* The value of the string to add the escape characters
* @return The string modified
*/
static public String addEscapeCharacter(String separator, String value) {
String result = "";
StringTokenizer st = new StringTokenizer(value, separator, true);
while (st.hasMoreTokens()) {
String token = st.nextToken();
if (token.equals(separator)) {
result = result.concat("\\" + token);
} else {
result = result.concat(token);
}
}
return result;
}
/**
* Split the string value with the separator, and check if there is no
* escape character before the separator
*
* @param separator
* The separator
* @param value
* The string value to be split
* @return The vector containing each token
*/
static public List<String> getRealTokens(String separator, String value) {
List<String> result = new ArrayList<String>();
if (value != null) {
StringTokenizer st = new StringTokenizer(value, separator, true);
String currentRealToken = "";
while (st.hasMoreTokens()) {
String token = st.nextToken();
// the token is the separator
if (token.equals(separator)) {
int nb = getNumberOfEscapeCharacter(currentRealToken);
// if nb is even, we don't have any escape character
if (nb % 2 == 0) {
result.add(currentRealToken);
currentRealToken = "";
}
// nb is odd
else {
// remove the escape character
currentRealToken = currentRealToken.substring(0,
currentRealToken.length() - 1);
// add the separator character
currentRealToken = currentRealToken.concat(separator);
// if it's the last token add it to the result
if (!st.hasMoreTokens()) {
result.add(currentRealToken);
}
}
}
// the token is a string
else {
currentRealToken = currentRealToken.concat(token);
// if it's the last token add it to the result
if (!st.hasMoreTokens()) {
result.add(currentRealToken);
}
}
}
}
return result;
}
/**
* Replaces every escape sequences by the corresponding original character
*
* @param value
* the string where some characters are escaped by '\' character
* @return the unescaped string
*/
static public String unescape(String value) {
StringBuilder result = new StringBuilder();
char c;
boolean escape = false; // escape sequence
for (int i = 0; i < value.length(); ++i) {
c = value.charAt(i);
if (escape) {
result.append(c);
escape = false;
} else {
if (c == '\\') {
escape = true;
} else {
result.append(c);
}
}
}
return result.toString();
}
}

View File

@ -1,189 +1,197 @@
package org.bench4q.agent.test;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.UUID;
import static org.junit.Assert.*;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import org.apache.commons.io.FileUtils;
import org.bench4q.share.helper.MarshalHelper;
import org.bench4q.share.models.agent.BehaviorBriefModel;
import org.bench4q.share.models.agent.RunScenarioModel;
import org.bench4q.share.models.agent.RunScenarioResultModel;
import org.bench4q.share.models.agent.statistics.AgentBriefStatusModel;
import org.bench4q.share.models.agent.statistics.AgentBehaviorsBriefModel;
import org.bench4q.share.models.agent.statistics.AgentPageBriefModel;
import org.junit.Test;
import Communication.HttpRequester;
import Communication.HttpRequester.HttpResponse;
public class TestWithScriptFile {
private HttpRequester httpRequester;
private String url = "http://localhost:6565/test";
private String filePath;
private UUID testId;
private static int load = 10;
public String getFilePath() {
return filePath;
}
public void setFilePath(String filePath) {
this.filePath = filePath;
}
public HttpRequester getHttpRequester() {
return httpRequester;
}
public void setHttpRequester(HttpRequester httpRequester) {
this.httpRequester = httpRequester;
}
public UUID getTestId() {
return testId;
}
public void setTestId(UUID testId) {
this.testId = testId;
}
public TestWithScriptFile() {
this.setFilePath("Scripts" + System.getProperty("file.separator")
+ "goodForPage.xml");
this.setHttpRequester(new HttpRequester());
}
public void startTest() throws JAXBException {
File file = new File(this.getFilePath());
if (!file.exists()) {
System.out.println("this script not exists!");
return;
}
String scriptContent;
try {
scriptContent = FileUtils.readFileToString(file);
RunScenarioModel runScenarioModel = extractRunScenarioModel(scriptContent);
if (runScenarioModel == null) {
System.out.println("can't execute an unvalid script");
return;
}
assertTrue(runScenarioModel.getPages().size() > 0);
assertTrue(runScenarioModel.getPages().get(0).getBatches().get(0)
.getBehaviors().size() > 0);
runScenarioModel.setPoolSize(load);
HttpResponse httpResponse = this.getHttpRequester().sendPostXml(
this.url + "/run",
marshalRunScenarioModel(runScenarioModel), null);
RunScenarioResultModel resultModel = (RunScenarioResultModel) MarshalHelper
.unmarshal(RunScenarioResultModel.class,
httpResponse.getContent());
this.setTestId(resultModel.getRunId());
} catch (IOException e) {
System.out.println("IO exception!");
}
}
private RunScenarioModel extractRunScenarioModel(String scriptContent) {
try {
Unmarshaller unmarshaller = JAXBContext.newInstance(
RunScenarioModel.class).createUnmarshaller();
return (RunScenarioModel) unmarshaller
.unmarshal(new ByteArrayInputStream(scriptContent
.getBytes()));
} catch (JAXBException e) {
System.out.println("model unmarshal has an exception!");
e.printStackTrace();
return null;
}
}
private String marshalRunScenarioModel(RunScenarioModel model)
throws JAXBException {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
JAXBContext.newInstance(RunScenarioModel.class).createMarshaller()
.marshal(model, outputStream);
return outputStream.toString();
}
private void stopTest() throws IOException {
System.out.println("Enter stopTest!");
this.getHttpRequester().sendGet(
this.url + "/stop/" + this.getTestId().toString(), null, null);
}
private void scenarioBrief() throws IOException, JAXBException {
System.out.println("Enter brief!");
HttpResponse httpResponse = this.getHttpRequester().sendGet(
this.url + "/brief/" + this.getTestId().toString(), null, null);
AgentBriefStatusModel briefModel = (AgentBriefStatusModel) MarshalHelper
.unmarshal(AgentBriefStatusModel.class,
httpResponse.getContent());
assertTrue(briefModel.getTimeFrame() > 0);
}
private void behaviorsBrief() throws IOException, JAXBException {
System.out.println("Enter behaviorsBrief!");
HttpResponse httpResponse = this.getHttpRequester().sendGet(
this.url + "/behaviorsBrief/" + this.getTestId().toString(),
null, null);
AgentBehaviorsBriefModel behaviorsBriefModel = (AgentBehaviorsBriefModel) MarshalHelper
.unmarshal(AgentBehaviorsBriefModel.class,
httpResponse.getContent());
assertTrue(behaviorsBriefModel.getBehaviorBriefModels().size() > 0);
}
private void behaviorBrief() throws IOException, JAXBException {
System.out.println("Enter behaviorBrief!");
HttpResponse httpResponse = this.getHttpRequester().sendGet(
this.url + "/brief/" + this.getTestId().toString() + "/0",
null, null);
BehaviorBriefModel behaviorBriefModel = (BehaviorBriefModel) MarshalHelper
.unmarshal(BehaviorBriefModel.class, httpResponse.getContent());
assertTrue(behaviorBriefModel.getDetailStatusCodeResultModels().size() > 0);
}
@Test
public void integrateTest() throws JAXBException, InterruptedException,
IOException {
this.startTest();
Thread.sleep(5000);
this.scenarioBrief();
Thread.sleep(5000);
this.behaviorsBrief();
Thread.sleep(5000);
this.behaviorBrief();
Thread.sleep(5000);
this.pageBrief(0);
this.stopTest();
}
private void pageBrief(int i) throws IOException, JAXBException {
try {
HttpResponse httpResponse = this.getHttpRequester().sendGet(
url + "/pageBrief/" + this.getTestId() + "/" + i, null,
null);
if (httpResponse == null || httpResponse.getContent().isEmpty()) {
fail();
}
System.out.println(httpResponse);
AgentPageBriefModel pageBriefModel = (AgentPageBriefModel) MarshalHelper
.unmarshal(AgentPageBriefModel.class,
httpResponse.getContent());
assertTrue(pageBriefModel.getCountFromBegin() > 0);
} catch (Exception e) {
this.stopTest();
}
}
}
package org.bench4q.agent.test;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.UUID;
import static org.junit.Assert.*;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import org.apache.commons.io.FileUtils;
import org.bench4q.share.helper.MarshalHelper;
import org.bench4q.share.models.agent.BehaviorBriefModel;
import org.bench4q.share.models.agent.RunScenarioModel;
import org.bench4q.share.models.agent.RunScenarioResultModel;
import org.bench4q.share.models.agent.statistics.AgentBriefStatusModel;
import org.bench4q.share.models.agent.statistics.AgentBehaviorsBriefModel;
import org.bench4q.share.models.agent.statistics.AgentPageBriefModel;
import org.junit.Test;
import Communication.HttpRequester;
import Communication.HttpRequester.HttpResponse;
public class TestWithScriptFile {
private HttpRequester httpRequester;
private String url = "http://agent1.jd-app.com/test";
private String filePath;
private UUID testId;
private static int load = 10;
public String getFilePath() {
return filePath;
}
public void setFilePath(String filePath) {
this.filePath = filePath;
}
public HttpRequester getHttpRequester() {
return httpRequester;
}
public void setHttpRequester(HttpRequester httpRequester) {
this.httpRequester = httpRequester;
}
public UUID getTestId() {
return testId;
}
public void setTestId(UUID testId) {
this.testId = testId;
}
public TestWithScriptFile() {
this.setFilePath("Scripts" + System.getProperty("file.separator")
+ "testJD.xml");
this.setHttpRequester(new HttpRequester());
}
public void startTest() throws JAXBException {
File file = new File(this.getFilePath());
if (!file.exists()) {
System.out.println("this script not exists!");
return;
}
String scriptContent;
try {
scriptContent = FileUtils.readFileToString(file);
RunScenarioModel runScenarioModel = extractRunScenarioModel(scriptContent);
if (runScenarioModel == null) {
System.out.println("can't execute an unvalid script");
return;
}
assertTrue(runScenarioModel.getPages().size() > 0);
assertTrue(runScenarioModel.getPages().get(0).getBatches().get(0)
.getBehaviors().size() > 0);
runScenarioModel.setPoolSize(load);
HttpResponse httpResponse = this.getHttpRequester().sendPostXml(
this.url + "/run",
marshalRunScenarioModel(runScenarioModel), null);
RunScenarioResultModel resultModel = (RunScenarioResultModel) MarshalHelper
.unmarshal(RunScenarioResultModel.class,
httpResponse.getContent());
this.setTestId(resultModel.getRunId());
} catch (IOException e) {
System.out.println("IO exception!");
}
}
private RunScenarioModel extractRunScenarioModel(String scriptContent) {
try {
Unmarshaller unmarshaller = JAXBContext.newInstance(
RunScenarioModel.class).createUnmarshaller();
return (RunScenarioModel) unmarshaller
.unmarshal(new ByteArrayInputStream(scriptContent
.getBytes()));
} catch (JAXBException e) {
System.out.println("model unmarshal has an exception!");
e.printStackTrace();
return null;
}
}
private String marshalRunScenarioModel(RunScenarioModel model)
throws JAXBException {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
JAXBContext.newInstance(RunScenarioModel.class).createMarshaller()
.marshal(model, outputStream);
return outputStream.toString();
}
private void stopTest() throws IOException {
System.out.println("Enter stopTest!");
this.getHttpRequester().sendGet(
this.url + "/stop/" + this.getTestId().toString(), null, null);
}
private void scenarioBrief() throws IOException, JAXBException {
System.out.println("Enter brief!");
HttpResponse httpResponse = this.getHttpRequester().sendGet(
this.url + "/brief/" + this.getTestId().toString(), null, null);
System.out.println(httpResponse.getContent());
AgentBriefStatusModel briefModel = (AgentBriefStatusModel) MarshalHelper
.unmarshal(AgentBriefStatusModel.class,
httpResponse.getContent());
assertTrue(briefModel.getTimeFrame() > 0);
}
private void behaviorsBrief() throws IOException, JAXBException {
System.out.println("Enter behaviorsBrief!");
HttpResponse httpResponse = this.getHttpRequester().sendGet(
this.url + "/behaviorsBrief/" + this.getTestId().toString(),
null, null);
System.out.println(httpResponse.getContent());
AgentBehaviorsBriefModel behaviorsBriefModel = (AgentBehaviorsBriefModel) MarshalHelper
.unmarshal(AgentBehaviorsBriefModel.class,
httpResponse.getContent());
assertTrue(behaviorsBriefModel.getBehaviorBriefModels().size() > 0);
}
private void behaviorBrief() throws IOException, JAXBException {
System.out.println("Enter behaviorBrief!");
HttpResponse httpResponse = this.getHttpRequester().sendGet(
this.url + "/brief/" + this.getTestId().toString() + "/0",
null, null);
BehaviorBriefModel behaviorBriefModel = (BehaviorBriefModel) MarshalHelper
.unmarshal(BehaviorBriefModel.class, httpResponse.getContent());
assertTrue(behaviorBriefModel.getDetailStatusCodeResultModels().size() > 0);
}
@Test
public void integrateTest() throws JAXBException, InterruptedException,
IOException {
try {
this.startTest();
Thread.sleep(5000);
this.scenarioBrief();
Thread.sleep(5000);
this.behaviorsBrief();
Thread.sleep(5000);
this.behaviorBrief();
Thread.sleep(5000);
this.pageBrief(0);
} catch (Exception e) {
e.printStackTrace();
} finally {
this.stopTest();
}
}
private void pageBrief(int i) throws IOException, JAXBException {
try {
HttpResponse httpResponse = this.getHttpRequester().sendGet(
url + "/pageBrief/" + this.getTestId() + "/" + i, null,
null);
if (httpResponse == null || httpResponse.getContent().isEmpty()) {
fail();
}
System.out.println(httpResponse);
AgentPageBriefModel pageBriefModel = (AgentPageBriefModel) MarshalHelper
.unmarshal(AgentPageBriefModel.class,
httpResponse.getContent());
assertTrue(pageBriefModel.getCountFromBegin() > 0);
} catch (Exception e) {
this.stopTest();
}
}
}

View File

@ -1,32 +1,30 @@
package org.bench4q.agent.test.plugin;
import org.bench4q.agent.plugin.basic.HttpPlugin;
import org.bench4q.agent.plugin.result.PluginReturn;
import org.junit.Test;
import static org.junit.Assert.*;
public class TestHttpPlugin {
private HttpPlugin httpPlugin;
private HttpPlugin getHttpPlugin() {
return httpPlugin;
}
private void setHttpPlugin(HttpPlugin httpPlugin) {
this.httpPlugin = httpPlugin;
}
public TestHttpPlugin() {
this.setHttpPlugin(new HttpPlugin());
}
@Test
public void testGet() {
PluginReturn return1 = this
.getHttpPlugin()
.get("http://www.baidu.com/su?wd=&cb=window.bdsug.sugPreRequest&sid=4382_1435_4261_4588&t=1387332769213");
assertTrue(return1.isSuccess());
}
}
package org.bench4q.agent.test.plugin;
import org.bench4q.agent.plugin.basic.HttpPlugin;
import org.bench4q.agent.plugin.result.PluginReturn;
import org.junit.Test;
import static org.junit.Assert.*;
public class TestHttpPlugin {
private HttpPlugin httpPlugin;
private HttpPlugin getHttpPlugin() {
return httpPlugin;
}
private void setHttpPlugin(HttpPlugin httpPlugin) {
this.httpPlugin = httpPlugin;
}
public TestHttpPlugin() {
this.setHttpPlugin(new HttpPlugin());
}
@Test
public void testGet() {
PluginReturn return1 = this.getHttpPlugin().get(
"http://www.baidu.com/s", "wd=ok", "");
assertTrue(return1.isSuccess());
}
}