/*
* Copyright (c) xsocket.org, 2006 - 2008. All rights reserved.
*
* 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.1 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
*
* Please refer to the LGPL license at: http://www.gnu.org/copyleft/lesser.txt
* The latest copy of this software may be found on http://www.xsocket.org/
*/
package org.xsocket.connection.http;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.LineNumberReader;
import java.io.RandomAccessFile;
import java.net.SocketTimeoutException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.channels.FileChannel;
import org.junit.Assert;
import org.junit.Test;
import org.xsocket.Execution;
import org.xsocket.connection.IServer;
import org.xsocket.connection.Server;
import org.xsocket.connection.ConnectionUtils;
import org.xsocket.connection.IConnection.FlushMode;
import org.xsocket.connection.http.HttpResponse;
import org.xsocket.connection.http.client.GetRequest;
import org.xsocket.connection.http.client.HttpClient;
import org.xsocket.connection.http.client.IHttpClientEndpoint;
import org.xsocket.connection.http.client.IHttpResponseHandler;
import org.xsocket.connection.http.server.HttpServer;
import org.xsocket.connection.http.server.IHttpResponseContext;
import org.xsocket.connection.http.server.IHttpRequestHandler;
/**
*
* @author grro@xsocket.org
*/
public final class HttpClientGetTest {
public static void main(String[] args) throws Exception {
final int port = 9728;
WebContainer servletEngine = new WebContainer(port, new HeaderInfoServlet());
servletEngine.start();
HttpClient httpclient= new HttpClient();
ConnectionUtils.registerMBean(httpclient);
for (int j = 0; j < 100000000; j++) {
HttpResponse response = httpclient.call(new GetRequest("http://www.web.de:80/"));
Assert.assertEquals(200, response.getStatus());
System.out.println(j);
}
servletEngine.stop();
}
@Test
public void testLiveGet() throws Exception {
IHttpClientEndpoint httpClient = new HttpClient();
HttpResponse response = httpClient.call(new GetRequest("http://www.web.de/index.html"));
Assert.assertEquals(302, response.getStatus());
}
@Test
public void testLiveGetFollowRedirect() throws Exception {
HttpClient httpClient = new HttpClient();
HttpResponse response = httpClient.callFollowRedirects(new GetRequest("http://www.web.de/index.html"));
Assert.assertEquals(200, response.getStatus());
}
@Test
public void testLiveGetFollowRedirectSend() throws Exception {
HttpClient httpClient = new HttpClient();
MultiThreadedResponseHandler hdl = new MultiThreadedResponseHandler();
httpClient.sendFollowRedirects(new GetRequest("http://www.web.de/index.html"), hdl);
QAUtil.sleep(2000);
Assert.assertEquals(200, hdl.response.getStatus());
}
/*
@Test
public void testLiveGetHttps() throws Exception {
HttpClient httpClient = new HttpClient(SSLContext.getDefault()); // SSLContext.getDefault() -> Java 1.6!
Response response = httpClient.callFollowRedirects(new GetRequest("https://www.web.de/"));
Assert.assertEquals(200, response.getStatus());
}
*/
@Test
public void testBlockingTransferTo() throws Exception {
IServer server = new HttpServer(new HeaderInfoServerHandler());
ConnectionUtils.start(server);
HttpClient httpClient = new HttpClient();
HttpResponse response = httpClient.call(new GetRequest("http://localhost:" + server.getLocalPort() + "/"));
File file = File.createTempFile("test", null);
file.createNewFile();
System.out.println("write to file " + file.getAbsolutePath());
FileChannel fc = new RandomAccessFile(file, "rw").getChannel();
response.getBlockingBody().transferTo(fc);
fc.close();
LineNumberReader lnr = new LineNumberReader(new FileReader(file));
String line = lnr.readLine();
Assert.assertEquals("method= GET", line);
server.close();
}
@Test
public void testCallTimeout() throws Exception {
IServer server = new Server(new DevNullHandler());
ConnectionUtils.start(server);
HttpClient httpClient = new HttpClient();
httpClient.setResponseTimeoutMillis(500);
try {
httpClient.call(new GetRequest("http://localhost:" + server.getLocalPort() + "/"));
Assert.fail("timeout exepction shoud haven been thrown");
} catch (SocketTimeoutException expeceted) { }
Assert.assertEquals(1, httpClient.getNumCreated());
Assert.assertEquals(1, httpClient.getNumDestroyed());
Assert.assertEquals(0, httpClient.getIdleConnectionInfos().size());
httpClient.close();
server.close();
}
@Test
public void testHeaders() throws Exception {
HttpClient httpClient = new HttpClient();
ConnectionUtils.registerMBean(httpClient);
IServer server = new HttpServer(new HeaderInfoServerHandler());
ConnectionUtils.start(server);
for (int i = 0; i < 5; i++) {
GetRequest request = new GetRequest("http://localhost:" + server.getLocalPort() + "/");
request.addHeader("header1", "value1");
request.addHeader("header2", "value2");
HttpResponse response = httpClient.call(request);
String body = response.getBlockingBody().toString();
Assert.assertTrue(body.indexOf("header1: value1") != -1);
Assert.assertTrue(body.indexOf("header2: value2") != -1);
}
httpClient.close();
server.close();
}
@Test
public void testLiveRedirect() throws Exception {
HttpClient httpClient = new HttpClient();
ConnectionUtils.registerMBean(httpClient);
HttpResponse response = httpClient.callFollowRedirects(new GetRequest("http://www.web.de:80/invalidpath"));
String body = response.getBlockingBody().readString();
Assert.assertTrue(body.indexOf("Die gew\u00FCnschte Seite wurde leider nicht gefunden") != -1);
}
@Test
public void testInvokeOnHeader() throws Exception {
int delay = 500;
IServer server = new HttpServer(new DelayServerHandler(delay));
ConnectionUtils.start(server);
HttpClient httpClient = new HttpClient();
HttpResponse response = httpClient.call(new GetRequest("http://localhost:" + server.getLocalPort() + "/"));
Assert.assertFalse(response.getNonBlockingBody().isComplete());
QAUtil.sleep(delay * 2);
Assert.assertTrue(response.getNonBlockingBody().isComplete());
/*
HttpClient httpClient = new HttpClient();
GetMethod getMeth = new GetMethod("http://localhost:" + server.getLocalPort() + "/test?size=10000&rate=45");
httpClient.executeMethod(getMeth);
int statusCode = getMeth.getStatusCode();
*/
httpClient.close();
//con.close();
server.close();
}
/* @Test
public void testSimpleCompare() throws Exception {
ItWorksServer server = new ItWorksServer(0);
ConnectionUtils.start(server);
// warm up
call("localhost", server.getLocalPort(), 20, true);
call("localhost", server.getLocalPort(), 20, false);
long start = System.currentTimeMillis();
call("localhost", server.getLocalPort(), 2000, true);
long elapsedPooled = System.currentTimeMillis() - start;
start = System.currentTimeMillis();
call("localhost", server.getLocalPort(), 2000, false);
long elapsedUnpooled = System.currentTimeMillis() - start;
System.out.println("\r\npooled " + DataConverter.toFormatedDuration(elapsedPooled) + " " +
" unpooled " + DataConverter.toFormatedDuration(elapsedUnpooled));
server.close();
Assert.assertTrue(elapsedPooled < elapsedUnpooled);
}
*/
private void call(String hostname, int port, int loops, boolean isPooled) throws IOException, URISyntaxException {
HttpClient httpClient = new HttpClient();
httpClient.setPooled(isPooled);
for (int i = 0; i < loops; i++) {
HttpResponse response = httpClient.call(new GetRequest("http://" + hostname + ":" + port + "/"));
Assert.assertEquals(200, response.getStatus());
}
httpClient.close();
}
@Test
public void testNonThreadedAsynchGet() throws Exception {
IServer server = new HttpServer(new HeaderInfoServerHandler());
ConnectionUtils.start(server);
IHttpClientEndpoint httpClient = new HttpClient();
NonThreadedResponseHandler hdl = new NonThreadedResponseHandler();
httpClient.send(new GetRequest("http://localhost:" + server.getLocalPort() + "/"), hdl);
QAUtil.sleep(500);
HttpResponse response = hdl.getResponse();
httpClient.close();
server.close();
Assert.assertTrue(hdl.threadname.startsWith("xDispatcher"));
Assert.assertEquals(200, response.getStatus());
}
@Test
public void testCallMaxRedirect() throws Exception {
IServer server = new HttpServer(new RedirectLoopServerHandler());
ConnectionUtils.start(server);
HttpClient httpClient = new HttpClient();
try {
HttpResponse response = httpClient.callFollowRedirects(new GetRequest("http://localhost:" + server.getLocalPort() + "/test"));
Assert.fail("max redirect exception should have been thrown");
} catch (IOException maxRedirect) {
System.out.println(".");
}
server.close();
}
@Test
public void testCallRelativeRedirect() throws Exception {
IServer server = new HttpServer(new RelativeRedirectHandler ());
ConnectionUtils.start(server);
HttpClient httpClient = new HttpClient();
HttpResponse response = httpClient.callFollowRedirects(new GetRequest("http://localhost:" + server.getLocalPort() + "/test"));
Assert.assertEquals(200, response.getStatus());
server.close();
}
@Test
public void testSendMaxRedirect() throws Exception {
IServer server = new HttpServer(new RedirectLoopServerHandler());
ConnectionUtils.start(server);
HttpClient httpClient = new HttpClient();
NonThreadedResponseHandler hdl = new NonThreadedResponseHandler();
httpClient.sendFollowRedirects(new GetRequest("http://localhost:" + server.getLocalPort() + "/test"), hdl);
Assert.assertNull(hdl.getResponse()); // redirect loop should bee terminated -> response is null
server.close();
}
@Test
public void testLiveNonThreadedAsynchGetRedirect() throws Exception {
HttpClient httpClient = new HttpClient();
NonThreadedResponseHandler hdl = new NonThreadedResponseHandler();
httpClient.sendFollowRedirects(new GetRequest("http://www.web.de:80/invalidpath"), hdl);
QAUtil.sleep(1000);
Assert.assertTrue(hdl.getThreadname().startsWith("xDispatcher"));
Assert.assertTrue(hdl.getResponse().getBlockingBody().readString().indexOf("Die gew\u00FCnschte Seite wurde leider nicht gefunden") != -1);
Assert.assertEquals(200, hdl.getResponse().getStatus());
}
@Test
public void testLiveMultiThreadedAsynchGetRedirect() throws Exception {
HttpClient httpClient = new HttpClient();
MultiThreadedResponseHandler hdl = new MultiThreadedResponseHandler();
httpClient.sendFollowRedirects(new GetRequest("http://www.web.de:80/invalidpath"), hdl);
QAUtil.sleep(1000);
HttpResponse response = hdl.getResponse();
Assert.assertFalse(hdl.threadname.startsWith("xDispatcher"));
Assert.assertTrue(hdl.response.getBlockingBody().readString().indexOf("Die gew\u00FCnschte Seite wurde leider nicht gefunden") != -1);
Assert.assertEquals(200, response.getStatus());
}
@Test
public void testMultiThreadedAsynchGet() throws Exception {
IServer server = new HttpServer(new HeaderInfoServerHandler());
ConnectionUtils.start(server);
HttpClient httpClient = new HttpClient();
Assert.assertEquals(0, httpClient.getActiveConnectionInfos().size());
Assert.assertEquals(0, httpClient.getIdleConnectionInfos().size());
MultiThreadedResponseHandler hdl = new MultiThreadedResponseHandler();
httpClient.send(new GetRequest("http://localhost:" + server.getLocalPort() + "/"), hdl);
QAUtil.sleep(500);
Assert.assertEquals(0, httpClient.getActiveConnectionInfos().size());
Assert.assertEquals(1, httpClient.getIdleConnectionInfos().size());
HttpResponse response = hdl.getResponse();
httpClient.close();
server.close();
Assert.assertFalse(hdl.threadname.startsWith("xDispatcher"));
Assert.assertEquals(200, response.getStatus());
}
@Execution(Execution.NONTHREADED)
private static final class NonThreadedResponseHandler implements IHttpResponseHandler {
private String threadname = null;
private HttpResponse response = null;
public void onResponse(HttpResponse response) throws IOException {
threadname = Thread.currentThread().getName();
this.response = response;
}
public HttpResponse getResponse() {
return response;
}
String getThreadname() {
return threadname;
}
}
@Execution(Execution.MULTITHREADED)
private static final class MultiThreadedResponseHandler implements IHttpResponseHandler {
private String threadname = null;
private HttpResponse response = null;
public void onResponse(HttpResponse response) throws IOException {
threadname = Thread.currentThread().getName();
this.response = response;
}
public HttpResponse getResponse() {
return response;
}
String getThreadname() {
return threadname;
}
}
private static final class DelayServerHandler implements IHttpRequestHandler {
private int delay = 0;
public DelayServerHandler(int delay) {
this.delay = delay;
}
public void onRequest(HttpRequest request, IHttpResponseContext httpServerEndpoint) throws IOException {
int size = 400;
BodyDataSink bodyDataSink = httpServerEndpoint.send(new HttpResponseHeader(200, "text/plain", size));
bodyDataSink.setFlushmode(FlushMode.ASYNC);
bodyDataSink.write((byte) 45);
QAUtil.sleep(delay);
byte[] bytes = new byte[size - 1];
for (int i = 0; i < bytes.length; i++) {
bytes[i] = 45;
}
bodyDataSink.write(bytes);
}
}
private static final class RedirectLoopServerHandler implements IHttpRequestHandler {
public void onRequest(HttpRequest request, IHttpResponseContext httpServerEndpoint) throws IOException {
URI targetURL = request.getTargetURI();
HttpResponse response = new HttpResponse(302);
response.setHeader("Location", targetURL.toString());
httpServerEndpoint.send(response);
}
}
private static final class RelativeRedirectHandler implements IHttpRequestHandler {
public void onRequest(HttpRequest request, IHttpResponseContext httpServerEndpoint) throws IOException {
if (request.getRequestURI().equals("/test")) {
HttpResponse response = new HttpResponse(302);
response.setHeader("Location", "/redirected");
httpServerEndpoint.send(response);
} else if (request.getRequestURI().equals("/redirected")) {
httpServerEndpoint.send(200);
} else {
httpServerEndpoint.sendError(500);
}
}
}
}
|