deal with the bug within the request body
This commit is contained in:
parent
c7220e919e
commit
61895272b0
|
@ -1,216 +1,219 @@
|
|||
package org.bench4q.master.scriptrecord.httpcapture;
|
||||
|
||||
import java.io.StringWriter;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import javax.xml.bind.JAXBContext;
|
||||
import javax.xml.bind.JAXBException;
|
||||
import javax.xml.bind.Marshaller;
|
||||
|
||||
import org.apache.log4j.Logger;
|
||||
import org.bench4q.master.exception.ExceptionLog;
|
||||
import org.bench4q.master.helper.RunScenarioModelHelper;
|
||||
import org.bench4q.master.scriptrecord.httpcapture.generator.ChildrenUrl;
|
||||
import org.bench4q.share.helper.MarshalHelper;
|
||||
import org.bench4q.share.models.agent.ParameterModel;
|
||||
import org.bench4q.share.models.agent.RunScenarioModel;
|
||||
import org.bench4q.share.models.agent.scriptrecord.BatchModel;
|
||||
import org.bench4q.share.models.agent.scriptrecord.BehaviorModel;
|
||||
import org.bench4q.share.models.agent.scriptrecord.PageModel;
|
||||
import org.bench4q.share.models.agent.scriptrecord.UsePluginModel;
|
||||
|
||||
public class Bench4qTestScriptAdapter implements IScriptAdapter {
|
||||
private int pageCount;
|
||||
private RunScenarioModel runScenarioModel;
|
||||
private List<ChildrenUrl> childrenUrls = new ArrayList<ChildrenUrl>();
|
||||
private static Logger logger = Logger
|
||||
.getLogger(Bench4qTestScriptAdapter.class);
|
||||
|
||||
public RunScenarioModel getRunScenarioModel() {
|
||||
return runScenarioModel;
|
||||
}
|
||||
|
||||
private void setRunScenarioModel(RunScenarioModel runScenarioModel) {
|
||||
this.runScenarioModel = runScenarioModel;
|
||||
}
|
||||
|
||||
public List<ChildrenUrl> getChildrenUrls() {
|
||||
return childrenUrls;
|
||||
}
|
||||
|
||||
private void setChildrenUrls(List<ChildrenUrl> childrenUrls) {
|
||||
this.childrenUrls = childrenUrls;
|
||||
}
|
||||
|
||||
private int getPageCount() {
|
||||
return pageCount;
|
||||
}
|
||||
|
||||
private void setPageCount(int pageCount) {
|
||||
this.pageCount = pageCount;
|
||||
}
|
||||
|
||||
public Bench4qTestScriptAdapter(RunScenarioModel runScenarioModel) {
|
||||
this.runScenarioModel = runScenarioModel;
|
||||
this.setChildrenUrls(new ArrayList<ChildrenUrl>());
|
||||
this.setPageCount(0);
|
||||
initWithOnePage();
|
||||
}
|
||||
|
||||
private void initWithOnePage() {
|
||||
addPage();
|
||||
}
|
||||
|
||||
public void appendUsePluginsToScenario(List<UsePluginModel> usePluginModels) {
|
||||
this.runScenarioModel.setUsePlugins(usePluginModels);
|
||||
}
|
||||
|
||||
public void addPage() {
|
||||
this.setPageCount(this.getPageCount() + 1);
|
||||
this.getRunScenarioModel().getPages().add(new PageModel());
|
||||
assert (pageCountEqualWithPageSizeInScenario());
|
||||
}
|
||||
|
||||
public void insertUserBehaviorsToScenario(BehaviorModel model) {
|
||||
List<BatchModel> batches = this.getCurrentPage().getBatches();
|
||||
int parentBatchId = -1;
|
||||
assert (batches != null);
|
||||
parentBatchId = getUrlParentBatch(model);
|
||||
if (isIndependent(parentBatchId)) {
|
||||
BatchModel batch = createBatchBehaviorWithProperBatchId();
|
||||
batch.getBehaviors().add(model);
|
||||
batches.add(batch);
|
||||
return;
|
||||
}
|
||||
guardChildBatchExist(batches, parentBatchId);
|
||||
batches.get(batches.get(parentBatchId).getChildId()).getBehaviors()
|
||||
.add(model);
|
||||
}
|
||||
|
||||
private void guardChildBatchExist(List<BatchModel> batches,
|
||||
int parentBatchId) {
|
||||
if (isChildBatchAbsent(batches, parentBatchId)) {
|
||||
BatchModel batchBehavior = createBatchBehaviorWithProperBatchId();
|
||||
batchBehavior.setParentId(parentBatchId);
|
||||
batches.add(batchBehavior);
|
||||
batches.get(parentBatchId).setChildId(batches.size() - 1);
|
||||
}
|
||||
}
|
||||
|
||||
private PageModel getCurrentPage() {
|
||||
if (!pageCountEqualWithPageSizeInScenario()) {
|
||||
logger.error("The page count is not equal with the size of scenario pages, and the page count is"
|
||||
+ this.getPageCount()
|
||||
+ " , and pageSize is "
|
||||
+ this.getRunScenarioModel().getPages().size());
|
||||
return new PageModel();
|
||||
}
|
||||
return this.getRunScenarioModel().getPages()
|
||||
.get(this.getPageCount() - 1);
|
||||
}
|
||||
|
||||
private boolean pageCountEqualWithPageSizeInScenario() {
|
||||
return this.getPageCount() == this.getRunScenarioModel().getPages()
|
||||
.size();
|
||||
}
|
||||
|
||||
private BatchModel createBatchBehaviorWithProperBatchId() {
|
||||
BatchModel batchBehavior = new BatchModel();
|
||||
batchBehavior.setId(RunScenarioModelHelper.getBatches(
|
||||
this.runScenarioModel).size());
|
||||
batchBehavior.setParentId(-1);
|
||||
batchBehavior.setChildId(-1);
|
||||
List<BehaviorModel> behaviors = new ArrayList<BehaviorModel>();
|
||||
batchBehavior.setBehaviors(behaviors);
|
||||
return batchBehavior;
|
||||
}
|
||||
|
||||
private boolean isChildBatchAbsent(List<BatchModel> batches,
|
||||
int parentBatchId) {
|
||||
return batches.get(parentBatchId).getChildId() < 0;
|
||||
}
|
||||
|
||||
private boolean isIndependent(int parentBatchId) {
|
||||
return parentBatchId < 0;
|
||||
}
|
||||
|
||||
public boolean isInChildrenUrl(String url) {
|
||||
for (ChildrenUrl childrenUrl : this.getChildrenUrls()) {
|
||||
if (childrenUrl.getUrl().equals(url)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private int getUrlParentBatch(BehaviorModel model) {
|
||||
int parentBatchId = -1;
|
||||
for (ParameterModel parameter : model.getParameters()) {
|
||||
if (!parameter.getKey().equals("url")) {
|
||||
continue;
|
||||
}
|
||||
parentBatchId = getParentBatchIdWithChildUrl(parameter.getValue());
|
||||
}
|
||||
return parentBatchId;
|
||||
}
|
||||
|
||||
private int getParentBatchIdWithChildUrl(String url) {
|
||||
for (ChildrenUrl childrenUrl : this.getChildrenUrls()) {
|
||||
if (childrenUrl.getUrl().equals(url)) {
|
||||
return childrenUrl.getParentBatchId();
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
public int getParentBatchIdWithParentUrl(String url) {
|
||||
List<BatchModel> batchesInScenario = RunScenarioModelHelper
|
||||
.getBatches(this.getRunScenarioModel());
|
||||
for (int batchId = 0; batchId < batchesInScenario.size(); batchId++) {
|
||||
BatchModel batch = batchesInScenario.get(batchId);
|
||||
for (BehaviorModel behavior : batch.getBehaviors()) {
|
||||
for (ParameterModel parameter : behavior.getParameters()) {
|
||||
if (parameter.getKey().equals("url")
|
||||
&& parameter.getValue().equals(url)) {
|
||||
return batchId;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
public void resetChildrenUrls() {
|
||||
this.getChildrenUrls().clear();
|
||||
}
|
||||
|
||||
public String getText() {
|
||||
StringWriter stringWriter = new StringWriter();
|
||||
try {
|
||||
Marshaller marshaller = JAXBContext.newInstance(
|
||||
this.runScenarioModel.getClass()).createMarshaller();
|
||||
marshaller.marshal(this.runScenarioModel, stringWriter);
|
||||
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
|
||||
} catch (JAXBException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
return stringWriter.toString();
|
||||
}
|
||||
|
||||
public void setText(String text) {
|
||||
if (text == null || text.isEmpty()) {
|
||||
// this.setRunScenarioModel(new RunScenarioModelNew());
|
||||
return;
|
||||
}
|
||||
try {
|
||||
this.setRunScenarioModel((RunScenarioModel) MarshalHelper
|
||||
.unmarshal(RunScenarioModel.class, text));
|
||||
} catch (JAXBException e) {
|
||||
logger.error(ExceptionLog.getStackTrace(e));
|
||||
this.setRunScenarioModel(new RunScenarioModel());
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
package org.bench4q.master.scriptrecord.httpcapture;
|
||||
|
||||
import java.io.StringWriter;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import javax.xml.bind.JAXBContext;
|
||||
import javax.xml.bind.JAXBException;
|
||||
import javax.xml.bind.Marshaller;
|
||||
|
||||
import org.apache.log4j.Logger;
|
||||
import org.bench4q.master.exception.ExceptionLog;
|
||||
import org.bench4q.master.helper.RunScenarioModelHelper;
|
||||
import org.bench4q.master.scriptrecord.httpcapture.generator.ChildrenUrl;
|
||||
import org.bench4q.share.helper.MarshalHelper;
|
||||
import org.bench4q.share.models.agent.ParameterModel;
|
||||
import org.bench4q.share.models.agent.RunScenarioModel;
|
||||
import org.bench4q.share.models.agent.scriptrecord.BatchModel;
|
||||
import org.bench4q.share.models.agent.scriptrecord.BehaviorModel;
|
||||
import org.bench4q.share.models.agent.scriptrecord.PageModel;
|
||||
import org.bench4q.share.models.agent.scriptrecord.UsePluginModel;
|
||||
|
||||
public class Bench4qTestScriptAdapter implements IScriptAdapter {
|
||||
private int pageCount;
|
||||
private RunScenarioModel runScenarioModel;
|
||||
private List<ChildrenUrl> childrenUrls = new ArrayList<ChildrenUrl>();
|
||||
private static Logger logger = Logger
|
||||
.getLogger(Bench4qTestScriptAdapter.class);
|
||||
|
||||
public RunScenarioModel getRunScenarioModel() {
|
||||
return runScenarioModel;
|
||||
}
|
||||
|
||||
private void setRunScenarioModel(RunScenarioModel runScenarioModel) {
|
||||
this.runScenarioModel = runScenarioModel;
|
||||
}
|
||||
|
||||
public List<ChildrenUrl> getChildrenUrls() {
|
||||
return childrenUrls;
|
||||
}
|
||||
|
||||
private void setChildrenUrls(List<ChildrenUrl> childrenUrls) {
|
||||
this.childrenUrls = childrenUrls;
|
||||
}
|
||||
|
||||
private int getPageCount() {
|
||||
return pageCount;
|
||||
}
|
||||
|
||||
private void setPageCount(int pageCount) {
|
||||
this.pageCount = pageCount;
|
||||
}
|
||||
|
||||
public Bench4qTestScriptAdapter(RunScenarioModel runScenarioModel) {
|
||||
this.runScenarioModel = runScenarioModel;
|
||||
this.setChildrenUrls(new ArrayList<ChildrenUrl>());
|
||||
this.setPageCount(0);
|
||||
initWithOnePage();
|
||||
}
|
||||
|
||||
private void initWithOnePage() {
|
||||
addPage();
|
||||
}
|
||||
|
||||
public void appendUsePluginsToScenario(List<UsePluginModel> usePluginModels) {
|
||||
this.runScenarioModel.setUsePlugins(usePluginModels);
|
||||
}
|
||||
|
||||
public void addPage() {
|
||||
this.setPageCount(this.getPageCount() + 1);
|
||||
this.getRunScenarioModel().getPages().add(new PageModel());
|
||||
assert (pageCountEqualWithPageSizeInScenario());
|
||||
}
|
||||
|
||||
public void insertUserBehaviorsToScenario(BehaviorModel model) {
|
||||
List<BatchModel> batches = this.getCurrentPage().getBatches();
|
||||
int parentBatchId = -1;
|
||||
assert (batches != null);
|
||||
parentBatchId = getUrlParentBatch(model);
|
||||
if (isIndependent(parentBatchId)) {
|
||||
BatchModel batch = createBatchBehaviorWithProperBatchId();
|
||||
batch.getBehaviors().add(model);
|
||||
batches.add(batch);
|
||||
return;
|
||||
}
|
||||
guardChildBatchExist(batches, parentBatchId);
|
||||
batches.get(batches.get(parentBatchId).getChildId()).getBehaviors()
|
||||
.add(model);
|
||||
}
|
||||
|
||||
private void guardChildBatchExist(List<BatchModel> batches,
|
||||
int parentBatchId) {
|
||||
if (isChildBatchAbsent(batches, parentBatchId)) {
|
||||
BatchModel batchBehavior = createBatchBehaviorWithProperBatchId();
|
||||
batchBehavior.setParentId(parentBatchId);
|
||||
batches.add(batchBehavior);
|
||||
batches.get(parentBatchId).setChildId(batches.size() - 1);
|
||||
}
|
||||
}
|
||||
|
||||
private PageModel getCurrentPage() {
|
||||
if (!pageCountEqualWithPageSizeInScenario()) {
|
||||
logger.error("The page count is not equal with the size of scenario pages, and the page count is"
|
||||
+ this.getPageCount()
|
||||
+ " , and pageSize is "
|
||||
+ this.getRunScenarioModel().getPages().size());
|
||||
return new PageModel();
|
||||
}
|
||||
return this.getRunScenarioModel().getPages()
|
||||
.get(this.getPageCount() - 1);
|
||||
}
|
||||
|
||||
private boolean pageCountEqualWithPageSizeInScenario() {
|
||||
return this.getPageCount() == this.getRunScenarioModel().getPages()
|
||||
.size();
|
||||
}
|
||||
|
||||
private BatchModel createBatchBehaviorWithProperBatchId() {
|
||||
BatchModel batchBehavior = new BatchModel();
|
||||
batchBehavior.setId(RunScenarioModelHelper.getBatches(
|
||||
this.runScenarioModel).size());
|
||||
batchBehavior.setParentId(-1);
|
||||
batchBehavior.setChildId(-1);
|
||||
List<BehaviorModel> behaviors = new ArrayList<BehaviorModel>();
|
||||
batchBehavior.setBehaviors(behaviors);
|
||||
return batchBehavior;
|
||||
}
|
||||
|
||||
private boolean isChildBatchAbsent(List<BatchModel> batches,
|
||||
int parentBatchId) {
|
||||
if (parentBatchId >= batches.size()) {
|
||||
return false;
|
||||
}
|
||||
return batches.get(parentBatchId).getChildId() < 0;
|
||||
}
|
||||
|
||||
private boolean isIndependent(int parentBatchId) {
|
||||
return parentBatchId < 0;
|
||||
}
|
||||
|
||||
public boolean isInChildrenUrl(String url) {
|
||||
for (ChildrenUrl childrenUrl : this.getChildrenUrls()) {
|
||||
if (childrenUrl.getUrl().equals(url)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private int getUrlParentBatch(BehaviorModel model) {
|
||||
int parentBatchId = -1;
|
||||
for (ParameterModel parameter : model.getParameters()) {
|
||||
if (!parameter.getKey().equals("url")) {
|
||||
continue;
|
||||
}
|
||||
parentBatchId = getParentBatchIdWithChildUrl(parameter.getValue());
|
||||
}
|
||||
return parentBatchId;
|
||||
}
|
||||
|
||||
private int getParentBatchIdWithChildUrl(String url) {
|
||||
for (ChildrenUrl childrenUrl : this.getChildrenUrls()) {
|
||||
if (childrenUrl.getUrl().equals(url)) {
|
||||
return childrenUrl.getParentBatchId();
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
public int getParentBatchIdWithParentUrl(String url) {
|
||||
List<BatchModel> batchesInScenario = RunScenarioModelHelper
|
||||
.getBatches(this.getRunScenarioModel());
|
||||
for (int batchId = 0; batchId < batchesInScenario.size(); batchId++) {
|
||||
BatchModel batch = batchesInScenario.get(batchId);
|
||||
for (BehaviorModel behavior : batch.getBehaviors()) {
|
||||
for (ParameterModel parameter : behavior.getParameters()) {
|
||||
if (parameter.getKey().equals("url")
|
||||
&& parameter.getValue().equals(url)) {
|
||||
return batchId;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
public void resetChildrenUrls() {
|
||||
this.getChildrenUrls().clear();
|
||||
}
|
||||
|
||||
public String getText() {
|
||||
StringWriter stringWriter = new StringWriter();
|
||||
try {
|
||||
Marshaller marshaller = JAXBContext.newInstance(
|
||||
this.runScenarioModel.getClass()).createMarshaller();
|
||||
marshaller.marshal(this.runScenarioModel, stringWriter);
|
||||
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
|
||||
} catch (JAXBException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
return stringWriter.toString();
|
||||
}
|
||||
|
||||
public void setText(String text) {
|
||||
if (text == null || text.isEmpty()) {
|
||||
// this.setRunScenarioModel(new RunScenarioModelNew());
|
||||
return;
|
||||
}
|
||||
try {
|
||||
this.setRunScenarioModel((RunScenarioModel) MarshalHelper
|
||||
.unmarshal(RunScenarioModel.class, text));
|
||||
} catch (JAXBException e) {
|
||||
logger.error(ExceptionLog.getStackTrace(e));
|
||||
this.setRunScenarioModel(new RunScenarioModel());
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -1,135 +1,287 @@
|
|||
package org.bench4q.master.scriptrecord.httpcapture;
|
||||
|
||||
import org.apache.commons.logging.Log;
|
||||
import org.apache.commons.logging.LogFactory;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.util.StringTokenizer;
|
||||
|
||||
import org.apache.http.Header;
|
||||
import org.apache.http.HttpException;
|
||||
import org.apache.http.HttpRequest;
|
||||
import org.apache.http.impl.io.DefaultHttpRequestParser;
|
||||
import org.apache.http.impl.io.HttpTransportMetricsImpl;
|
||||
import org.apache.http.impl.io.SessionInputBufferImpl;
|
||||
import org.apache.log4j.Logger;
|
||||
import org.bench4q.master.exception.ExceptionLog;
|
||||
|
||||
/**
|
||||
* Parses and stores a http server request. Originally posted to comp.lang.java
|
||||
* in 1996.
|
||||
*
|
||||
* @author Sherman Janes
|
||||
*/
|
||||
public class HttpRequestHeader {
|
||||
private static final Logger log = Logger.getLogger(HttpRequestHeader.class);
|
||||
|
||||
public String charset = new String();
|
||||
private static final Log log = LogFactory.getLog(HttpRequestHeader.class);
|
||||
|
||||
/**
|
||||
* Http Request method. Such as get or post.
|
||||
*/
|
||||
public String method = new String();
|
||||
|
||||
/**
|
||||
* The requested url. The universal resource locator that hopefully uniquely
|
||||
* describes the object or service the client is requesting.
|
||||
*/
|
||||
public String url = new String();
|
||||
|
||||
/**
|
||||
* Version of http being used. Such as HTTP/1.0
|
||||
*/
|
||||
public String version = new String();
|
||||
/**
|
||||
* to support http 1.1
|
||||
*/
|
||||
public String host = new String();
|
||||
|
||||
public String version = new String();
|
||||
|
||||
/**
|
||||
* The client's browser's name.
|
||||
*/
|
||||
public String userAgent = new String();
|
||||
|
||||
/**
|
||||
* The requesting documents that contained the url link.
|
||||
*/
|
||||
public String referer = new String();
|
||||
|
||||
/**
|
||||
* A internet address date of the remote copy.
|
||||
*/
|
||||
public String ifModifiedSince = new String();
|
||||
|
||||
/**
|
||||
* A list of mime types the client can accept.
|
||||
*/
|
||||
public String accept = new String();
|
||||
|
||||
/**
|
||||
* The clients authorization. Don't belive it.
|
||||
*/
|
||||
public String authorization = new String();
|
||||
|
||||
/**
|
||||
* The type of content following the request header. Normally there is no
|
||||
* content and this is blank, however the post method usually does have a
|
||||
* content and a content length.
|
||||
*/
|
||||
public String contentType = new String();
|
||||
|
||||
/**
|
||||
* The length of the content following the header. Usually blank.
|
||||
*/
|
||||
public int contentLength = -1;
|
||||
|
||||
/**
|
||||
* The content length of a remote copy of the requested object.
|
||||
*/
|
||||
public int oldContentLength = -1;
|
||||
|
||||
/**
|
||||
* Anything in the header that was unrecognized by this class.
|
||||
*/
|
||||
public String unrecognized = new String();
|
||||
|
||||
/**
|
||||
* Indicates that no cached versions of the requested object are to be sent.
|
||||
* Usually used to tell proxy not to send a cached copy. This may also
|
||||
* effect servers that are front end for data bases.
|
||||
*/
|
||||
public boolean pragmaNoCache = false;
|
||||
|
||||
static final String CR = "\r\n";
|
||||
final static String CR = "\r\n";
|
||||
|
||||
private HttpRequest httpRequest;
|
||||
|
||||
private HttpRequest getHttpRequest() {
|
||||
return httpRequest;
|
||||
}
|
||||
|
||||
private void setHttpRequest(HttpRequest httpRequest) {
|
||||
this.httpRequest = httpRequest;
|
||||
}
|
||||
/**
|
||||
* That from which we read.
|
||||
*/
|
||||
private InputStream input;
|
||||
|
||||
/**
|
||||
* Parses a http header from a stream.
|
||||
*
|
||||
* @param in
|
||||
* The stream to parse.
|
||||
*/
|
||||
public HttpRequestHeader(InputStream in) throws IOException {
|
||||
SessionInputBufferImpl inputBuffer = new SessionInputBufferImpl(
|
||||
new HttpTransportMetricsImpl(), 1024);
|
||||
inputBuffer.bind(in);
|
||||
try {
|
||||
this.setHttpRequest(new DefaultHttpRequestParser(inputBuffer)
|
||||
.parse());
|
||||
input = in;
|
||||
/*
|
||||
* Read by lines
|
||||
*/
|
||||
StringTokenizer tz = new StringTokenizer(readLine());
|
||||
/*
|
||||
* HTTP COMMAND LINE < <METHOD==get> <URL> <HTTP_VERSION> >
|
||||
*/
|
||||
method = getToken(tz).toUpperCase();
|
||||
url = getToken(tz);
|
||||
version = getToken(tz);
|
||||
|
||||
this.url = this.httpRequest.getRequestLine().getUri();
|
||||
this.method = this.httpRequest.getRequestLine().getMethod();
|
||||
this.version = this.httpRequest.getRequestLine()
|
||||
.getProtocolVersion().toString();
|
||||
while (true) {
|
||||
String line = readLine();
|
||||
log.trace(line);
|
||||
tz = new StringTokenizer(line);
|
||||
String Token = getToken(tz);
|
||||
// look for termination of HTTP command
|
||||
if (0 == Token.length())
|
||||
break;
|
||||
if (Token.equalsIgnoreCase("Host:")) {
|
||||
// line = <Host: host description>
|
||||
host = getRemainder(tz);
|
||||
} else if (Token.equalsIgnoreCase("USER-AGENT:")) {
|
||||
// line =<User-Agent: <Agent Description>>
|
||||
userAgent = getRemainder(tz);
|
||||
} else if (Token.equalsIgnoreCase("ACCEPT:")) {
|
||||
// line=<Accept: <Type>/<Form>
|
||||
// examp: Accept image/jpeg
|
||||
accept += " " + getRemainder(tz);
|
||||
|
||||
this.accept = this.getHeaderValue(HeaderValue.REQUEST_ACCEPT);
|
||||
this.referer = this.getHeaderValue(HeaderValue.REQUEST_REFERER);
|
||||
this.userAgent = this
|
||||
.getHeaderValue(HeaderValue.REQUEST_USER_AGENT);
|
||||
this.ifModifiedSince = this.getHeaderValue("if-modified-since");
|
||||
this.authorization = this
|
||||
.getHeaderValue(HeaderValue.REQUEST_AUTHORIZATION);
|
||||
this.contentType = this
|
||||
.getHeaderValue(HeaderValue.ENTITY_CONTENT_TYPE);
|
||||
this.pragmaNoCache = this
|
||||
.getHeaderValue(HeaderValue.GENERAL_PRAGMA)
|
||||
.equalsIgnoreCase("NO-CACHE");
|
||||
this.host = this.getHeaderValue(HeaderValue.REQUEST_HOST);
|
||||
if (this.getHttpRequest().containsHeader(
|
||||
HeaderValue.ENTITY_CONTENT_LENGHT)) {
|
||||
this.contentLength = Integer.parseInt(this.httpRequest
|
||||
.getFirstHeader(HeaderValue.ENTITY_CONTENT_LENGHT)
|
||||
.getValue());
|
||||
} else if (Token.equalsIgnoreCase("REFERER:")) {
|
||||
// line =<Referer: <URL>>
|
||||
referer = getRemainder(tz);
|
||||
|
||||
} else if (Token.equalsIgnoreCase("PRAGMA:")) {
|
||||
// Pragma: <no-cache>
|
||||
Token = getToken(tz);
|
||||
|
||||
if (Token.equalsIgnoreCase("NO-CACHE"))
|
||||
pragmaNoCache = true;
|
||||
else
|
||||
unrecognized += "Pragma:" + Token + " " + getRemainder(tz)
|
||||
+ "\n";
|
||||
} else if (Token.equalsIgnoreCase("AUTHORIZATION:")) {
|
||||
// Authenticate: Basic UUENCODED
|
||||
authorization = getRemainder(tz);
|
||||
|
||||
} else if (Token.equalsIgnoreCase("IF-MODIFIED-SINCE:")) {
|
||||
// line =<If-Modified-Since: <http date>
|
||||
// *** Conditional GET replaces HEAD method ***
|
||||
String str = getRemainder(tz);
|
||||
int index = str.indexOf(";");
|
||||
if (index == -1) {
|
||||
ifModifiedSince = str;
|
||||
} else {
|
||||
ifModifiedSince = str.substring(0, index);
|
||||
|
||||
index = str.indexOf("=");
|
||||
if (index != -1) {
|
||||
str = str.substring(index + 1);
|
||||
oldContentLength = Integer.parseInt(str);
|
||||
}
|
||||
}
|
||||
} else if (Token.equalsIgnoreCase("CONTENT-LENGTH:")) {
|
||||
Token = getToken(tz);
|
||||
contentLength = Integer.parseInt(Token);
|
||||
} else if (Token.equalsIgnoreCase("CONTENT-TYPE:")) {
|
||||
contentType = getRemainder(tz);
|
||||
} else {
|
||||
this.contentLength = 0;
|
||||
unrecognized += Token + " " + getRemainder(tz) + CR;
|
||||
}
|
||||
} catch (IOException e) {
|
||||
throw e;
|
||||
} catch (HttpException e) {
|
||||
log.error(ExceptionLog.getStackTrace(e));
|
||||
} catch (NumberFormatException e) {
|
||||
log.error(ExceptionLog.getStackTrace(e));
|
||||
}
|
||||
}
|
||||
|
||||
public boolean containsHeader(String name) {
|
||||
return this.getHttpRequest().containsHeader(name);
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param name
|
||||
* @return if contains this header return the header's value; if not return
|
||||
* ""
|
||||
* We would like to use BufferedReader.readLine(), but it may read past the
|
||||
* header while filling its buffer. Anything it over-read would thus be
|
||||
* missed from the body. (Reading the body cannot be via a Reader- derived
|
||||
* class because we do not want to do any character set conversion at this
|
||||
* stage. It might be binary data!)
|
||||
*/
|
||||
public String getHeaderValue(String name) {
|
||||
if (!this.containsHeader(name)) {
|
||||
return "";
|
||||
String readLine() throws IOException {
|
||||
int c;
|
||||
StringBuffer sb = new StringBuffer();
|
||||
while ((c = input.read()) != '\n') {
|
||||
if (c == -1)
|
||||
throw new IOException("unterminated line in request header");
|
||||
sb.append((char) c);
|
||||
}
|
||||
return this.getHttpRequest().getFirstHeader(name).getValue();
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
/*
|
||||
* Rebuilds the header in a string
|
||||
*
|
||||
* @return The header in a string.
|
||||
*/
|
||||
public String toString(boolean sendUnknowen) {
|
||||
String Request;
|
||||
|
||||
if (0 == method.length())
|
||||
method = "GET";
|
||||
|
||||
Request = method + " " + url + " " + version + CR;
|
||||
|
||||
if (0 < host.length()) {
|
||||
Request += "Host:" + host + CR;
|
||||
}
|
||||
if (0 < userAgent.length())
|
||||
Request += "User-Agent:" + userAgent + CR;
|
||||
|
||||
if (0 < referer.length())
|
||||
Request += "Referer:" + referer + CR;
|
||||
|
||||
if (pragmaNoCache)
|
||||
Request += "Pragma: no-cache" + CR;
|
||||
|
||||
if (0 < ifModifiedSince.length())
|
||||
Request += "If-Modified-Since: " + ifModifiedSince + CR;
|
||||
|
||||
// ACCEPT TYPES //
|
||||
if (0 < accept.length())
|
||||
Request += "Accept: " + accept + CR;
|
||||
else
|
||||
Request += "Accept: */" + "* \r\n";
|
||||
|
||||
if (0 < contentType.length())
|
||||
Request += "Content-Type: " + contentType + CR;
|
||||
|
||||
if (0 < contentLength)
|
||||
Request += "Content-Length: " + contentLength + CR;
|
||||
|
||||
if (0 != authorization.length())
|
||||
Request += "Authorization: " + authorization + CR;
|
||||
|
||||
if (sendUnknowen) {
|
||||
if (0 != unrecognized.length())
|
||||
Request += unrecognized;
|
||||
}
|
||||
|
||||
Request += CR;
|
||||
|
||||
return Request;
|
||||
}
|
||||
|
||||
/**
|
||||
* (Re)builds the header in a string.
|
||||
*
|
||||
* @return The header in a string.
|
||||
*/
|
||||
public String toString() {
|
||||
return toStringWithLib();
|
||||
return toString(true);
|
||||
}
|
||||
|
||||
public String toStringWithLib() {
|
||||
String result = this.getHttpRequest().getRequestLine().toString();
|
||||
for (Header header : this.getHttpRequest().getAllHeaders()) {
|
||||
result += CR + header.getName() + ": " + header.getValue();
|
||||
/**
|
||||
* Returns the next token in a string
|
||||
*
|
||||
* @param tk
|
||||
* String that is partially tokenized.
|
||||
* @return The remainder
|
||||
*/
|
||||
String getToken(StringTokenizer tk) {
|
||||
String str = "";
|
||||
if (tk.hasMoreTokens())
|
||||
str = tk.nextToken();
|
||||
return str;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the remainder of a tokenized string
|
||||
*
|
||||
* @param tk
|
||||
* String that is partially tokenized.
|
||||
* @return The remainder
|
||||
*/
|
||||
String getRemainder(StringTokenizer tk) {
|
||||
String str = "";
|
||||
if (tk.hasMoreTokens())
|
||||
str = tk.nextToken();
|
||||
while (tk.hasMoreTokens()) {
|
||||
str += " " + tk.nextToken();
|
||||
}
|
||||
result += CR + CR;
|
||||
return result;
|
||||
return str;
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
@ -1,198 +1,214 @@
|
|||
package org.bench4q.master.scriptrecord.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.log4j.Logger;
|
||||
import org.bench4q.master.exception.ExceptionLog;
|
||||
|
||||
public class RequestHandler implements Runnable {
|
||||
private static final Logger log = Logger.getLogger(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();
|
||||
|
||||
public 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.error("truncated request from browser: "
|
||||
+ ExceptionLog.getStackTrace(e).toString()
|
||||
+ this.header.url);
|
||||
throw new Utils.SilentException();
|
||||
}
|
||||
if (!this.header.url.startsWith("http"))
|
||||
throw new Utils.UserException(
|
||||
"Bench4Q only supports the HTTP protocol.");
|
||||
URL url = new URL(this.header.url);
|
||||
|
||||
Config.ProxySettings proxy = this.config.getProxySettings();
|
||||
int port;
|
||||
String host;
|
||||
if (proxy != null) {
|
||||
host = proxy.host;
|
||||
port = proxy.port;
|
||||
} else {
|
||||
host = url.getHost();
|
||||
port = url.getPort();
|
||||
}
|
||||
|
||||
if (port < 1)
|
||||
port = 80;
|
||||
try {
|
||||
this.serverSocket = new Socket(InetAddress.getByName(host), port);
|
||||
} catch (ConnectException e) {
|
||||
String msg = "Cannot connect to ";
|
||||
if (proxy != null)
|
||||
msg = msg + "proxy server ";
|
||||
msg = msg + host;
|
||||
if (port != 80)
|
||||
msg = msg + " on port " + Integer.toString(port);
|
||||
throw new Utils.UserException(msg + ".");
|
||||
}
|
||||
try {
|
||||
this.serverIn = this.serverSocket.getInputStream();
|
||||
this.serverOut = this.serverSocket.getOutputStream();
|
||||
} catch (Throwable e) {
|
||||
this.serverSocket.close();
|
||||
this.serverSocket = null;
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
private String stripProxyInfoFromRequestHeader()
|
||||
throws MalformedURLException {
|
||||
String res = "";
|
||||
String origUrl = this.header.url;
|
||||
URL url = new URL(origUrl);
|
||||
this.header.url = url.getFile();
|
||||
res = this.header.toString();
|
||||
this.header.url = origUrl;
|
||||
return res;
|
||||
}
|
||||
|
||||
public void run() {
|
||||
try {
|
||||
try {
|
||||
int rs = this.clientSocket.getReceiveBufferSize();
|
||||
int ss = this.clientSocket.getSendBufferSize();
|
||||
int BUF_SIZE = rs < ss ? ss : rs;
|
||||
|
||||
byte[] buf = new byte[BUF_SIZE];
|
||||
|
||||
initClientServerConnections(this.clientSocket);
|
||||
String headerStr;
|
||||
if (this.config.getProxySettings() == null)
|
||||
headerStr = stripProxyInfoFromRequestHeader();
|
||||
else
|
||||
headerStr = this.header.toString();
|
||||
log.trace("read request header");
|
||||
|
||||
byte[] bytes = headerStr.getBytes();
|
||||
this.serverOut.write(bytes, 0, bytes.length);
|
||||
|
||||
log.trace("wrote request header");
|
||||
byte[] requestBody;
|
||||
if (this.header.contentLength > 0) {
|
||||
this.buffer.reset();
|
||||
int len = 0;
|
||||
int num = 0;
|
||||
while (num < this.header.contentLength) {
|
||||
try {
|
||||
len = this.clientIn.read(buf, 0, buf.length);
|
||||
} catch (SocketException e) {
|
||||
log.info("truncated request from browser: "
|
||||
+ e.getMessage());
|
||||
throw new Utils.SilentException();
|
||||
}
|
||||
if (len == 0)
|
||||
break;
|
||||
log.trace("read " + Integer.toString(len) + " bytes");
|
||||
this.serverOut.write(buf, 0, len);
|
||||
this.buffer.write(buf, 0, len);
|
||||
log.trace("wrote " + Integer.toString(len) + " bytes");
|
||||
num += len;
|
||||
}
|
||||
requestBody = this.buffer.toByteArray();
|
||||
log.trace("transferred rest of request body");
|
||||
} else {
|
||||
requestBody = new byte[0];
|
||||
log.trace("no request body");
|
||||
}
|
||||
|
||||
this.clientSocket.shutdownInput();
|
||||
|
||||
this.serverSocket.shutdownOutput();
|
||||
|
||||
synchronized (mutex) {
|
||||
this.proxyServer.processRequest(this.header, requestBody);
|
||||
log.trace("processed request");
|
||||
|
||||
this.buffer.reset();
|
||||
int len;
|
||||
while ((len = this.serverIn.read(buf, 0, buf.length)) > 0) {
|
||||
log.trace("read " + Integer.toString(len));
|
||||
try {
|
||||
this.clientOut.write(buf, 0, len);
|
||||
} catch (SocketException e) {
|
||||
log.info("browser stopped listening: "
|
||||
+ e.getMessage() + this.buffer.toString());
|
||||
throw new Utils.SilentException();
|
||||
}
|
||||
this.buffer.write(buf, 0, len);
|
||||
}
|
||||
log.trace("transferred response len:" + len);
|
||||
|
||||
this.proxyServer.processResponse(this.header, requestBody,
|
||||
this.buffer.toByteArray());
|
||||
log.trace("processed response");
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error(ExceptionLog.getStackTrace(e));
|
||||
} 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) {
|
||||
log.error(ExceptionLog.getStackTrace(localThrowable));
|
||||
}
|
||||
}
|
||||
}
|
||||
package org.bench4q.master.scriptrecord.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.log4j.Logger;
|
||||
import org.bench4q.master.exception.ExceptionLog;
|
||||
|
||||
public class RequestHandler implements Runnable {
|
||||
private static final Logger log = Logger.getLogger(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();
|
||||
|
||||
public 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.error("truncated request from browser: "
|
||||
+ ExceptionLog.getStackTrace(e).toString()
|
||||
+ this.header.url);
|
||||
throw new Utils.SilentException();
|
||||
}
|
||||
if (!this.header.url.startsWith("http"))
|
||||
throw new Utils.UserException(
|
||||
"Bench4Q 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 = readRequestBody(buf);
|
||||
} catch (SocketException e) {
|
||||
log.info("truncated request from browser: "
|
||||
+ e.getMessage());
|
||||
throw new Utils.SilentException();
|
||||
}
|
||||
if (len == 0 || len == -1) {
|
||||
System.out.println("Read " + num
|
||||
+ "byte from requestBody");
|
||||
break;
|
||||
}
|
||||
log.trace("read " + Integer.toString(len) + " bytes");
|
||||
this.serverOut.write(buf, 0, len);
|
||||
this.buffer.write(buf, 0, len);
|
||||
log.trace("wrote " + Integer.toString(len) + " bytes");
|
||||
num += len;
|
||||
}
|
||||
requestBody = this.buffer.toByteArray();
|
||||
log.trace("transferred rest of request body");
|
||||
} else {
|
||||
requestBody = new byte[0];
|
||||
log.trace("no request body");
|
||||
}
|
||||
|
||||
this.clientSocket.shutdownInput();
|
||||
|
||||
this.serverSocket.shutdownOutput();
|
||||
|
||||
synchronized (mutex) {
|
||||
this.proxyServer.processRequest(this.header, requestBody);
|
||||
log.trace("processed request");
|
||||
|
||||
this.buffer.reset();
|
||||
int len;
|
||||
while ((len = this.serverIn.read(buf, 0, buf.length)) > 0) {
|
||||
log.trace("read " + Integer.toString(len));
|
||||
try {
|
||||
this.clientOut.write(buf, 0, len);
|
||||
} catch (SocketException e) {
|
||||
log.info("browser stopped listening: "
|
||||
+ e.getMessage() + this.buffer.toString());
|
||||
throw new Utils.SilentException();
|
||||
}
|
||||
this.buffer.write(buf, 0, len);
|
||||
}
|
||||
log.trace("transferred response len:" + len);
|
||||
|
||||
this.proxyServer.processResponse(this.header, requestBody,
|
||||
this.buffer.toByteArray());
|
||||
log.trace("processed response");
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error(ExceptionLog.getStackTrace(e));
|
||||
} 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) {
|
||||
log.error(ExceptionLog.getStackTrace(localThrowable));
|
||||
}
|
||||
}
|
||||
|
||||
private int readRequestBody(byte[] buf) throws IOException {
|
||||
int alreadyReadLength = 0;
|
||||
int ch = -1;
|
||||
while (alreadyReadLength < this.header.contentLength) {
|
||||
if ((ch = this.clientIn.read()) != -1) {
|
||||
buf[alreadyReadLength] = (byte) ch;
|
||||
}
|
||||
alreadyReadLength++;
|
||||
}
|
||||
return alreadyReadLength;
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,91 +1,91 @@
|
|||
package org.bench4q.master.test.controller;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import javax.xml.bind.JAXBException;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
import org.bench4q.share.communication.HttpRequester.HttpResponse;
|
||||
import org.bench4q.share.helper.MarshalHelper;
|
||||
import org.bench4q.share.models.agent.RunScenarioModel;
|
||||
import org.bench4q.share.models.master.OperateScriptServerResponseModel;
|
||||
import org.bench4q.share.models.master.ScriptModel;
|
||||
import org.junit.Test;
|
||||
|
||||
public class RecordScriptControllerTest extends TestBase {
|
||||
private static final int RECORD_TIME = 60000;
|
||||
private final String SCRIPT_URL = TestBase.BASE_URL + "/RecordScript";
|
||||
|
||||
public OperateScriptServerResponseModel startRecord() throws IOException,
|
||||
JAXBException {
|
||||
HttpResponse httpResponse = this.httpRequester.sendPost(this.SCRIPT_URL
|
||||
+ "/startScriptRecordServer", null,
|
||||
this.makeAccessTockenMap(this.getAccessTocken()));
|
||||
System.out.println(httpResponse.getContent());
|
||||
OperateScriptServerResponseModel ret = (OperateScriptServerResponseModel) MarshalHelper
|
||||
.unmarshal(OperateScriptServerResponseModel.class,
|
||||
httpResponse.getContent());
|
||||
assertTrue(ret.isSuccess());
|
||||
return ret;
|
||||
}
|
||||
|
||||
public void stopRecord(OperateScriptServerResponseModel model)
|
||||
throws IOException, JAXBException {
|
||||
Map<String, String> paramsMap = buildParams("port",
|
||||
String.valueOf(model.getPort()));
|
||||
paramsMap.put("fileNameUUID", model.getFileName());
|
||||
HttpResponse httpResponse = this.httpRequester.sendPost(this.SCRIPT_URL
|
||||
+ "/stopScriptRecordServer", paramsMap,
|
||||
this.makeAccessTockenMap(this.accessTocken));
|
||||
OperateScriptServerResponseModel ret = (OperateScriptServerResponseModel) MarshalHelper
|
||||
.unmarshal(OperateScriptServerResponseModel.class,
|
||||
httpResponse.getContent());
|
||||
assertTrue(ret.isSuccess());
|
||||
}
|
||||
|
||||
private Map<String, String> buildParams(String key, String value) {
|
||||
Map<String, String> params = new HashMap<String, String>();
|
||||
params.put(key, value);
|
||||
return params;
|
||||
}
|
||||
|
||||
public ScriptModel saveScriptToDB(OperateScriptServerResponseModel model,
|
||||
String scriptName) throws IOException, JAXBException {
|
||||
Map<String, String> params = new HashMap<String, String>();
|
||||
params.put("scriptName", scriptName);
|
||||
params.put("port", String.valueOf(model.getPort()));
|
||||
params.put("fileNameUUID", model.getFileName());
|
||||
HttpResponse httpResponse = this.httpRequester.sendPost(this.SCRIPT_URL
|
||||
+ "/saveScriptToDB", params,
|
||||
this.makeAccessTockenMap(this.getAccessTocken()));
|
||||
OperateScriptServerResponseModel ret = (OperateScriptServerResponseModel) MarshalHelper
|
||||
.unmarshal(OperateScriptServerResponseModel.class,
|
||||
httpResponse.getContent());
|
||||
assertTrue(ret.isSuccess());
|
||||
assertNotNull(ret.getScriptModels());
|
||||
assertNotNull(ret.getScriptModels().get(0));
|
||||
return ret.getScriptModels().get(0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testRecordScript() throws IOException, JAXBException,
|
||||
InterruptedException {
|
||||
RecordScriptControllerTest test = new RecordScriptControllerTest();
|
||||
test.accessTocken = test.login();
|
||||
Thread.sleep(1000);
|
||||
OperateScriptServerResponseModel model = test.startRecord();
|
||||
Thread.sleep(RECORD_TIME);
|
||||
System.out.println("Thread has waken up");
|
||||
test.stopRecord(model);
|
||||
ScriptModel scriptModel = test.saveScriptToDB(model, "chen2");
|
||||
assertNotNull(scriptModel.getScriptContent());
|
||||
RunScenarioModel runScenarioModel = (RunScenarioModel) MarshalHelper
|
||||
.unmarshal(RunScenarioModel.class,
|
||||
scriptModel.getScriptContent());
|
||||
assertNotNull(runScenarioModel);
|
||||
|
||||
}
|
||||
}
|
||||
package org.bench4q.master.test.controller;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import javax.xml.bind.JAXBException;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
import org.bench4q.share.communication.HttpRequester.HttpResponse;
|
||||
import org.bench4q.share.helper.MarshalHelper;
|
||||
import org.bench4q.share.models.agent.RunScenarioModel;
|
||||
import org.bench4q.share.models.master.OperateScriptServerResponseModel;
|
||||
import org.bench4q.share.models.master.ScriptModel;
|
||||
import org.junit.Test;
|
||||
|
||||
public class RecordScriptControllerTest extends TestBase {
|
||||
private static final int RECORD_TIME = 6000000;
|
||||
private final String SCRIPT_URL = TestBase.BASE_URL + "/RecordScript";
|
||||
|
||||
public OperateScriptServerResponseModel startRecord() throws IOException,
|
||||
JAXBException {
|
||||
HttpResponse httpResponse = this.httpRequester.sendPost(this.SCRIPT_URL
|
||||
+ "/startScriptRecordServer", null,
|
||||
this.makeAccessTockenMap(this.getAccessTocken()));
|
||||
System.out.println(httpResponse.getContent());
|
||||
OperateScriptServerResponseModel ret = (OperateScriptServerResponseModel) MarshalHelper
|
||||
.unmarshal(OperateScriptServerResponseModel.class,
|
||||
httpResponse.getContent());
|
||||
assertTrue(ret.isSuccess());
|
||||
return ret;
|
||||
}
|
||||
|
||||
public void stopRecord(OperateScriptServerResponseModel model)
|
||||
throws IOException, JAXBException {
|
||||
Map<String, String> paramsMap = buildParams("port",
|
||||
String.valueOf(model.getPort()));
|
||||
paramsMap.put("fileNameUUID", model.getFileName());
|
||||
HttpResponse httpResponse = this.httpRequester.sendPost(this.SCRIPT_URL
|
||||
+ "/stopScriptRecordServer", paramsMap,
|
||||
this.makeAccessTockenMap(this.accessTocken));
|
||||
OperateScriptServerResponseModel ret = (OperateScriptServerResponseModel) MarshalHelper
|
||||
.unmarshal(OperateScriptServerResponseModel.class,
|
||||
httpResponse.getContent());
|
||||
assertTrue(ret.isSuccess());
|
||||
}
|
||||
|
||||
private Map<String, String> buildParams(String key, String value) {
|
||||
Map<String, String> params = new HashMap<String, String>();
|
||||
params.put(key, value);
|
||||
return params;
|
||||
}
|
||||
|
||||
public ScriptModel saveScriptToDB(OperateScriptServerResponseModel model,
|
||||
String scriptName) throws IOException, JAXBException {
|
||||
Map<String, String> params = new HashMap<String, String>();
|
||||
params.put("scriptName", scriptName);
|
||||
params.put("port", String.valueOf(model.getPort()));
|
||||
params.put("fileNameUUID", model.getFileName());
|
||||
HttpResponse httpResponse = this.httpRequester.sendPost(this.SCRIPT_URL
|
||||
+ "/saveScriptToDB", params,
|
||||
this.makeAccessTockenMap(this.getAccessTocken()));
|
||||
OperateScriptServerResponseModel ret = (OperateScriptServerResponseModel) MarshalHelper
|
||||
.unmarshal(OperateScriptServerResponseModel.class,
|
||||
httpResponse.getContent());
|
||||
assertTrue(ret.isSuccess());
|
||||
assertNotNull(ret.getScriptModels());
|
||||
assertNotNull(ret.getScriptModels().get(0));
|
||||
return ret.getScriptModels().get(0);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testRecordScript() throws IOException, JAXBException,
|
||||
InterruptedException {
|
||||
RecordScriptControllerTest test = new RecordScriptControllerTest();
|
||||
test.accessTocken = test.login();
|
||||
Thread.sleep(1000);
|
||||
OperateScriptServerResponseModel model = test.startRecord();
|
||||
Thread.sleep(RECORD_TIME);
|
||||
System.out.println("Thread has waken up");
|
||||
test.stopRecord(model);
|
||||
ScriptModel scriptModel = test.saveScriptToDB(model, "chen2");
|
||||
assertNotNull(scriptModel.getScriptContent());
|
||||
RunScenarioModel runScenarioModel = (RunScenarioModel) MarshalHelper
|
||||
.unmarshal(RunScenarioModel.class,
|
||||
scriptModel.getScriptContent());
|
||||
assertNotNull(runScenarioModel);
|
||||
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,87 +1,86 @@
|
|||
package org.bench4q.master.test.recordscript;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileNotFoundException;
|
||||
import java.io.IOException;
|
||||
import java.net.URL;
|
||||
|
||||
import org.apache.commons.io.FileUtils;
|
||||
import org.apache.http.HttpException;
|
||||
import org.bench4q.master.scriptrecord.httpcapture.HttpRequestHeader;
|
||||
import org.junit.Test;
|
||||
|
||||
public class TestHttpRequestHeader {
|
||||
private static final String PATHNAME = TestCodeGenerator.dealWithSerie
|
||||
+ "Request.txt";
|
||||
private HttpRequestHeader requestHeader;
|
||||
|
||||
private HttpRequestHeader getRequestHeader() {
|
||||
return requestHeader;
|
||||
}
|
||||
|
||||
private void setRequestHeader(HttpRequestHeader requestHeader) {
|
||||
this.requestHeader = requestHeader;
|
||||
}
|
||||
|
||||
public TestHttpRequestHeader() throws FileNotFoundException, IOException,
|
||||
HttpException {
|
||||
this.setRequestHeader(new HttpRequestHeader(new FileInputStream(
|
||||
new File(PATHNAME))));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testHeaders() {
|
||||
assertEquals("GET", this.getRequestHeader().method.toUpperCase());
|
||||
assertEquals("HTTP://WWW.BAIDU.COM/",
|
||||
this.getRequestHeader().referer.toUpperCase());
|
||||
assertEquals(
|
||||
"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
|
||||
this.getRequestHeader().accept.toLowerCase().trim());
|
||||
assertEquals("/phoenix.zhtml?c=188488&p=irol-homeprofile",
|
||||
this.getRequestHeader().url.toLowerCase().trim());
|
||||
assertEquals("HTTP/1.1", this.getRequestHeader().version.toUpperCase()
|
||||
.trim());
|
||||
assertEquals(
|
||||
"Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36",
|
||||
this.getRequestHeader().userAgent.trim());
|
||||
assertEquals("bearer", this.getRequestHeader().authorization.trim());
|
||||
assertEquals("multipart", this.getRequestHeader().contentType.trim());
|
||||
assertEquals(100, this.getRequestHeader().contentLength);
|
||||
assertEquals(true, this.getRequestHeader().pragmaNoCache);
|
||||
|
||||
assertEquals("Mon, 22 Mar 2010 14:14:40 GMT; old-content-length=200",
|
||||
this.getRequestHeader().ifModifiedSince.trim());
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testToString() throws IOException {
|
||||
assertEquals(FileUtils.readFileToString(new File(PATHNAME))
|
||||
.toLowerCase(), this.getRequestHeader().toStringWithLib()
|
||||
.toLowerCase());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testStripProxyInfoFromRequestHeader() throws Exception {
|
||||
HttpRequestHeader header = new HttpRequestHeader(new FileInputStream(
|
||||
new File(PATHNAME)));
|
||||
String res = "";
|
||||
String origUrl = "http://ir.baidu.com/phoenix.zhtml?c=188488&p=irol-homeprofile";
|
||||
|
||||
URL url = new URL(origUrl);
|
||||
header.url = url.getFile();
|
||||
res = header.toString();
|
||||
header.url = origUrl;
|
||||
System.out.println(res);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testToStringWithLib() throws IOException {
|
||||
assertEquals(FileUtils.readFileToString(new File(PATHNAME))
|
||||
.toLowerCase(), this.getRequestHeader().toStringWithLib()
|
||||
.toLowerCase());
|
||||
}
|
||||
}
|
||||
package org.bench4q.master.test.recordscript;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileNotFoundException;
|
||||
import java.io.IOException;
|
||||
import java.net.URL;
|
||||
|
||||
import org.apache.http.HttpException;
|
||||
import org.bench4q.master.scriptrecord.httpcapture.HttpRequestHeader;
|
||||
import org.junit.Test;
|
||||
|
||||
public class TestHttpRequestHeader {
|
||||
private static final String PATHNAME = TestCodeGenerator.dealWithSerie
|
||||
+ "Request.txt";
|
||||
private HttpRequestHeader requestHeader;
|
||||
|
||||
private HttpRequestHeader getRequestHeader() {
|
||||
return requestHeader;
|
||||
}
|
||||
|
||||
private void setRequestHeader(HttpRequestHeader requestHeader) {
|
||||
this.requestHeader = requestHeader;
|
||||
}
|
||||
|
||||
public TestHttpRequestHeader() throws FileNotFoundException, IOException,
|
||||
HttpException {
|
||||
this.setRequestHeader(new HttpRequestHeader(new FileInputStream(
|
||||
new File(PATHNAME))));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testHeaders() {
|
||||
assertEquals("GET", this.getRequestHeader().method.toUpperCase());
|
||||
assertEquals("HTTP://WWW.BAIDU.COM/",
|
||||
this.getRequestHeader().referer.toUpperCase());
|
||||
assertEquals(
|
||||
"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
|
||||
this.getRequestHeader().accept.toLowerCase().trim());
|
||||
assertEquals("/phoenix.zhtml?c=188488&p=irol-homeprofile",
|
||||
this.getRequestHeader().url.toLowerCase().trim());
|
||||
assertEquals("HTTP/1.1", this.getRequestHeader().version.toUpperCase()
|
||||
.trim());
|
||||
assertEquals(
|
||||
"Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36",
|
||||
this.getRequestHeader().userAgent.trim());
|
||||
assertEquals("bearer", this.getRequestHeader().authorization.trim());
|
||||
assertEquals("multipart", this.getRequestHeader().contentType.trim());
|
||||
assertEquals(100, this.getRequestHeader().contentLength);
|
||||
assertEquals(true, this.getRequestHeader().pragmaNoCache);
|
||||
|
||||
assertEquals("Mon, 22 Mar 2010 14:14:40 GMT; old-content-length=200",
|
||||
this.getRequestHeader().ifModifiedSince.trim());
|
||||
|
||||
}
|
||||
|
||||
// @Test
|
||||
// public void testToString() throws IOException {
|
||||
// assertEquals(FileUtils.readFileToString(new File(PATHNAME))
|
||||
// .toLowerCase(), this.getRequestHeader().toStringWithLib()
|
||||
// .toLowerCase());
|
||||
// }
|
||||
|
||||
@Test
|
||||
public void testStripProxyInfoFromRequestHeader() throws Exception {
|
||||
HttpRequestHeader header = new HttpRequestHeader(new FileInputStream(
|
||||
new File(PATHNAME)));
|
||||
String res = "";
|
||||
String origUrl = "http://ir.baidu.com/phoenix.zhtml?c=188488&p=irol-homeprofile";
|
||||
|
||||
URL url = new URL(origUrl);
|
||||
header.url = url.getFile();
|
||||
res = header.toString();
|
||||
header.url = origUrl;
|
||||
System.out.println(res);
|
||||
}
|
||||
|
||||
// @Test
|
||||
// public void testToStringWithLib() throws IOException {
|
||||
// assertEquals(FileUtils.readFileToString(new File(PATHNAME))
|
||||
// .toLowerCase(), this.getRequestHeader().toStringWithLib()
|
||||
// .toLowerCase());
|
||||
// }
|
||||
}
|
||||
|
|
|
@ -1,49 +1,49 @@
|
|||
package org.bench4q.master.test.recordscript;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.UnsupportedEncodingException;
|
||||
|
||||
import org.apache.commons.io.FileUtils;
|
||||
import org.bench4q.master.scriptrecord.httpcapture.generator.ResponseHeader;
|
||||
import org.bench4q.master.scriptrecord.httpcapture.generator.ResponseParser;
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
public class TestResponseParser {
|
||||
private ResponseParser responseParser;
|
||||
private static String FILE_SEPARATOR = System.getProperty("file.separator");
|
||||
|
||||
private ResponseParser getResponseParser() {
|
||||
return responseParser;
|
||||
}
|
||||
|
||||
private void setResponseParser(ResponseParser responseParser) {
|
||||
this.responseParser = responseParser;
|
||||
}
|
||||
|
||||
public TestResponseParser() throws IOException {
|
||||
byte[] response = FileUtils.readFileToByteArray(new File(
|
||||
"RecordScriptTestCase" + FILE_SEPARATOR
|
||||
+ "gzipBaiduResponse.txt"));
|
||||
this.setResponseParser(new ResponseParser(response));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testParseResponseHeader() throws Exception {
|
||||
ResponseHeader parseResponseHeader = this.getResponseParser()
|
||||
.getResponseHeader();
|
||||
assertEquals(parseResponseHeader.getContentLength(), 12852);
|
||||
assertEquals(parseResponseHeader.getCharset(), "utf-8");
|
||||
assertEquals(parseResponseHeader.getContentEncoding(), "gzip");
|
||||
assertEquals(parseResponseHeader.getContentType(), "text/html");
|
||||
assertEquals(parseResponseHeader.getRespCode(), "200");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testParseResponseBody() throws UnsupportedEncodingException {
|
||||
String responseBody = this.getResponseParser().getResponseBody();
|
||||
assertTrue(responseBody.indexOf("ÎÒµÄ") > -1);
|
||||
}
|
||||
}
|
||||
package org.bench4q.master.test.recordscript;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.UnsupportedEncodingException;
|
||||
|
||||
import org.apache.commons.io.FileUtils;
|
||||
import org.bench4q.master.scriptrecord.httpcapture.generator.ResponseHeader;
|
||||
import org.bench4q.master.scriptrecord.httpcapture.generator.ResponseParser;
|
||||
import org.junit.Test;
|
||||
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
public class TestResponseParser {
|
||||
private ResponseParser responseParser;
|
||||
private static String FILE_SEPARATOR = System.getProperty("file.separator");
|
||||
|
||||
private ResponseParser getResponseParser() {
|
||||
return responseParser;
|
||||
}
|
||||
|
||||
private void setResponseParser(ResponseParser responseParser) {
|
||||
this.responseParser = responseParser;
|
||||
}
|
||||
|
||||
public TestResponseParser() throws IOException {
|
||||
byte[] response = FileUtils.readFileToByteArray(new File(
|
||||
"RecordScriptTestCase" + FILE_SEPARATOR
|
||||
+ "gzipBaiduResponse.txt"));
|
||||
this.setResponseParser(new ResponseParser(response));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testParseResponseHeader() throws Exception {
|
||||
ResponseHeader parseResponseHeader = this.getResponseParser()
|
||||
.getResponseHeader();
|
||||
assertEquals(parseResponseHeader.getContentLength(), 12852);
|
||||
assertEquals(parseResponseHeader.getCharset(), "utf-8");
|
||||
assertEquals(parseResponseHeader.getContentEncoding(), "gzip");
|
||||
assertEquals(parseResponseHeader.getContentType(), "text/html");
|
||||
assertEquals(parseResponseHeader.getRespCode(), "200");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testParseResponseBody() throws UnsupportedEncodingException {
|
||||
String responseBody = this.getResponseParser().getResponseBody();
|
||||
assertTrue(responseBody.indexOf("我的") > -1);
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue