495085: rename TestProxy to MockServer
The TestProxy class is not a proxy and CommonHttpClientProxyTest has
nothing to do with proxies. This also removes the copy of TestProxy that
was deprecated 5 years ago and changes the classes that were still using
it to use MockServer
Change-Id: I0e9563de0e8830b553af953970ce4941fbc7815e
Task-Url: https://bugs.eclipse.org/bugs/show_bug.cgi?id=495085
diff --git a/org.eclipse.mylyn.commons.repositories.http.tests/src/org/eclipse/mylyn/commons/repositories/http/tests/CommonHttpClientProxyTest.java b/org.eclipse.mylyn.commons.repositories.http.tests/src/org/eclipse/mylyn/commons/repositories/http/tests/CommonHttpClientPreemptiveAuthTest.java
similarity index 71%
rename from org.eclipse.mylyn.commons.repositories.http.tests/src/org/eclipse/mylyn/commons/repositories/http/tests/CommonHttpClientProxyTest.java
rename to org.eclipse.mylyn.commons.repositories.http.tests/src/org/eclipse/mylyn/commons/repositories/http/tests/CommonHttpClientPreemptiveAuthTest.java
index 3e68e6e..43abdb9 100644
--- a/org.eclipse.mylyn.commons.repositories.http.tests/src/org/eclipse/mylyn/commons/repositories/http/tests/CommonHttpClientProxyTest.java
+++ b/org.eclipse.mylyn.commons.repositories.http.tests/src/org/eclipse/mylyn/commons/repositories/http/tests/CommonHttpClientPreemptiveAuthTest.java
@@ -21,7 +21,7 @@
import org.eclipse.mylyn.commons.repositories.http.core.CommonHttpClient;
import org.eclipse.mylyn.commons.repositories.http.core.CommonHttpResponse;
import org.eclipse.mylyn.commons.repositories.http.core.HttpRequestProcessor;
-import org.eclipse.mylyn.commons.sdk.util.TestProxy;
+import org.eclipse.mylyn.commons.sdk.util.MockServer;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
@@ -29,77 +29,77 @@
/**
* @author Steffen Pingel
*/
-public class CommonHttpClientProxyTest {
+public class CommonHttpClientPreemptiveAuthTest {
- private TestProxy testProxy;
+ private MockServer server;
- public CommonHttpClientProxyTest() {
+ public CommonHttpClientPreemptiveAuthTest() {
}
@Before
public void setUp() throws Exception {
- testProxy = new TestProxy();
- testProxy.startAndWait();
+ server = new MockServer();
+ server.startAndWait();
}
@After
public void tearDown() throws Exception {
- testProxy.stop();
+ server.stop();
}
@Test
public void testExecuteGetNoPreemptiveAuth() throws Exception {
- RepositoryLocation location = new RepositoryLocation(testProxy.getUrl());
+ RepositoryLocation location = new RepositoryLocation(server.getUrl());
location.setCredentials(AuthenticationType.HTTP, new UserCredentials("user", "pass"));
CommonHttpClient client = new CommonHttpClient(location);
- testProxy.addResponse(TestProxy.OK);
+ server.addResponse(MockServer.OK);
CommonHttpResponse response = client.executeGet("/", null, HttpRequestProcessor.DEFAULT);
assertEquals(HttpStatus.SC_OK, response.getStatusCode());
- assertEquals(null, testProxy.getRequest().getHeader("Authorization"));
+ assertEquals(null, server.getRequest().getHeader("Authorization"));
}
@Test(expected = AuthenticationException.class)
public void testExecuteGetAuthChallengeNoCredentials() throws Exception {
- RepositoryLocation location = new RepositoryLocation(testProxy.getUrl());
+ RepositoryLocation location = new RepositoryLocation(server.getUrl());
CommonHttpClient client = new CommonHttpClient(location);
- testProxy.addResponse(TestProxy.UNAUTHORIZED);
+ server.addResponse(MockServer.UNAUTHORIZED);
client.executeGet("/", null, HttpRequestProcessor.DEFAULT);
}
@Test
public void testExecuteGetAuthChallenge() throws Exception {
- RepositoryLocation location = new RepositoryLocation(testProxy.getUrl());
+ RepositoryLocation location = new RepositoryLocation(server.getUrl());
location.setCredentials(AuthenticationType.HTTP, new UserCredentials("user", "pass"));
CommonHttpClient client = new CommonHttpClient(location);
- testProxy.addResponse(TestProxy.UNAUTHORIZED);
- testProxy.addResponse(TestProxy.OK);
+ server.addResponse(MockServer.UNAUTHORIZED);
+ server.addResponse(MockServer.OK);
CommonHttpResponse response = client.executeGet("/", null, HttpRequestProcessor.DEFAULT);
assertEquals(HttpStatus.SC_OK, response.getStatusCode());
- assertEquals("Did not expect preemptive credentails", null, testProxy.getRequest().getHeader("Authorization"));
- assertEquals("Expect credentails on challenge", "Authorization: Basic dXNlcjpwYXNz", testProxy.getRequest()
- .getHeader("Authorization"));
+ assertEquals("Did not expect preemptive credentails", null, server.getRequest().getHeader("Authorization"));
+ assertEquals("Expect credentails on challenge", "Authorization: Basic dXNlcjpwYXNz",
+ server.getRequest().getHeader("Authorization"));
}
@Test
public void testExecuteGetPreemptiveAuth() throws Exception {
- RepositoryLocation location = new RepositoryLocation(testProxy.getUrl());
+ RepositoryLocation location = new RepositoryLocation(server.getUrl());
location.setCredentials(AuthenticationType.HTTP, new UserCredentials("user", "pass"));
CommonHttpClient client = new CommonHttpClient(location);
client.setPreemptiveAuthenticationEnabled(true);
- testProxy.addResponse(TestProxy.OK);
+ server.addResponse(MockServer.OK);
CommonHttpResponse response = client.executeGet("/", null, HttpRequestProcessor.DEFAULT);
- assertEquals("Authorization: Basic dXNlcjpwYXNz", testProxy.getRequest().getHeader("Authorization"));
+ assertEquals("Authorization: Basic dXNlcjpwYXNz", server.getRequest().getHeader("Authorization"));
assertEquals(HttpStatus.SC_OK, response.getStatusCode());
// subsequent requests will have cached credentials
client.setPreemptiveAuthenticationEnabled(false);
- testProxy.addResponse(TestProxy.OK);
+ server.addResponse(MockServer.OK);
response = client.executeGet("/", null, HttpRequestProcessor.DEFAULT);
- assertEquals("Authorization: Basic dXNlcjpwYXNz", testProxy.getRequest().getHeader("Authorization"));
+ assertEquals("Authorization: Basic dXNlcjpwYXNz", server.getRequest().getHeader("Authorization"));
assertEquals(HttpStatus.SC_OK, response.getStatusCode());
}
diff --git a/org.eclipse.mylyn.commons.repositories.http.tests/src/org/eclipse/mylyn/commons/repositories/http/tests/HttpUtilTest.java b/org.eclipse.mylyn.commons.repositories.http.tests/src/org/eclipse/mylyn/commons/repositories/http/tests/HttpUtilTest.java
index fa7dbb4..0421066 100644
--- a/org.eclipse.mylyn.commons.repositories.http.tests/src/org/eclipse/mylyn/commons/repositories/http/tests/HttpUtilTest.java
+++ b/org.eclipse.mylyn.commons.repositories.http.tests/src/org/eclipse/mylyn/commons/repositories/http/tests/HttpUtilTest.java
@@ -1,163 +1,163 @@
-/*******************************************************************************
- * Copyright (c) 2004, 2014 Tasktop Technologies and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Tasktop Technologies - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.mylyn.commons.repositories.http.tests;
-
-import static org.junit.Assert.assertEquals;
-
-import org.apache.http.HttpResponse;
-import org.apache.http.HttpStatus;
-import org.apache.http.client.methods.HttpGet;
-import org.apache.http.client.methods.HttpRequestBase;
-import org.apache.http.conn.ClientConnectionManager;
-import org.apache.http.impl.client.ContentEncodingHttpClient;
-import org.apache.http.impl.client.DefaultHttpClient;
-import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
-import org.apache.http.params.HttpProtocolParams;
-import org.eclipse.core.runtime.AssertionFailedException;
-import org.eclipse.mylyn.commons.core.CoreUtil;
-import org.eclipse.mylyn.commons.repositories.core.RepositoryLocation;
-import org.eclipse.mylyn.commons.repositories.core.auth.UserCredentials;
-import org.eclipse.mylyn.commons.repositories.http.core.HttpUtil;
-import org.eclipse.mylyn.commons.sdk.util.TestProxy;
-import org.eclipse.mylyn.commons.sdk.util.TestProxy.Message;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-
-/**
- * @author Steffen Pingel
- */
-public class HttpUtilTest {
-
- private static final int /*NetUtil.*/MAX_HTTP_HOST_CONNECTIONS_DEFAULT = 100;
-
- private static final int /*NetUtil.*/MAX_HTTP_TOTAL_CONNECTIONS_DEFAULT = 1000;
-
- private TestProxy testProxy;
-
- private DefaultHttpClient client;
-
- private ThreadSafeClientConnManager connectionManager;
-
- public HttpUtilTest() {
- }
-
- @Before
- public void setUp() throws Exception {
- testProxy = new TestProxy();
- testProxy.startAndWait();
- connectionManager = new ThreadSafeClientConnManager();
- client = new DefaultHttpClient() {
- @Override
- protected ClientConnectionManager createClientConnectionManager() {
- return connectionManager;
- }
- };
- }
-
- @After
- public void tearDown() throws Exception {
- testProxy.stop();
- }
-
- @Test
- public void testGetRequestPoolConnections() throws Exception {
- testProxy.addResponse(TestProxy.SERVICE_UNVAILABLE);
- HttpRequestBase request = new HttpGet(testProxy.getUrl());
-
- HttpUtil.configureClient(client, null);
- assertEquals(0, connectionManager.getConnectionsInPool());
-
- HttpResponse response = HttpUtil.execute(client, null, request, null);
- assertEquals(HttpStatus.SC_SERVICE_UNAVAILABLE, response.getStatusLine().getStatusCode());
- assertEquals(1, connectionManager.getConnectionsInPool());
- }
-
- @Test(expected = AssertionFailedException.class)
- public void testConfigureAuthenticationNullUrl() {
- HttpUtil.configureAuthentication(client, new RepositoryLocation((String) null), new UserCredentials("", ""));
- }
-
- @Test(expected = AssertionFailedException.class)
- public void testConfigureAuthenticationNullClient() {
- HttpUtil.configureAuthentication(null, new RepositoryLocation("url"), new UserCredentials("", ""));
- }
-
- @Test(expected = AssertionFailedException.class)
- public void testConfigureAuthenticationNullCredentials() {
- HttpUtil.configureAuthentication(client, new RepositoryLocation("url"), null);
- }
-
- @Test
- public void testConfigureAuthentication() {
- HttpUtil.configureAuthentication(client, new RepositoryLocation("url"), new UserCredentials("", ""));
- }
-
- @Test
- public void testConfigureProxy() {
- HttpUtil.configureProxy(client, new RepositoryLocation("url"));
- }
-
- @Test(expected = AssertionFailedException.class)
- public void testConfigureProxyNullClient() {
- HttpUtil.configureProxy(null, new RepositoryLocation("url"));
- }
-
- @Test(expected = AssertionFailedException.class)
- public void testConfigureProxyNullLocation() {
- HttpUtil.configureProxy(client, null);
- }
-
- @Test
- public void testGetEmptyGzipResponse() throws Exception {
- client = new ContentEncodingHttpClient() {
- @Override
- protected ClientConnectionManager createClientConnectionManager() {
- return connectionManager;
- }
- };
-
- Message message = new Message("HTTP/1.1 200 OK");
- message.headers.add("Content-Length: 0");
- message.headers.add("Content-Encoding: gzip");
- message.headers.add("Connection: close");
-
- testProxy.addResponse(message);
- HttpRequestBase request = new HttpGet(testProxy.getUrl());
-
- HttpUtil.configureClient(client, null);
- HttpResponse response = HttpUtil.execute(client, null, request, null);
- assertEquals(1, connectionManager.getConnectionsInPool());
- HttpUtil.release(request, response, null);
- assertEquals(0, connectionManager.getConnectionsInPool());
- }
-
- @Test
- public void testConfigureClient() {
- HttpUtil.configureClient(client, "Agent 007");
- assertEquals("Agent 007", HttpProtocolParams.getUserAgent(client.getParams()));
-
- HttpUtil.configureClient(client, "Special Agent Fox Mulder");
- assertEquals("Special Agent Fox Mulder", HttpProtocolParams.getUserAgent(client.getParams()));
-
- HttpUtil.configureClient(client, null);
- assertEquals("Special Agent Fox Mulder", HttpProtocolParams.getUserAgent(client.getParams()));
- }
-
- @Test
- public void testConfigureConnectionManager() {
- ThreadSafeClientConnManager connManager = HttpUtil.getConnectionManager();
-
- assertEquals(CoreUtil.TEST_MODE ? 2 : MAX_HTTP_HOST_CONNECTIONS_DEFAULT, connManager.getDefaultMaxPerRoute());
- assertEquals(CoreUtil.TEST_MODE ? 20 : MAX_HTTP_TOTAL_CONNECTIONS_DEFAULT, connManager.getMaxTotal());
- }
-}
+/*******************************************************************************
+ * Copyright (c) 2004, 2014 Tasktop Technologies and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Tasktop Technologies - initial API and implementation
+ *******************************************************************************/
+
+package org.eclipse.mylyn.commons.repositories.http.tests;
+
+import static org.junit.Assert.assertEquals;
+
+import org.apache.http.HttpResponse;
+import org.apache.http.HttpStatus;
+import org.apache.http.client.methods.HttpGet;
+import org.apache.http.client.methods.HttpRequestBase;
+import org.apache.http.conn.ClientConnectionManager;
+import org.apache.http.impl.client.ContentEncodingHttpClient;
+import org.apache.http.impl.client.DefaultHttpClient;
+import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
+import org.apache.http.params.HttpProtocolParams;
+import org.eclipse.core.runtime.AssertionFailedException;
+import org.eclipse.mylyn.commons.core.CoreUtil;
+import org.eclipse.mylyn.commons.repositories.core.RepositoryLocation;
+import org.eclipse.mylyn.commons.repositories.core.auth.UserCredentials;
+import org.eclipse.mylyn.commons.repositories.http.core.HttpUtil;
+import org.eclipse.mylyn.commons.sdk.util.MockServer;
+import org.eclipse.mylyn.commons.sdk.util.MockServer.Message;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+
+/**
+ * @author Steffen Pingel
+ */
+public class HttpUtilTest {
+
+ private static final int /*NetUtil.*/MAX_HTTP_HOST_CONNECTIONS_DEFAULT = 100;
+
+ private static final int /*NetUtil.*/MAX_HTTP_TOTAL_CONNECTIONS_DEFAULT = 1000;
+
+ private MockServer server;
+
+ private DefaultHttpClient client;
+
+ private ThreadSafeClientConnManager connectionManager;
+
+ public HttpUtilTest() {
+ }
+
+ @Before
+ public void setUp() throws Exception {
+ server = new MockServer();
+ server.startAndWait();
+ connectionManager = new ThreadSafeClientConnManager();
+ client = new DefaultHttpClient() {
+ @Override
+ protected ClientConnectionManager createClientConnectionManager() {
+ return connectionManager;
+ }
+ };
+ }
+
+ @After
+ public void tearDown() throws Exception {
+ server.stop();
+ }
+
+ @Test
+ public void testGetRequestPoolConnections() throws Exception {
+ server.addResponse(MockServer.SERVICE_UNVAILABLE);
+ HttpRequestBase request = new HttpGet(server.getUrl());
+
+ HttpUtil.configureClient(client, null);
+ assertEquals(0, connectionManager.getConnectionsInPool());
+
+ HttpResponse response = HttpUtil.execute(client, null, request, null);
+ assertEquals(HttpStatus.SC_SERVICE_UNAVAILABLE, response.getStatusLine().getStatusCode());
+ assertEquals(1, connectionManager.getConnectionsInPool());
+ }
+
+ @Test(expected = AssertionFailedException.class)
+ public void testConfigureAuthenticationNullUrl() {
+ HttpUtil.configureAuthentication(client, new RepositoryLocation((String) null), new UserCredentials("", ""));
+ }
+
+ @Test(expected = AssertionFailedException.class)
+ public void testConfigureAuthenticationNullClient() {
+ HttpUtil.configureAuthentication(null, new RepositoryLocation("url"), new UserCredentials("", ""));
+ }
+
+ @Test(expected = AssertionFailedException.class)
+ public void testConfigureAuthenticationNullCredentials() {
+ HttpUtil.configureAuthentication(client, new RepositoryLocation("url"), null);
+ }
+
+ @Test
+ public void testConfigureAuthentication() {
+ HttpUtil.configureAuthentication(client, new RepositoryLocation("url"), new UserCredentials("", ""));
+ }
+
+ @Test
+ public void testConfigureProxy() {
+ HttpUtil.configureProxy(client, new RepositoryLocation("url"));
+ }
+
+ @Test(expected = AssertionFailedException.class)
+ public void testConfigureProxyNullClient() {
+ HttpUtil.configureProxy(null, new RepositoryLocation("url"));
+ }
+
+ @Test(expected = AssertionFailedException.class)
+ public void testConfigureProxyNullLocation() {
+ HttpUtil.configureProxy(client, null);
+ }
+
+ @Test
+ public void testGetEmptyGzipResponse() throws Exception {
+ client = new ContentEncodingHttpClient() {
+ @Override
+ protected ClientConnectionManager createClientConnectionManager() {
+ return connectionManager;
+ }
+ };
+
+ Message message = new Message("HTTP/1.1 200 OK");
+ message.headers.add("Content-Length: 0");
+ message.headers.add("Content-Encoding: gzip");
+ message.headers.add("Connection: close");
+
+ server.addResponse(message);
+ HttpRequestBase request = new HttpGet(server.getUrl());
+
+ HttpUtil.configureClient(client, null);
+ HttpResponse response = HttpUtil.execute(client, null, request, null);
+ assertEquals(1, connectionManager.getConnectionsInPool());
+ HttpUtil.release(request, response, null);
+ assertEquals(0, connectionManager.getConnectionsInPool());
+ }
+
+ @Test
+ public void testConfigureClient() {
+ HttpUtil.configureClient(client, "Agent 007");
+ assertEquals("Agent 007", HttpProtocolParams.getUserAgent(client.getParams()));
+
+ HttpUtil.configureClient(client, "Special Agent Fox Mulder");
+ assertEquals("Special Agent Fox Mulder", HttpProtocolParams.getUserAgent(client.getParams()));
+
+ HttpUtil.configureClient(client, null);
+ assertEquals("Special Agent Fox Mulder", HttpProtocolParams.getUserAgent(client.getParams()));
+ }
+
+ @Test
+ public void testConfigureConnectionManager() {
+ ThreadSafeClientConnManager connManager = HttpUtil.getConnectionManager();
+
+ assertEquals(CoreUtil.TEST_MODE ? 2 : MAX_HTTP_HOST_CONNECTIONS_DEFAULT, connManager.getDefaultMaxPerRoute());
+ assertEquals(CoreUtil.TEST_MODE ? 20 : MAX_HTTP_TOTAL_CONNECTIONS_DEFAULT, connManager.getMaxTotal());
+ }
+}
diff --git a/org.eclipse.mylyn.commons.sdk.util/src/org/eclipse/mylyn/commons/sdk/util/TestProxy.java b/org.eclipse.mylyn.commons.sdk.util/src/org/eclipse/mylyn/commons/sdk/util/MockServer.java
similarity index 96%
rename from org.eclipse.mylyn.commons.sdk.util/src/org/eclipse/mylyn/commons/sdk/util/TestProxy.java
rename to org.eclipse.mylyn.commons.sdk.util/src/org/eclipse/mylyn/commons/sdk/util/MockServer.java
index 9f1cfb9..7a4421e 100644
--- a/org.eclipse.mylyn.commons.sdk.util/src/org/eclipse/mylyn/commons/sdk/util/TestProxy.java
+++ b/org.eclipse.mylyn.commons.sdk.util/src/org/eclipse/mylyn/commons/sdk/util/MockServer.java
@@ -1,388 +1,390 @@
-/*******************************************************************************
- * Copyright (c) 2004, 2012 Tasktop Technologies and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Tasktop Technologies - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.mylyn.commons.sdk.util;
-
-import java.io.BufferedReader;
-import java.io.BufferedWriter;
-import java.io.EOFException;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.io.InterruptedIOException;
-import java.io.OutputStream;
-import java.io.OutputStreamWriter;
-import java.net.InetSocketAddress;
-import java.net.ServerSocket;
-import java.net.Socket;
-import java.util.ArrayList;
-import java.util.List;
-
-import junit.framework.AssertionFailedError;
-
-/**
- * @author Steffen Pingel
- */
-public class TestProxy implements Runnable {
-
- public static String CRLF = "\r\n";
-
- public static class Message {
-
- public List<String> headers = new ArrayList<String>();
-
- public String request;
-
- private String charset;
-
- public Message(String request) {
- this.request = request;
- this.charset = "ISO-8859-1";
- }
-
- public String getCharset() {
- return charset;
- }
-
- public String getHeader(String prefix) {
- if (headers != null) {
- for (String header : headers) {
- if (header.startsWith(prefix)) {
- return header;
- }
- }
- }
- return null;
- }
-
- public String getHeaderValue(String prefix) {
- String header = getHeader(prefix);
- if (header != null) {
- int i = header.indexOf(": ");
- return (i != -1) ? header.substring(i + 2) : "";
- }
- return null;
- }
-
- public String getMethod() {
- int i = request.indexOf(" ");
- return (i != -1) ? request.substring(0, i) : request;
- }
-
- public void setCharset(String charset) {
- this.charset = charset;
- }
-
- public String getStatusLine() {
- int i = request.indexOf("\n");
- return (i != -1) ? request.substring(0, i) : request;
- }
-
- @Override
- public String toString() {
- StringBuilder sb = new StringBuilder();
- sb.append(request);
- sb.append("\n");
- if (headers != null) {
- for (String header : headers) {
- sb.append(header);
- sb.append("\n");
- }
- }
- sb.append("\n");
- return sb.toString().replaceAll("\n", CRLF);
- }
-
- }
-
- public static final String HEADER_CONNECTION_CLOSE = "Connection: Close";
-
- public static final String HEADER_NO_CONTENT = "Content-Length: 0";
-
- public static final Message NOT_FOUND = new Message("HTTP/1.1 404 Not Found");
-
- public static final Message OK = new Message("HTTP/1.1 200 OK");
-
- public static final Message TIMEOUT = new Message("HTTP/1.1 200 OK");
-
- public static final Message UNAUTHORIZED = new Message("HTTP/1.1 401 Unauthorized");
-
- public static final Message SERVICE_UNVAILABLE = createEmptyMessage("HTTP/1.1 503 Service Unavailable");
-
- static {
- NOT_FOUND.headers.add(HEADER_CONNECTION_CLOSE);
- OK.headers.add(HEADER_CONNECTION_CLOSE);
- SERVICE_UNVAILABLE.headers.add(HEADER_CONNECTION_CLOSE);
- TIMEOUT.headers.add("Content-Length: 500");
- UNAUTHORIZED.headers.add("WWW-Authenticate: Basic realm=\"Test\"");
- }
-
- private static Message createEmptyMessage(String status) {
- return new Message(status + "\n" + HEADER_NO_CONTENT + "\n\n");
- }
-
- private boolean autoClose;
-
- private IOException exception;
-
- private final int listenPort;
-
- private final List<Message> requests = new ArrayList<Message>();
-
- private final List<Message> responses = new ArrayList<Message>();
-
- private Thread runner;
-
- private volatile ServerSocket serverSocket;
-
- private volatile boolean stopped;
-
- private boolean waitForResponse;
-
- private boolean closeOnConnect;
-
- private boolean debugEnabled;
-
- public TestProxy() {
- this(0);
- }
-
- public TestProxy(int listenPort) {
- this.listenPort = listenPort;
- this.autoClose = true;
- }
-
- public synchronized void addRequest(Message request) {
- this.requests.add(request);
- notifyAll();
- }
-
- public synchronized void addResponse(Message response) {
- this.responses.add(response);
- notifyAll();
- }
-
- public synchronized void addResponse(String response) {
- this.responses.add(new Message(response));
- notifyAll();
- }
-
- public synchronized void checkForException() throws IOException {
- if (exception != null) {
- throw exception;
- }
- }
-
- public int getPort() {
- return serverSocket.getLocalPort();
- }
-
- public synchronized Message getRequest() throws InterruptedException {
- if (requests.isEmpty()) {
- throw new AssertionFailedError("Request list is empty");
- }
- return requests.remove(0);
- }
-
- private void handleConnection(Socket socket) {
- try {
- while (!closeOnConnect && !stopped) {
- Message request = readMessage(socket.getInputStream());
- if (stopped || request == null) {
- break;
- }
- addRequest(request);
-
- if (hasMoreResponses() || waitForResponse) {
- Message response = waitForResponse();
- if (stopped || response == null) {
- break;
- }
- writeMessage(response, socket.getOutputStream());
-
- if (autoClose && response.toString().contains(HEADER_CONNECTION_CLOSE)) {
- break;
- }
- } else {
- writeMessage(SERVICE_UNVAILABLE, socket.getOutputStream());
- System.err.println("Unexpected request: ");
- System.err.println(request.toString());
- break;
- }
- }
- } catch (IOException e) {
- setException(e);
- } catch (InterruptedException e) {
- } finally {
- try {
- socket.close();
- } catch (IOException e1) {
- }
- }
- }
-
- private synchronized boolean hasMoreResponses() {
- return !responses.isEmpty();
- }
-
- public synchronized boolean hasRequest() {
- return !requests.isEmpty();
- }
-
- public boolean isAutoClose() {
- return autoClose;
- }
-
- public boolean isCloseOnConnect() {
- return closeOnConnect;
- }
-
- private Message readMessage(InputStream in) throws IOException {
- BufferedReader reader = new BufferedReader(new InputStreamReader(in));
- Message message = null;
- String line;
- while ((line = reader.readLine()) != null) {
- if (line.length() == 0) {
- if (message == null) {
- throw new IOException("Incomplete message");
- }
- return message;
- }
-
- if (message == null) {
- if (isDebugEnabled()) {
- System.err.println("< " + line);
- }
- message = new Message(line);
- } else {
- message.headers.add(line);
- }
- }
- throw new EOFException();
- }
-
- public void run() {
- try {
- serverSocket = new ServerSocket(listenPort);
- while (!stopped) {
- Socket socket = serverSocket.accept();
- handleConnection(socket);
- }
- } catch (InterruptedIOException e) {
- // ignore
- } catch (IOException e) {
- setException(e);
- } finally {
- if (serverSocket != null) {
- try {
- serverSocket.close();
- } catch (IOException e) {
- }
- }
- }
-
- }
-
- public void setCloseOnConnect(boolean closeOnConnect) {
- this.closeOnConnect = closeOnConnect;
- }
-
- public void setAutoClose(boolean autoClose) {
- this.autoClose = autoClose;
- }
-
- private synchronized void setException(IOException exception) {
- this.exception = exception;
- notifyAll();
- }
-
- public void setWaitForResponse(boolean waitForResponse) {
- this.waitForResponse = waitForResponse;
- }
-
- public void start() {
- runner = new Thread(this, "TestProxy :" + listenPort);
- runner.start();
- }
-
- public int startAndWait() throws InterruptedException {
- start();
- while (serverSocket == null || serverSocket.getLocalPort() == -1) {
- Thread.sleep(100);
- }
- return serverSocket.getLocalPort();
- }
-
- public String getUrl() {
- InetSocketAddress address = new InetSocketAddress("localhost", serverSocket.getLocalPort());
- return "http://" + address.getHostName() + ":" + address.getPort() + "/";
-// try {
-// return "http://" + InetAddress.getLocalHost().getHostAddress() + ":" + serverSocket.getLocalPort();
-// } catch (UnknownHostException e) {
-// return "http://localhost:" + serverSocket.getLocalPort();
-// }
- }
-
- public void stop() {
- stopped = true;
- try {
- if (serverSocket != null) {
- serverSocket.close();
- }
- } catch (IOException e1) {
- // ignore
- }
- runner.interrupt();
- try {
- runner.join(500);
- } catch (InterruptedException e) {
- }
- }
-
- public synchronized Message waitForRequest() throws InterruptedException {
- while (requests.isEmpty()) {
- if (stopped) {
- return null;
- }
- wait();
- }
- return requests.remove(0);
- }
-
- public synchronized Message waitForResponse() throws InterruptedException {
- while (!stopped && responses.isEmpty()) {
- if (stopped || autoClose) {
- return null;
- }
- wait();
- }
- return responses.remove(0);
- }
-
- private void writeMessage(Message message, OutputStream out) throws IOException {
- if (isDebugEnabled()) {
- System.err.println("> " + message.getStatusLine());
- }
-
- BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, message.getCharset()));
- writer.write(message.toString());
- writer.flush();
- }
-
- public boolean isDebugEnabled() {
- return debugEnabled;
- }
-
- public void setDebugEnabled(boolean debugEnabled) {
- this.debugEnabled = debugEnabled;
- }
-
-}
+/*******************************************************************************
+ * Copyright (c) 2004, 2012 Tasktop Technologies and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Tasktop Technologies - initial API and implementation
+ *******************************************************************************/
+
+package org.eclipse.mylyn.commons.sdk.util;
+
+import java.io.BufferedReader;
+import java.io.BufferedWriter;
+import java.io.EOFException;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.io.InterruptedIOException;
+import java.io.OutputStream;
+import java.io.OutputStreamWriter;
+import java.net.InetSocketAddress;
+import java.net.ServerSocket;
+import java.net.Socket;
+import java.util.ArrayList;
+import java.util.List;
+
+import junit.framework.AssertionFailedError;
+
+/**
+ * A server that listens for requests and returns preconfigured responses, used for testing HTTP clients.
+ *
+ * @author Steffen Pingel
+ */
+public class MockServer implements Runnable {
+
+ public static String CRLF = "\r\n";
+
+ public static class Message {
+
+ public List<String> headers = new ArrayList<String>();
+
+ public String request;
+
+ private String charset;
+
+ public Message(String request) {
+ this.request = request;
+ this.charset = "ISO-8859-1";
+ }
+
+ public String getCharset() {
+ return charset;
+ }
+
+ public String getHeader(String prefix) {
+ if (headers != null) {
+ for (String header : headers) {
+ if (header.startsWith(prefix)) {
+ return header;
+ }
+ }
+ }
+ return null;
+ }
+
+ public String getHeaderValue(String prefix) {
+ String header = getHeader(prefix);
+ if (header != null) {
+ int i = header.indexOf(": ");
+ return (i != -1) ? header.substring(i + 2) : "";
+ }
+ return null;
+ }
+
+ public String getMethod() {
+ int i = request.indexOf(" ");
+ return (i != -1) ? request.substring(0, i) : request;
+ }
+
+ public void setCharset(String charset) {
+ this.charset = charset;
+ }
+
+ public String getStatusLine() {
+ int i = request.indexOf("\n");
+ return (i != -1) ? request.substring(0, i) : request;
+ }
+
+ @Override
+ public String toString() {
+ StringBuilder sb = new StringBuilder();
+ sb.append(request);
+ sb.append("\n");
+ if (headers != null) {
+ for (String header : headers) {
+ sb.append(header);
+ sb.append("\n");
+ }
+ }
+ sb.append("\n");
+ return sb.toString().replaceAll("\n", CRLF);
+ }
+
+ }
+
+ public static final String HEADER_CONNECTION_CLOSE = "Connection: Close";
+
+ public static final String HEADER_NO_CONTENT = "Content-Length: 0";
+
+ public static final Message NOT_FOUND = new Message("HTTP/1.1 404 Not Found");
+
+ public static final Message OK = new Message("HTTP/1.1 200 OK");
+
+ public static final Message TIMEOUT = new Message("HTTP/1.1 200 OK");
+
+ public static final Message UNAUTHORIZED = new Message("HTTP/1.1 401 Unauthorized");
+
+ public static final Message SERVICE_UNVAILABLE = createEmptyMessage("HTTP/1.1 503 Service Unavailable");
+
+ static {
+ NOT_FOUND.headers.add(HEADER_CONNECTION_CLOSE);
+ OK.headers.add(HEADER_CONNECTION_CLOSE);
+ SERVICE_UNVAILABLE.headers.add(HEADER_CONNECTION_CLOSE);
+ TIMEOUT.headers.add("Content-Length: 500");
+ UNAUTHORIZED.headers.add("WWW-Authenticate: Basic realm=\"Test\"");
+ }
+
+ private static Message createEmptyMessage(String status) {
+ return new Message(status + "\n" + HEADER_NO_CONTENT + "\n\n");
+ }
+
+ private boolean autoClose;
+
+ private IOException exception;
+
+ private final int listenPort;
+
+ private final List<Message> requests = new ArrayList<Message>();
+
+ private final List<Message> responses = new ArrayList<Message>();
+
+ private Thread runner;
+
+ private volatile ServerSocket serverSocket;
+
+ private volatile boolean stopped;
+
+ private boolean waitForResponse;
+
+ private boolean closeOnConnect;
+
+ private boolean debugEnabled;
+
+ public MockServer() {
+ this(0);
+ }
+
+ public MockServer(int listenPort) {
+ this.listenPort = listenPort;
+ this.autoClose = true;
+ }
+
+ public synchronized void addRequest(Message request) {
+ this.requests.add(request);
+ notifyAll();
+ }
+
+ public synchronized void addResponse(Message response) {
+ this.responses.add(response);
+ notifyAll();
+ }
+
+ public synchronized void addResponse(String response) {
+ this.responses.add(new Message(response));
+ notifyAll();
+ }
+
+ public synchronized void checkForException() throws IOException {
+ if (exception != null) {
+ throw exception;
+ }
+ }
+
+ public int getPort() {
+ return serverSocket.getLocalPort();
+ }
+
+ public synchronized Message getRequest() throws InterruptedException {
+ if (requests.isEmpty()) {
+ throw new AssertionFailedError("Request list is empty");
+ }
+ return requests.remove(0);
+ }
+
+ private void handleConnection(Socket socket) {
+ try {
+ while (!closeOnConnect && !stopped) {
+ Message request = readMessage(socket.getInputStream());
+ if (stopped || request == null) {
+ break;
+ }
+ addRequest(request);
+
+ if (hasMoreResponses() || waitForResponse) {
+ Message response = waitForResponse();
+ if (stopped || response == null) {
+ break;
+ }
+ writeMessage(response, socket.getOutputStream());
+
+ if (autoClose && response.toString().contains(HEADER_CONNECTION_CLOSE)) {
+ break;
+ }
+ } else {
+ writeMessage(SERVICE_UNVAILABLE, socket.getOutputStream());
+ System.err.println("Unexpected request: ");
+ System.err.println(request.toString());
+ break;
+ }
+ }
+ } catch (IOException e) {
+ setException(e);
+ } catch (InterruptedException e) {
+ } finally {
+ try {
+ socket.close();
+ } catch (IOException e1) {
+ }
+ }
+ }
+
+ private synchronized boolean hasMoreResponses() {
+ return !responses.isEmpty();
+ }
+
+ public synchronized boolean hasRequest() {
+ return !requests.isEmpty();
+ }
+
+ public boolean isAutoClose() {
+ return autoClose;
+ }
+
+ public boolean isCloseOnConnect() {
+ return closeOnConnect;
+ }
+
+ private Message readMessage(InputStream in) throws IOException {
+ BufferedReader reader = new BufferedReader(new InputStreamReader(in));
+ Message message = null;
+ String line;
+ while ((line = reader.readLine()) != null) {
+ if (line.length() == 0) {
+ if (message == null) {
+ throw new IOException("Incomplete message");
+ }
+ return message;
+ }
+
+ if (message == null) {
+ if (isDebugEnabled()) {
+ System.err.println("< " + line);
+ }
+ message = new Message(line);
+ } else {
+ message.headers.add(line);
+ }
+ }
+ throw new EOFException();
+ }
+
+ public void run() {
+ try {
+ serverSocket = new ServerSocket(listenPort);
+ while (!stopped) {
+ Socket socket = serverSocket.accept();
+ handleConnection(socket);
+ }
+ } catch (InterruptedIOException e) {
+ // ignore
+ } catch (IOException e) {
+ setException(e);
+ } finally {
+ if (serverSocket != null) {
+ try {
+ serverSocket.close();
+ } catch (IOException e) {
+ }
+ }
+ }
+
+ }
+
+ public void setCloseOnConnect(boolean closeOnConnect) {
+ this.closeOnConnect = closeOnConnect;
+ }
+
+ public void setAutoClose(boolean autoClose) {
+ this.autoClose = autoClose;
+ }
+
+ private synchronized void setException(IOException exception) {
+ this.exception = exception;
+ notifyAll();
+ }
+
+ public void setWaitForResponse(boolean waitForResponse) {
+ this.waitForResponse = waitForResponse;
+ }
+
+ public void start() {
+ runner = new Thread(this, "MockServer :" + listenPort);
+ runner.start();
+ }
+
+ public int startAndWait() throws InterruptedException {
+ start();
+ while (serverSocket == null || serverSocket.getLocalPort() == -1) {
+ Thread.sleep(100);
+ }
+ return serverSocket.getLocalPort();
+ }
+
+ public String getUrl() {
+ InetSocketAddress address = new InetSocketAddress("localhost", serverSocket.getLocalPort());
+ return "http://" + address.getHostName() + ":" + address.getPort() + "/";
+// try {
+// return "http://" + InetAddress.getLocalHost().getHostAddress() + ":" + serverSocket.getLocalPort();
+// } catch (UnknownHostException e) {
+// return "http://localhost:" + serverSocket.getLocalPort();
+// }
+ }
+
+ public void stop() {
+ stopped = true;
+ try {
+ if (serverSocket != null) {
+ serverSocket.close();
+ }
+ } catch (IOException e1) {
+ // ignore
+ }
+ runner.interrupt();
+ try {
+ runner.join(500);
+ } catch (InterruptedException e) {
+ }
+ }
+
+ public synchronized Message waitForRequest() throws InterruptedException {
+ while (requests.isEmpty()) {
+ if (stopped) {
+ return null;
+ }
+ wait();
+ }
+ return requests.remove(0);
+ }
+
+ public synchronized Message waitForResponse() throws InterruptedException {
+ while (!stopped && responses.isEmpty()) {
+ if (stopped || autoClose) {
+ return null;
+ }
+ wait();
+ }
+ return responses.remove(0);
+ }
+
+ private void writeMessage(Message message, OutputStream out) throws IOException {
+ if (isDebugEnabled()) {
+ System.err.println("> " + message.getStatusLine());
+ }
+
+ BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, message.getCharset()));
+ writer.write(message.toString());
+ writer.flush();
+ }
+
+ public boolean isDebugEnabled() {
+ return debugEnabled;
+ }
+
+ public void setDebugEnabled(boolean debugEnabled) {
+ this.debugEnabled = debugEnabled;
+ }
+
+}
diff --git a/org.eclipse.mylyn.commons.tests/src/org/eclipse/mylyn/commons/tests/net/SslProtocolSocketFactoryTest.java b/org.eclipse.mylyn.commons.tests/src/org/eclipse/mylyn/commons/tests/net/SslProtocolSocketFactoryTest.java
index edc56c0..21903cb 100644
--- a/org.eclipse.mylyn.commons.tests/src/org/eclipse/mylyn/commons/tests/net/SslProtocolSocketFactoryTest.java
+++ b/org.eclipse.mylyn.commons.tests/src/org/eclipse/mylyn/commons/tests/net/SslProtocolSocketFactoryTest.java
@@ -1,76 +1,76 @@
-/*******************************************************************************
- * Copyright (c) 2004, 2009 Tasktop Technologies and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Tasktop Technologies - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.mylyn.commons.tests.net;
-
-import java.net.InetAddress;
-import java.net.InetSocketAddress;
-import java.net.Socket;
-
-import junit.framework.TestCase;
-
-import org.apache.commons.httpclient.params.HttpConnectionParams;
-import org.apache.commons.httpclient.protocol.SecureProtocolSocketFactory;
-import org.eclipse.mylyn.commons.tests.support.TestProxy;
-import org.eclipse.mylyn.internal.commons.net.PollingSslProtocolSocketFactory;
-
-/**
- * @author Steffen Pingel
- */
-public class SslProtocolSocketFactoryTest extends TestCase {
-
- private TestProxy testProxy;
-
- private InetSocketAddress proxyAddress;
-
- @Override
- protected void setUp() throws Exception {
- testProxy = new TestProxy();
- int proxyPort = testProxy.startAndWait();
- assert proxyPort > 0;
- proxyAddress = new InetSocketAddress("localhost", proxyPort);
- }
-
- @Override
- protected void tearDown() throws Exception {
- testProxy.stop();
- }
-
- public void testTrustAllSslProtocolSocketFactory() throws Exception {
- SecureProtocolSocketFactory factory = new PollingSslProtocolSocketFactory();
- Socket s;
-
- s = factory.createSocket(proxyAddress.getHostName(), proxyAddress.getPort());
- assertNotNull(s);
- assertTrue(s.isConnected());
- s.close();
-
- InetAddress anyHost = new Socket().getLocalAddress();
-
- s = factory.createSocket(proxyAddress.getHostName(), proxyAddress.getPort(), anyHost, 0);
- assertNotNull(s);
- assertTrue(s.isConnected());
- s.close();
-
- HttpConnectionParams params = new HttpConnectionParams();
- s = factory.createSocket(proxyAddress.getHostName(), proxyAddress.getPort(), anyHost, 0, params);
- assertNotNull(s);
- assertTrue(s.isConnected());
- s.close();
-
- params.setConnectionTimeout(1000);
- s = factory.createSocket(proxyAddress.getHostName(), proxyAddress.getPort(), anyHost, 0, params);
- assertNotNull(s);
- assertTrue(s.isConnected());
- s.close();
- }
-
-}
+/*******************************************************************************
+ * Copyright (c) 2004, 2009 Tasktop Technologies and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Tasktop Technologies - initial API and implementation
+ *******************************************************************************/
+
+package org.eclipse.mylyn.commons.tests.net;
+
+import java.net.InetAddress;
+import java.net.InetSocketAddress;
+import java.net.Socket;
+
+import org.apache.commons.httpclient.params.HttpConnectionParams;
+import org.apache.commons.httpclient.protocol.SecureProtocolSocketFactory;
+import org.eclipse.mylyn.commons.sdk.util.MockServer;
+import org.eclipse.mylyn.internal.commons.net.PollingSslProtocolSocketFactory;
+
+import junit.framework.TestCase;
+
+/**
+ * @author Steffen Pingel
+ */
+public class SslProtocolSocketFactoryTest extends TestCase {
+
+ private MockServer server;
+
+ private InetSocketAddress proxyAddress;
+
+ @Override
+ protected void setUp() throws Exception {
+ server = new MockServer();
+ int proxyPort = server.startAndWait();
+ assert proxyPort > 0;
+ proxyAddress = new InetSocketAddress("localhost", proxyPort);
+ }
+
+ @Override
+ protected void tearDown() throws Exception {
+ server.stop();
+ }
+
+ public void testTrustAllSslProtocolSocketFactory() throws Exception {
+ SecureProtocolSocketFactory factory = new PollingSslProtocolSocketFactory();
+ Socket s;
+
+ s = factory.createSocket(proxyAddress.getHostName(), proxyAddress.getPort());
+ assertNotNull(s);
+ assertTrue(s.isConnected());
+ s.close();
+
+ InetAddress anyHost = new Socket().getLocalAddress();
+
+ s = factory.createSocket(proxyAddress.getHostName(), proxyAddress.getPort(), anyHost, 0);
+ assertNotNull(s);
+ assertTrue(s.isConnected());
+ s.close();
+
+ HttpConnectionParams params = new HttpConnectionParams();
+ s = factory.createSocket(proxyAddress.getHostName(), proxyAddress.getPort(), anyHost, 0, params);
+ assertNotNull(s);
+ assertTrue(s.isConnected());
+ s.close();
+
+ params.setConnectionTimeout(1000);
+ s = factory.createSocket(proxyAddress.getHostName(), proxyAddress.getPort(), anyHost, 0, params);
+ assertNotNull(s);
+ assertTrue(s.isConnected());
+ s.close();
+ }
+
+}
diff --git a/org.eclipse.mylyn.commons.tests/src/org/eclipse/mylyn/commons/tests/net/WebUtilTest.java b/org.eclipse.mylyn.commons.tests/src/org/eclipse/mylyn/commons/tests/net/WebUtilTest.java
index 68b9249..06fa5ab 100644
--- a/org.eclipse.mylyn.commons.tests/src/org/eclipse/mylyn/commons/tests/net/WebUtilTest.java
+++ b/org.eclipse.mylyn.commons.tests/src/org/eclipse/mylyn/commons/tests/net/WebUtilTest.java
@@ -1,672 +1,672 @@
-/*******************************************************************************
- * Copyright (c) 2004, 2014 Tasktop Technologies and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Tasktop Technologies - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.mylyn.commons.tests.net;
-
-import static org.eclipse.mylyn.commons.tests.net.NetUtilTest.MAX_HTTP_HOST_CONNECTIONS_DEFAULT;
-import static org.eclipse.mylyn.commons.tests.net.NetUtilTest.MAX_HTTP_TOTAL_CONNECTIONS_DEFAULT;
-
-import java.io.IOException;
-import java.io.InterruptedIOException;
-import java.net.ConnectException;
-import java.net.InetSocketAddress;
-import java.net.Proxy;
-import java.net.Proxy.Type;
-import java.net.Socket;
-import java.net.SocketException;
-import java.util.concurrent.ThreadPoolExecutor;
-
-import javax.net.ssl.SSLHandshakeException;
-
-import junit.framework.TestCase;
-
-import org.apache.commons.httpclient.HostConfiguration;
-import org.apache.commons.httpclient.HttpClient;
-import org.apache.commons.httpclient.HttpMethod;
-import org.apache.commons.httpclient.HttpMethodRetryHandler;
-import org.apache.commons.httpclient.HttpStatus;
-import org.apache.commons.httpclient.methods.GetMethod;
-import org.apache.commons.httpclient.params.HttpConnectionManagerParams;
-import org.apache.commons.httpclient.params.HttpMethodParams;
-import org.eclipse.core.net.proxy.IProxyData;
-import org.eclipse.core.runtime.IProgressMonitor;
-import org.eclipse.core.runtime.NullProgressMonitor;
-import org.eclipse.core.runtime.OperationCanceledException;
-import org.eclipse.mylyn.commons.core.CoreUtil;
-import org.eclipse.mylyn.commons.net.AbstractWebLocation;
-import org.eclipse.mylyn.commons.net.AuthenticationType;
-import org.eclipse.mylyn.commons.net.IProxyProvider;
-import org.eclipse.mylyn.commons.net.WebLocation;
-import org.eclipse.mylyn.commons.net.WebUtil;
-import org.eclipse.mylyn.commons.sdk.util.CommonTestUtil;
-import org.eclipse.mylyn.commons.sdk.util.TestUrl;
-import org.eclipse.mylyn.commons.tests.support.TestProxy;
-import org.eclipse.mylyn.commons.tests.support.TestProxy.Message;
-import org.eclipse.mylyn.internal.commons.net.AuthenticatedProxy;
-import org.eclipse.mylyn.internal.commons.net.CommonsNetPlugin;
-import org.eclipse.mylyn.internal.commons.net.PollingInputStream;
-import org.eclipse.mylyn.internal.commons.net.PollingSslProtocolSocketFactory;
-import org.eclipse.mylyn.internal.commons.net.TimeoutInputStream;
-
-/**
- * @author Steffen Pingel
- */
-public class WebUtilTest extends TestCase {
-
- static class StubProgressMonitor implements IProgressMonitor {
-
- private volatile boolean canceled;
-
- public void beginTask(String name, int totalWork) {
- }
-
- public void done() {
- }
-
- public void internalWorked(double work) {
- }
-
- public boolean isCanceled() {
- return canceled;
- }
-
- public void setCanceled(boolean value) {
- this.canceled = value;
- }
-
- public void setTaskName(String name) {
- }
-
- public void subTask(String name) {
- }
-
- public void worked(int work) {
- }
-
- }
-
- private TestProxy testProxy;
-
- private HttpClient client;
-
- private InetSocketAddress proxyAddress;
-
- public WebUtilTest() {
- }
-
- @Override
- protected void setUp() throws Exception {
- super.setUp();
- testProxy = new TestProxy();
- int proxyPort = testProxy.startAndWait();
- assert proxyPort > 0;
- proxyAddress = new InetSocketAddress("localhost", proxyPort);
-
- client = new HttpClient();
- }
-
- @Override
- protected void tearDown() throws Exception {
- super.tearDown();
-
- testProxy.stop();
- }
-
- public void testConnectCancelStalledConnect() throws Exception {
- final StubProgressMonitor monitor = new StubProgressMonitor();
- String host = "google.com";
- int port = 9999;
-
- try {
- Runnable runner = new Runnable() {
- public void run() {
- try {
- Thread.sleep(500);
- } catch (InterruptedException e) {
- }
- monitor.canceled = true;
- }
- };
- new Thread(runner).start();
- WebUtil.connect(new Socket(), new InetSocketAddress(host, port), 5000, monitor);
- fail("Expected OperationCanceledException");
- } catch (OperationCanceledException expected) {
- assertTrue(monitor.isCanceled());
- } catch (ConnectException ignored) {
- System.err.println("Skipping testConnectCancelStalledConnect() due to blocking firewall");
- }
- }
-
- public void testConfigureClient() throws Exception {
- WebLocation location = new WebLocation(TestUrl.DEFAULT.getHttpOk().toString());
-
- WebUtil.createHostConfiguration(client, location, null /*monitor*/);
-
- HttpConnectionManagerParams params = client.getHttpConnectionManager().getParams();
- assertEquals(CoreUtil.TEST_MODE ? 2 : MAX_HTTP_HOST_CONNECTIONS_DEFAULT,
- params.getMaxConnectionsPerHost(HostConfiguration.ANY_HOST_CONFIGURATION));
- assertEquals(CoreUtil.TEST_MODE ? 20 : MAX_HTTP_TOTAL_CONNECTIONS_DEFAULT, params.getMaxTotalConnections());
- }
-
- public void testExecute() throws Exception {
- StubProgressMonitor monitor = new StubProgressMonitor();
- HttpClient client = new HttpClient();
- WebLocation location = new WebLocation(TestUrl.DEFAULT.getHttpOk().toString());
- HostConfiguration hostConfiguration = WebUtil.createHostConfiguration(client, location, monitor);
-
- GetMethod method = new GetMethod(location.getUrl());
- try {
- int result = WebUtil.execute(client, hostConfiguration, method, monitor);
- assertEquals(HttpStatus.SC_OK, result);
- } finally {
- WebUtil.releaseConnection(method, monitor);
- }
- }
-
- public void testExecuteCancelStalledConnect() throws Exception {
- final StubProgressMonitor monitor = new StubProgressMonitor();
- HttpClient client = new HttpClient();
- WebLocation location = new WebLocation(TestUrl.DEFAULT.getConnectionTimeout().toString());
- HostConfiguration hostConfiguration = WebUtil.createHostConfiguration(client, location, monitor);
-
- GetMethod method = new GetMethod(location.getUrl());
- try {
- Runnable runner = new Runnable() {
- public void run() {
- try {
- Thread.sleep(500);
- } catch (InterruptedException e) {
- }
- monitor.canceled = true;
- }
- };
- new Thread(runner).start();
- WebUtil.execute(client, hostConfiguration, method, monitor);
- client.executeMethod(method);
- fail("Expected OperationCanceledException");
- } catch (OperationCanceledException expected) {
- assertTrue(monitor.isCanceled());
- } catch (ConnectException ignored) {
- System.err.println("Skipping testExecuteCancelStalledConnect() due to blocking firewall");
- } finally {
- WebUtil.releaseConnection(method, monitor);
- }
- }
-
- public void testExecuteAlreadyCancelled() throws Exception {
- StubProgressMonitor monitor = new StubProgressMonitor();
- HttpClient client = new HttpClient();
- WebLocation location = new WebLocation(TestUrl.DEFAULT.getHttpOk().toString());
- HostConfiguration hostConfiguration = WebUtil.createHostConfiguration(client, location, monitor);
-
- GetMethod method = new GetMethod(location.getUrl());
- try {
- monitor.canceled = true;
- WebUtil.execute(client, hostConfiguration, method, monitor);
- fail("Expected InterruptedIOException");
- } catch (OperationCanceledException expected) {
- } finally {
- WebUtil.releaseConnection(method, monitor);
- }
- }
-
- public void testConfigureHttpClient() {
- HttpClient client = new HttpClient();
-
- WebUtil.configureHttpClient(client, "");
- assertEquals(WebUtil.getUserAgent(""), client.getParams().getParameter(HttpMethodParams.USER_AGENT));
-
- WebUtil.configureHttpClient(client, null);
- assertEquals(WebUtil.getUserAgent(""), client.getParams().getParameter(HttpMethodParams.USER_AGENT));
-
- WebUtil.configureHttpClient(client, "myagent");
- assertTrue(-1 != client.getParams().getParameter(HttpMethodParams.USER_AGENT).toString().indexOf("myagent"));
-
- // TODO test timeouts
- }
-
- public void testCreateHostConfigurationProxy() throws Exception {
- StubProgressMonitor monitor = new StubProgressMonitor();
- HttpClient client = new HttpClient();
- WebUtil.createHostConfiguration(client, new WebLocation(TestUrl.DEFAULT.getHttpOk().toString(), null, null,
- new IProxyProvider() {
- public Proxy getProxyForHost(String host, String proxyType) {
- assertEquals(IProxyData.HTTP_PROXY_TYPE, proxyType);
- return null;
- }
- }), monitor);
- WebUtil.createHostConfiguration(client, new WebLocation(TestUrl.DEFAULT.getHttpsOk().toString(), null, null,
- new IProxyProvider() {
- public Proxy getProxyForHost(String host, String proxyType) {
- assertEquals(IProxyData.HTTPS_PROXY_TYPE, proxyType);
- return null;
- }
- }), monitor);
- }
-
- public void testReadTimeout() throws Exception {
- // wait 5 seconds for thread pool to be idle
- for (int i = 0; i < 10; i++) {
- if (((ThreadPoolExecutor) CommonsNetPlugin.getExecutorService()).getActiveCount() == 0) {
- break;
- }
- Thread.sleep(500);
- }
- assertEquals(0, ((ThreadPoolExecutor) CommonsNetPlugin.getExecutorService()).getActiveCount());
-
- String url = "http://" + proxyAddress.getHostName() + ":" + proxyAddress.getPort() + "/";
- AbstractWebLocation location = new WebLocation(url, null, null, null);
- HostConfiguration hostConfiguration = WebUtil.createHostConfiguration(client, location, null);
-
- testProxy.addResponse(TestProxy.TIMEOUT);
-
- GetMethod method = new GetMethod("/");
- method.getParams().setSoTimeout(100);
- int statusCode = client.executeMethod(hostConfiguration, method);
- assertEquals(200, statusCode);
-
- PollingInputStream in = new PollingInputStream(new TimeoutInputStream(method.getResponseBodyAsStream(), 8192,
- 500L, -1), 1, new NullProgressMonitor());
- try {
- in.read();
- fail("expected InterruptedIOException");
- } catch (InterruptedIOException e) {
- // expected
- } finally {
- in.close();
- }
- Thread.sleep(500);
- assertEquals(0, ((ThreadPoolExecutor) CommonsNetPlugin.getExecutorService()).getActiveCount());
- }
-
- public void testLocationConnect() throws Exception {
- String url = "http://" + proxyAddress.getHostName() + ":" + proxyAddress.getPort() + "/";
- AbstractWebLocation location = new WebLocation(url, null, null, null);
- HostConfiguration hostConfiguration = WebUtil.createHostConfiguration(client, location, null);
-
- testProxy.addResponse(TestProxy.OK);
-
- GetMethod method = new GetMethod("/");
- int statusCode = client.executeMethod(hostConfiguration, method);
- assertEquals(200, statusCode);
-
- Message request = testProxy.getRequest();
- assertEquals("GET / HTTP/1.1", request.request);
- }
-
- public void testLocationConnectSsl() throws Exception {
- String url = "https://" + proxyAddress.getHostName() + ":" + proxyAddress.getPort() + "/";
- AbstractWebLocation location = new WebLocation(url, null, null, null);
- HostConfiguration hostConfiguration = WebUtil.createHostConfiguration(client, location, null);
-
- testProxy.setCloseOnConnect(true);
-
- GetMethod method = new GetMethod("/");
- try {
- int statusCode = client.executeMethod(hostConfiguration, method);
- fail("Expected SSLHandshakeException or connection reset, got status: " + statusCode);
- } catch (SSLHandshakeException e) {
- } catch (SocketException e) {
- assertEquals("Connection reset", e.getMessage());
- }
-
- assertFalse(testProxy.hasRequest());
- }
-
- public void testLocationConnectProxy() throws Exception {
- String url = "http://foo/bar";
- final Proxy proxy = new Proxy(Type.HTTP, proxyAddress);
- AbstractWebLocation location = new WebLocation(url, null, null, new IProxyProvider() {
- public Proxy getProxyForHost(String host, String proxyType) {
- return proxy;
- }
- });
- HostConfiguration hostConfiguration = WebUtil.createHostConfiguration(client, location, null);
-
- testProxy.addResponse(TestProxy.OK);
-
- GetMethod method = new GetMethod(WebUtil.getRequestPath(url));
- int statusCode = client.executeMethod(hostConfiguration, method);
- assertEquals(200, statusCode);
-
- Message request = testProxy.getRequest();
- assertEquals("GET http://foo/bar HTTP/1.1", request.request);
- }
-
- public void testLocationConnectProxyHttpAuth() throws Exception {
- String url = "http://foo/bar";
- final Proxy proxy = new Proxy(Type.HTTP, proxyAddress);
- WebLocation location = new WebLocation(url, "", "", new IProxyProvider() {
- public Proxy getProxyForHost(String host, String proxyType) {
- return proxy;
- }
- });
- location.setCredentials(AuthenticationType.HTTP, "user", "pass");
- HostConfiguration hostConfiguration = WebUtil.createHostConfiguration(client, location, null);
- client.getParams().setAuthenticationPreemptive(true);
-
- Message response = new Message("HTTP/1.1 401 Authentication required");
- response.headers.add("WWW-Authenticate: Basic realm=\"Foo\"");
- testProxy.addResponse(response);
- testProxy.addResponse(TestProxy.OK);
-
- GetMethod method = new GetMethod(url);
- int statusCode = client.executeMethod(hostConfiguration, method);
- assertEquals(401, statusCode);
-
- Message request = testProxy.getRequest();
- assertEquals("GET http://foo/bar HTTP/1.1", request.request);
- assertEquals("Basic dXNlcjpwYXNz", request.getHeaderValue("Authorization"));
- }
-
- public void testLocationConnectProxyNoProxyCredentials() throws Exception {
- String url = "http://foo/bar";
- final Proxy proxy = new Proxy(Type.HTTP, proxyAddress);
- AbstractWebLocation location = new WebLocation(url, "user", "pass", new IProxyProvider() {
- public Proxy getProxyForHost(String host, String proxyType) {
- return proxy;
- }
- });
- HostConfiguration hostConfiguration = WebUtil.createHostConfiguration(client, location, null);
-
- Message response = new Message("HTTP/1.1 407 Proxy authentication required");
- response.headers.add("Proxy-Authenticate: Basic realm=\"Foo\"");
- testProxy.addResponse(response);
- testProxy.addResponse(TestProxy.OK);
-
- GetMethod method = new GetMethod(url);
- int statusCode = client.executeMethod(hostConfiguration, method);
- assertEquals(407, statusCode);
-
- Message request = testProxy.getRequest();
- assertEquals("GET http://foo/bar HTTP/1.1", request.request);
-
- assertFalse("Expected HttpClient to close connection", testProxy.hasRequest());
- }
-
- public void testLocationConnectProxyProxyCredentials() throws Exception {
- String url = "http://foo/bar";
- final Proxy proxy = new AuthenticatedProxy(Type.HTTP, proxyAddress, "proxyUser", "proxyPass");
- AbstractWebLocation location = new WebLocation(url, "user", "pass", new IProxyProvider() {
- public Proxy getProxyForHost(String host, String proxyType) {
- return proxy;
- }
- });
- HostConfiguration hostConfiguration = WebUtil.createHostConfiguration(client, location, null);
- client.getParams().setAuthenticationPreemptive(true);
-
- Message response = new Message("HTTP/1.1 407 Proxy authentication required");
- response.headers.add("Proxy-Authenticate: Basic realm=\"Foo\"");
- testProxy.addResponse(response);
- testProxy.addResponse(TestProxy.OK);
-
- GetMethod method = new GetMethod(url);
- int statusCode = client.executeMethod(hostConfiguration, method);
- assertEquals(407, statusCode);
-
- Message request = testProxy.getRequest();
- assertEquals("GET http://foo/bar HTTP/1.1", request.request);
- assertEquals("Basic cHJveHlVc2VyOnByb3h5UGFzcw==", request.getHeaderValue("Proxy-Authorization"));
- }
-
- public void testLocationConnectProxyProxyCredentialsHttpAuth() throws Exception {
- String url = "http://foo/bar";
- final Proxy proxy = new AuthenticatedProxy(Type.HTTP, proxyAddress, "proxyUser", "proxyPass");
- WebLocation location = new WebLocation(url, "", "", new IProxyProvider() {
- public Proxy getProxyForHost(String host, String proxyType) {
- return proxy;
- }
- });
- location.setCredentials(AuthenticationType.HTTP, "user", "pass");
-
- HostConfiguration hostConfiguration = WebUtil.createHostConfiguration(client, location, null);
- client.getParams().setAuthenticationPreemptive(true);
-
- testProxy.addResponse(TestProxy.OK);
-
- GetMethod method = new GetMethod(url);
- int statusCode = client.executeMethod(hostConfiguration, method);
- assertEquals(200, statusCode);
-
- Message request = testProxy.getRequest();
- assertEquals("GET http://foo/bar HTTP/1.1", request.request);
- assertEquals("Basic cHJveHlVc2VyOnByb3h5UGFzcw==", request.getHeaderValue("Proxy-Authorization"));
- assertEquals("Basic dXNlcjpwYXNz", request.getHeaderValue("Authorization"));
- }
-
- public void testLocationSslConnectProxy() throws Exception {
- String url = "https://foo/bar";
- final Proxy proxy = new Proxy(Type.HTTP, proxyAddress);
- AbstractWebLocation location = new WebLocation(url, null, null, new IProxyProvider() {
- public Proxy getProxyForHost(String host, String proxyType) {
- return proxy;
- }
- });
- HostConfiguration hostConfiguration = WebUtil.createHostConfiguration(client, location, null);
- ;
-
- testProxy.addResponse(TestProxy.SERVICE_UNVAILABLE);
-
- GetMethod method = new GetMethod("/");
- int statusCode = client.executeMethod(hostConfiguration, method);
- assertEquals(503, statusCode);
-
- Message request = testProxy.getRequest();
- assertEquals("CONNECT foo:443 HTTP/1.1", request.request);
- }
-
- public void testLocationSslConnectProxyProxyCredentials() throws Exception {
- String url = "https://foo/bar";
- final Proxy proxy = new AuthenticatedProxy(Type.HTTP, proxyAddress, "proxyUser", "proxyPass");
- AbstractWebLocation location = new WebLocation(url, null, null, new IProxyProvider() {
- public Proxy getProxyForHost(String host, String proxyType) {
- return proxy;
- }
- });
- HostConfiguration hostConfiguration = WebUtil.createHostConfiguration(client, location, null);
- ;
- client.getParams().setAuthenticationPreemptive(true);
-
- testProxy.addResponse(TestProxy.SERVICE_UNVAILABLE);
-
- GetMethod method = new GetMethod("/");
- int statusCode = client.executeMethod(hostConfiguration, method);
- assertEquals(503, statusCode);
-
- Message request = testProxy.getRequest();
- assertEquals("CONNECT foo:443 HTTP/1.1", request.request);
- assertEquals("Basic cHJveHlVc2VyOnByb3h5UGFzcw==", request.getHeaderValue("Proxy-Authorization"));
- }
-
- public void testLocationSslConnectProxyNoProxyCredentials() throws Exception {
- String url = "https://foo/bar";
- final Proxy proxy = new Proxy(Type.HTTP, proxyAddress);
- AbstractWebLocation location = new WebLocation(url, null, null, new IProxyProvider() {
- public Proxy getProxyForHost(String host, String proxyType) {
- return proxy;
- }
- });
- HostConfiguration hostConfiguration = WebUtil.createHostConfiguration(client, location, null);
- ;
-
- Message response = new Message("HTTP/1.1 407 Proxy authentication required");
- response.headers.add("Proxy-Authenticate: Basic realm=\"Foo\"");
- testProxy.addResponse(response);
- testProxy.addResponse(TestProxy.SERVICE_UNVAILABLE);
-
- GetMethod method = new GetMethod("/");
- int statusCode = client.executeMethod(hostConfiguration, method);
- assertEquals(407, statusCode);
-
- Message request = testProxy.getRequest();
- assertEquals("CONNECT foo:443 HTTP/1.1", request.request);
-
- assertFalse("Expected HttpClient to close connection", testProxy.hasRequest());
- }
-
- public void testLocationSslConnectProxyTimeout() throws Exception {
- String url = "https://foo/bar";
- final Proxy proxy = new Proxy(Type.HTTP, proxyAddress);
- AbstractWebLocation location = new WebLocation(url, null, null, new IProxyProvider() {
- public Proxy getProxyForHost(String host, String proxyType) {
- return proxy;
- }
- });
- HostConfiguration hostConfiguration = WebUtil.createHostConfiguration(client, location, null);
-
- testProxy.addResponse(TestProxy.OK);
-
- GetMethod method = new GetMethod("/");
- // avoid second attempt to connect to proxy to get exception right away
- method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new HttpMethodRetryHandler() {
- public boolean retryMethod(HttpMethod method, IOException exception, int executionCount) {
- return false;
- }
- });
- try {
- int statusCode = client.executeMethod(hostConfiguration, method);
- fail("Expected SSLHandshakeException, got status: " + statusCode);
- } catch (SSLHandshakeException e) {
- } catch (SocketException e) {
- // connection reset, happens in some environments instead of SSLHandshakeExecption depending on how much data has been written before the socket is closed
- }
-
- Message request = testProxy.getRequest();
- assertEquals("CONNECT foo:443 HTTP/1.1", request.request);
- }
-
- public void testLocationConnectSslClientCert() throws Exception {
- if (CommonTestUtil.isCertificateAuthBroken()) {
- return; // skip test
- }
-
- String url = "https://mylyn.org/secure/";
- AbstractWebLocation location = new WebLocation(url);
- HostConfiguration hostConfiguration = WebUtil.createHostConfiguration(client, location, null);
-
- if (!((PollingSslProtocolSocketFactory) hostConfiguration.getProtocol().getSocketFactory()).hasKeyManager()) {
- return; // skip test if keystore property is not set
- }
-
- GetMethod method = new GetMethod(WebUtil.getRequestPath(url));
- int statusCode = client.executeMethod(hostConfiguration, method);
- assertEquals(200, statusCode);
- }
-
- public void testGetUserAgent() {
- String userAgent = WebUtil.getUserAgent(null);
- assertEquals(userAgent, WebUtil.getUserAgent(""));
- assertEquals(-1, userAgent.indexOf("null"));
- assertEquals(-1, userAgent.indexOf(" "));
- assertEquals(0, userAgent.indexOf("Mylyn"));
-
- userAgent = WebUtil.getUserAgent("abc");
- assertEquals(-1, userAgent.indexOf("null"));
- assertEquals(-1, userAgent.indexOf(" "));
- assertEquals(0, userAgent.indexOf("Mylyn"));
- assertTrue(userAgent.contains(" abc "));
- }
-
- public void testUrlParsers() {
- String url = "https://example.com:444/folder/file.txt";
- assertEquals(444, WebUtil.getPort(url));
- assertEquals("example.com", WebUtil.getHost(url));
- assertEquals("/folder/file.txt", WebUtil.getRequestPath(url));
-
- url = "http://example.com/";
- assertEquals(80, WebUtil.getPort(url));
- assertEquals("example.com", WebUtil.getHost(url));
- assertEquals("/", WebUtil.getRequestPath(url));
-
- url = "http://example.com";
- assertEquals(80, WebUtil.getPort(url));
- assertEquals("example.com", WebUtil.getHost(url));
- assertEquals("", WebUtil.getRequestPath(url));
-
- url = "https://example.com:321";
- assertEquals(321, WebUtil.getPort(url));
- assertEquals("example.com", WebUtil.getHost(url));
- assertEquals("", WebUtil.getRequestPath(url));
-
- url = "example.com:321";
- assertEquals(321, WebUtil.getPort(url));
- assertEquals("example.com", WebUtil.getHost(url));
- assertEquals("", WebUtil.getRequestPath(url));
-
- url = "https://example.com:444/folder/file.txt?search=https://example.com:812/folder/file.txt";
- assertEquals(444, WebUtil.getPort(url));
- assertEquals("example.com", WebUtil.getHost(url));
- assertEquals("/folder/file.txt?search=https://example.com:812/folder/file.txt", WebUtil.getRequestPath(url));
-
- url = "https://example.com/folder/file.txt?search=https://example.com:812/folder/file.txt";
- assertEquals(443, WebUtil.getPort(url));
- assertEquals("example.com", WebUtil.getHost(url));
- assertEquals("/folder/file.txt?search=https://example.com:812/folder/file.txt", WebUtil.getRequestPath(url));
-
- url = "https://jira.codehaus.org/sr/jira.issueviews:searchrequest-xml/temp/SearchRequest.xml?&pid=11093&resolution=-1&sorter/field=updated&sorter/order=DESC&tempMax=1000";
- assertEquals(443, WebUtil.getPort(url));
- assertEquals("jira.codehaus.org", WebUtil.getHost(url));
- assertEquals(
- "/sr/jira.issueviews:searchrequest-xml/temp/SearchRequest.xml?&pid=11093&resolution=-1&sorter/field=updated&sorter/order=DESC&tempMax=1000",
- WebUtil.getRequestPath(url));
- }
-
- public void testGetTitleFromUrl() throws Exception {
- assertEquals("Eclipse Mylyn Open Source Project",
- WebUtil.getTitleFromUrl(new WebLocation(TestUrl.DEFAULT.getHttpOk().toString()), null));
- // disabled: fails in environments where the DNS resolver redirects for unknown hosts
- // try {
-// String title = WebUtil.getTitleFromUrl(new WebLocation("http://invalidurl"), null);
-// fail("Expected UnknownHostException, got: " + title);
-// } catch (UnknownHostException e) {
-// }
- String url = "http://" + proxyAddress.getHostName() + ":" + proxyAddress.getPort() + "/";
- testProxy.addResponse(TestProxy.OK);
- assertNull(WebUtil.getTitleFromUrl(new WebLocation(url), null));
- }
-
- /**
- * Default encoding needs to be set to non-UTF8 encoding for this test to be meaningful, e.g.
- * <code>-Dfile.encoding=ISO-8859-1</code>.
- */
- public void testGetTitleFromUrlUtf8() throws Exception {
- String message = "HTTP/1.1 200 OK\n" + "Date: Sat, 03 Jan 2009 14:40:23 GMT\n" + "Connection: close\n"
- + "Content-Type: text/html; charset=UTF-8\n" + "Content-Length: 30\n" + "\n"
- + "<html><title>\u00C3\u00BC</title></html>";
- testProxy.addResponse(message);
- String url = "http://" + proxyAddress.getHostName() + ":" + proxyAddress.getPort() + "/";
- assertEquals("\u00FC", WebUtil.getTitleFromUrl(new WebLocation(url), null));
- }
-
- // FIXME
-// public void testGetPlatformProxyDefault() {
-// assertNull(WebUtil.getProxy("mylyn.eclipse.org", Type.HTTP));
-// assertNull(WebUtil.getProxy("mylyn.eclipse.org", Type.DIRECT));
-// assertNull(WebUtil.getProxy("mylyn.eclipse.org", Type.SOCKS));
-// }
-
-// public void testGetPlatformProxy() {
-// IProxyService defaultProxyService = WebUtil.getProxyService();
-// try {
-// StubProxyService proxyService = new StubProxyService();
-// WebUtil.setProxyService(proxyService);
-// proxyService.setProxy(IProxyData.HTTP_PROXY_TYPE, "proxy", 8080, false);
-// Proxy proxy = WebUtil.getProxy("mylyn.eclipse.org", Type.HTTP);
-// assertNotNull(proxy);
-// assertEquals(Proxy.Type.HTTP, proxy.type());
-// proxy = WebUtil.getProxy("mylyn.eclipse.org", Type.SOCKS);
-// assertNull(proxy);
-// } finally {
-// WebUtil.setProxyService(defaultProxyService);
-// }
-// }
-
-}
+/*******************************************************************************
+ * Copyright (c) 2004, 2014 Tasktop Technologies and others.
+ * All rights reserved. This program and the accompanying materials
+ * are made available under the terms of the Eclipse Public License v1.0
+ * which accompanies this distribution, and is available at
+ * http://www.eclipse.org/legal/epl-v10.html
+ *
+ * Contributors:
+ * Tasktop Technologies - initial API and implementation
+ *******************************************************************************/
+
+package org.eclipse.mylyn.commons.tests.net;
+
+import static org.eclipse.mylyn.commons.tests.net.NetUtilTest.MAX_HTTP_HOST_CONNECTIONS_DEFAULT;
+import static org.eclipse.mylyn.commons.tests.net.NetUtilTest.MAX_HTTP_TOTAL_CONNECTIONS_DEFAULT;
+
+import java.io.IOException;
+import java.io.InterruptedIOException;
+import java.net.ConnectException;
+import java.net.InetSocketAddress;
+import java.net.Proxy;
+import java.net.Proxy.Type;
+import java.net.Socket;
+import java.net.SocketException;
+import java.util.concurrent.ThreadPoolExecutor;
+
+import javax.net.ssl.SSLHandshakeException;
+
+import org.apache.commons.httpclient.HostConfiguration;
+import org.apache.commons.httpclient.HttpClient;
+import org.apache.commons.httpclient.HttpMethod;
+import org.apache.commons.httpclient.HttpMethodRetryHandler;
+import org.apache.commons.httpclient.HttpStatus;
+import org.apache.commons.httpclient.methods.GetMethod;
+import org.apache.commons.httpclient.params.HttpConnectionManagerParams;
+import org.apache.commons.httpclient.params.HttpMethodParams;
+import org.eclipse.core.net.proxy.IProxyData;
+import org.eclipse.core.runtime.IProgressMonitor;
+import org.eclipse.core.runtime.NullProgressMonitor;
+import org.eclipse.core.runtime.OperationCanceledException;
+import org.eclipse.mylyn.commons.core.CoreUtil;
+import org.eclipse.mylyn.commons.net.AbstractWebLocation;
+import org.eclipse.mylyn.commons.net.AuthenticationType;
+import org.eclipse.mylyn.commons.net.IProxyProvider;
+import org.eclipse.mylyn.commons.net.WebLocation;
+import org.eclipse.mylyn.commons.net.WebUtil;
+import org.eclipse.mylyn.commons.sdk.util.CommonTestUtil;
+import org.eclipse.mylyn.commons.sdk.util.MockServer;
+import org.eclipse.mylyn.commons.sdk.util.MockServer.Message;
+import org.eclipse.mylyn.commons.sdk.util.TestUrl;
+import org.eclipse.mylyn.internal.commons.net.AuthenticatedProxy;
+import org.eclipse.mylyn.internal.commons.net.CommonsNetPlugin;
+import org.eclipse.mylyn.internal.commons.net.PollingInputStream;
+import org.eclipse.mylyn.internal.commons.net.PollingSslProtocolSocketFactory;
+import org.eclipse.mylyn.internal.commons.net.TimeoutInputStream;
+
+import junit.framework.TestCase;
+
+/**
+ * @author Steffen Pingel
+ */
+public class WebUtilTest extends TestCase {
+
+ static class StubProgressMonitor implements IProgressMonitor {
+
+ private volatile boolean canceled;
+
+ public void beginTask(String name, int totalWork) {
+ }
+
+ public void done() {
+ }
+
+ public void internalWorked(double work) {
+ }
+
+ public boolean isCanceled() {
+ return canceled;
+ }
+
+ public void setCanceled(boolean value) {
+ this.canceled = value;
+ }
+
+ public void setTaskName(String name) {
+ }
+
+ public void subTask(String name) {
+ }
+
+ public void worked(int work) {
+ }
+
+ }
+
+ private MockServer server;
+
+ private HttpClient client;
+
+ private InetSocketAddress proxyAddress;
+
+ public WebUtilTest() {
+ }
+
+ @Override
+ protected void setUp() throws Exception {
+ super.setUp();
+ server = new MockServer();
+ int proxyPort = server.startAndWait();
+ assert proxyPort > 0;
+ proxyAddress = new InetSocketAddress("localhost", proxyPort);
+
+ client = new HttpClient();
+ }
+
+ @Override
+ protected void tearDown() throws Exception {
+ super.tearDown();
+
+ server.stop();
+ }
+
+ public void testConnectCancelStalledConnect() throws Exception {
+ final StubProgressMonitor monitor = new StubProgressMonitor();
+ String host = "google.com";
+ int port = 9999;
+
+ try {
+ Runnable runner = new Runnable() {
+ public void run() {
+ try {
+ Thread.sleep(500);
+ } catch (InterruptedException e) {
+ }
+ monitor.canceled = true;
+ }
+ };
+ new Thread(runner).start();
+ WebUtil.connect(new Socket(), new InetSocketAddress(host, port), 5000, monitor);
+ fail("Expected OperationCanceledException");
+ } catch (OperationCanceledException expected) {
+ assertTrue(monitor.isCanceled());
+ } catch (ConnectException ignored) {
+ System.err.println("Skipping testConnectCancelStalledConnect() due to blocking firewall");
+ }
+ }
+
+ public void testConfigureClient() throws Exception {
+ WebLocation location = new WebLocation(TestUrl.DEFAULT.getHttpOk().toString());
+
+ WebUtil.createHostConfiguration(client, location, null /*monitor*/);
+
+ HttpConnectionManagerParams params = client.getHttpConnectionManager().getParams();
+ assertEquals(CoreUtil.TEST_MODE ? 2 : MAX_HTTP_HOST_CONNECTIONS_DEFAULT,
+ params.getMaxConnectionsPerHost(HostConfiguration.ANY_HOST_CONFIGURATION));
+ assertEquals(CoreUtil.TEST_MODE ? 20 : MAX_HTTP_TOTAL_CONNECTIONS_DEFAULT, params.getMaxTotalConnections());
+ }
+
+ public void testExecute() throws Exception {
+ StubProgressMonitor monitor = new StubProgressMonitor();
+ HttpClient client = new HttpClient();
+ WebLocation location = new WebLocation(TestUrl.DEFAULT.getHttpOk().toString());
+ HostConfiguration hostConfiguration = WebUtil.createHostConfiguration(client, location, monitor);
+
+ GetMethod method = new GetMethod(location.getUrl());
+ try {
+ int result = WebUtil.execute(client, hostConfiguration, method, monitor);
+ assertEquals(HttpStatus.SC_OK, result);
+ } finally {
+ WebUtil.releaseConnection(method, monitor);
+ }
+ }
+
+ public void testExecuteCancelStalledConnect() throws Exception {
+ final StubProgressMonitor monitor = new StubProgressMonitor();
+ HttpClient client = new HttpClient();
+ WebLocation location = new WebLocation(TestUrl.DEFAULT.getConnectionTimeout().toString());
+ HostConfiguration hostConfiguration = WebUtil.createHostConfiguration(client, location, monitor);
+
+ GetMethod method = new GetMethod(location.getUrl());
+ try {
+ Runnable runner = new Runnable() {
+ public void run() {
+ try {
+ Thread.sleep(500);
+ } catch (InterruptedException e) {
+ }
+ monitor.canceled = true;
+ }
+ };
+ new Thread(runner).start();
+ WebUtil.execute(client, hostConfiguration, method, monitor);
+ client.executeMethod(method);
+ fail("Expected OperationCanceledException");
+ } catch (OperationCanceledException expected) {
+ assertTrue(monitor.isCanceled());
+ } catch (ConnectException ignored) {
+ System.err.println("Skipping testExecuteCancelStalledConnect() due to blocking firewall");
+ } finally {
+ WebUtil.releaseConnection(method, monitor);
+ }
+ }
+
+ public void testExecuteAlreadyCancelled() throws Exception {
+ StubProgressMonitor monitor = new StubProgressMonitor();
+ HttpClient client = new HttpClient();
+ WebLocation location = new WebLocation(TestUrl.DEFAULT.getHttpOk().toString());
+ HostConfiguration hostConfiguration = WebUtil.createHostConfiguration(client, location, monitor);
+
+ GetMethod method = new GetMethod(location.getUrl());
+ try {
+ monitor.canceled = true;
+ WebUtil.execute(client, hostConfiguration, method, monitor);
+ fail("Expected InterruptedIOException");
+ } catch (OperationCanceledException expected) {
+ } finally {
+ WebUtil.releaseConnection(method, monitor);
+ }
+ }
+
+ public void testConfigureHttpClient() {
+ HttpClient client = new HttpClient();
+
+ WebUtil.configureHttpClient(client, "");
+ assertEquals(WebUtil.getUserAgent(""), client.getParams().getParameter(HttpMethodParams.USER_AGENT));
+
+ WebUtil.configureHttpClient(client, null);
+ assertEquals(WebUtil.getUserAgent(""), client.getParams().getParameter(HttpMethodParams.USER_AGENT));
+
+ WebUtil.configureHttpClient(client, "myagent");
+ assertTrue(-1 != client.getParams().getParameter(HttpMethodParams.USER_AGENT).toString().indexOf("myagent"));
+
+ // TODO test timeouts
+ }
+
+ public void testCreateHostConfigurationProxy() throws Exception {
+ StubProgressMonitor monitor = new StubProgressMonitor();
+ HttpClient client = new HttpClient();
+ WebUtil.createHostConfiguration(client,
+ new WebLocation(TestUrl.DEFAULT.getHttpOk().toString(), null, null, new IProxyProvider() {
+ public Proxy getProxyForHost(String host, String proxyType) {
+ assertEquals(IProxyData.HTTP_PROXY_TYPE, proxyType);
+ return null;
+ }
+ }), monitor);
+ WebUtil.createHostConfiguration(client,
+ new WebLocation(TestUrl.DEFAULT.getHttpsOk().toString(), null, null, new IProxyProvider() {
+ public Proxy getProxyForHost(String host, String proxyType) {
+ assertEquals(IProxyData.HTTPS_PROXY_TYPE, proxyType);
+ return null;
+ }
+ }), monitor);
+ }
+
+ public void testReadTimeout() throws Exception {
+ // wait 5 seconds for thread pool to be idle
+ for (int i = 0; i < 10; i++) {
+ if (((ThreadPoolExecutor) CommonsNetPlugin.getExecutorService()).getActiveCount() == 0) {
+ break;
+ }
+ Thread.sleep(500);
+ }
+ assertEquals(0, ((ThreadPoolExecutor) CommonsNetPlugin.getExecutorService()).getActiveCount());
+
+ String url = "http://" + proxyAddress.getHostName() + ":" + proxyAddress.getPort() + "/";
+ AbstractWebLocation location = new WebLocation(url, null, null, null);
+ HostConfiguration hostConfiguration = WebUtil.createHostConfiguration(client, location, null);
+
+ server.addResponse(MockServer.TIMEOUT);
+
+ GetMethod method = new GetMethod("/");
+ method.getParams().setSoTimeout(100);
+ int statusCode = client.executeMethod(hostConfiguration, method);
+ assertEquals(200, statusCode);
+
+ PollingInputStream in = new PollingInputStream(
+ new TimeoutInputStream(method.getResponseBodyAsStream(), 8192, 500L, -1), 1, new NullProgressMonitor());
+ try {
+ in.read();
+ fail("expected InterruptedIOException");
+ } catch (InterruptedIOException e) {
+ // expected
+ } finally {
+ in.close();
+ }
+ Thread.sleep(500);
+ assertEquals(0, ((ThreadPoolExecutor) CommonsNetPlugin.getExecutorService()).getActiveCount());
+ }
+
+ public void testLocationConnect() throws Exception {
+ String url = "http://" + proxyAddress.getHostName() + ":" + proxyAddress.getPort() + "/";
+ AbstractWebLocation location = new WebLocation(url, null, null, null);
+ HostConfiguration hostConfiguration = WebUtil.createHostConfiguration(client, location, null);
+
+ server.addResponse(MockServer.OK);
+
+ GetMethod method = new GetMethod("/");
+ int statusCode = client.executeMethod(hostConfiguration, method);
+ assertEquals(200, statusCode);
+
+ Message request = server.getRequest();
+ assertEquals("GET / HTTP/1.1", request.request);
+ }
+
+ public void testLocationConnectSsl() throws Exception {
+ String url = "https://" + proxyAddress.getHostName() + ":" + proxyAddress.getPort() + "/";
+ AbstractWebLocation location = new WebLocation(url, null, null, null);
+ HostConfiguration hostConfiguration = WebUtil.createHostConfiguration(client, location, null);
+
+ server.setCloseOnConnect(true);
+
+ GetMethod method = new GetMethod("/");
+ try {
+ int statusCode = client.executeMethod(hostConfiguration, method);
+ fail("Expected SSLHandshakeException or connection reset, got status: " + statusCode);
+ } catch (SSLHandshakeException e) {
+ } catch (SocketException e) {
+ assertEquals("Connection reset", e.getMessage());
+ }
+
+ assertFalse(server.hasRequest());
+ }
+
+ public void testLocationConnectProxy() throws Exception {
+ String url = "http://foo/bar";
+ final Proxy proxy = new Proxy(Type.HTTP, proxyAddress);
+ AbstractWebLocation location = new WebLocation(url, null, null, new IProxyProvider() {
+ public Proxy getProxyForHost(String host, String proxyType) {
+ return proxy;
+ }
+ });
+ HostConfiguration hostConfiguration = WebUtil.createHostConfiguration(client, location, null);
+
+ server.addResponse(MockServer.OK);
+
+ GetMethod method = new GetMethod(WebUtil.getRequestPath(url));
+ int statusCode = client.executeMethod(hostConfiguration, method);
+ assertEquals(200, statusCode);
+
+ Message request = server.getRequest();
+ assertEquals("GET http://foo/bar HTTP/1.1", request.request);
+ }
+
+ public void testLocationConnectProxyHttpAuth() throws Exception {
+ String url = "http://foo/bar";
+ final Proxy proxy = new Proxy(Type.HTTP, proxyAddress);
+ WebLocation location = new WebLocation(url, "", "", new IProxyProvider() {
+ public Proxy getProxyForHost(String host, String proxyType) {
+ return proxy;
+ }
+ });
+ location.setCredentials(AuthenticationType.HTTP, "user", "pass");
+ HostConfiguration hostConfiguration = WebUtil.createHostConfiguration(client, location, null);
+ client.getParams().setAuthenticationPreemptive(true);
+
+ Message response = new Message("HTTP/1.1 401 Authentication required");
+ response.headers.add("WWW-Authenticate: Basic realm=\"Foo\"");
+ server.addResponse(response);
+ server.addResponse(MockServer.OK);
+
+ GetMethod method = new GetMethod(url);
+ int statusCode = client.executeMethod(hostConfiguration, method);
+ assertEquals(401, statusCode);
+
+ Message request = server.getRequest();
+ assertEquals("GET http://foo/bar HTTP/1.1", request.request);
+ assertEquals("Basic dXNlcjpwYXNz", request.getHeaderValue("Authorization"));
+ }
+
+ public void testLocationConnectProxyNoProxyCredentials() throws Exception {
+ String url = "http://foo/bar";
+ final Proxy proxy = new Proxy(Type.HTTP, proxyAddress);
+ AbstractWebLocation location = new WebLocation(url, "user", "pass", new IProxyProvider() {
+ public Proxy getProxyForHost(String host, String proxyType) {
+ return proxy;
+ }
+ });
+ HostConfiguration hostConfiguration = WebUtil.createHostConfiguration(client, location, null);
+
+ Message response = new Message("HTTP/1.1 407 Proxy authentication required");
+ response.headers.add("Proxy-Authenticate: Basic realm=\"Foo\"");
+ server.addResponse(response);
+ server.addResponse(MockServer.OK);
+
+ GetMethod method = new GetMethod(url);
+ int statusCode = client.executeMethod(hostConfiguration, method);
+ assertEquals(407, statusCode);
+
+ Message request = server.getRequest();
+ assertEquals("GET http://foo/bar HTTP/1.1", request.request);
+
+ assertFalse("Expected HttpClient to close connection", server.hasRequest());
+ }
+
+ public void testLocationConnectProxyProxyCredentials() throws Exception {
+ String url = "http://foo/bar";
+ final Proxy proxy = new AuthenticatedProxy(Type.HTTP, proxyAddress, "proxyUser", "proxyPass");
+ AbstractWebLocation location = new WebLocation(url, "user", "pass", new IProxyProvider() {
+ public Proxy getProxyForHost(String host, String proxyType) {
+ return proxy;
+ }
+ });
+ HostConfiguration hostConfiguration = WebUtil.createHostConfiguration(client, location, null);
+ client.getParams().setAuthenticationPreemptive(true);
+
+ Message response = new Message("HTTP/1.1 407 Proxy authentication required");
+ response.headers.add("Proxy-Authenticate: Basic realm=\"Foo\"");
+ server.addResponse(response);
+ server.addResponse(MockServer.OK);
+
+ GetMethod method = new GetMethod(url);
+ int statusCode = client.executeMethod(hostConfiguration, method);
+ assertEquals(407, statusCode);
+
+ Message request = server.getRequest();
+ assertEquals("GET http://foo/bar HTTP/1.1", request.request);
+ assertEquals("Basic cHJveHlVc2VyOnByb3h5UGFzcw==", request.getHeaderValue("Proxy-Authorization"));
+ }
+
+ public void testLocationConnectProxyProxyCredentialsHttpAuth() throws Exception {
+ String url = "http://foo/bar";
+ final Proxy proxy = new AuthenticatedProxy(Type.HTTP, proxyAddress, "proxyUser", "proxyPass");
+ WebLocation location = new WebLocation(url, "", "", new IProxyProvider() {
+ public Proxy getProxyForHost(String host, String proxyType) {
+ return proxy;
+ }
+ });
+ location.setCredentials(AuthenticationType.HTTP, "user", "pass");
+
+ HostConfiguration hostConfiguration = WebUtil.createHostConfiguration(client, location, null);
+ client.getParams().setAuthenticationPreemptive(true);
+
+ server.addResponse(MockServer.OK);
+
+ GetMethod method = new GetMethod(url);
+ int statusCode = client.executeMethod(hostConfiguration, method);
+ assertEquals(200, statusCode);
+
+ Message request = server.getRequest();
+ assertEquals("GET http://foo/bar HTTP/1.1", request.request);
+ assertEquals("Basic cHJveHlVc2VyOnByb3h5UGFzcw==", request.getHeaderValue("Proxy-Authorization"));
+ assertEquals("Basic dXNlcjpwYXNz", request.getHeaderValue("Authorization"));
+ }
+
+ public void testLocationSslConnectProxy() throws Exception {
+ String url = "https://foo/bar";
+ final Proxy proxy = new Proxy(Type.HTTP, proxyAddress);
+ AbstractWebLocation location = new WebLocation(url, null, null, new IProxyProvider() {
+ public Proxy getProxyForHost(String host, String proxyType) {
+ return proxy;
+ }
+ });
+ HostConfiguration hostConfiguration = WebUtil.createHostConfiguration(client, location, null);
+ ;
+
+ server.addResponse(MockServer.SERVICE_UNVAILABLE);
+
+ GetMethod method = new GetMethod("/");
+ int statusCode = client.executeMethod(hostConfiguration, method);
+ assertEquals(503, statusCode);
+
+ Message request = server.getRequest();
+ assertEquals("CONNECT foo:443 HTTP/1.1", request.request);
+ }
+
+ public void testLocationSslConnectProxyProxyCredentials() throws Exception {
+ String url = "https://foo/bar";
+ final Proxy proxy = new AuthenticatedProxy(Type.HTTP, proxyAddress, "proxyUser", "proxyPass");
+ AbstractWebLocation location = new WebLocation(url, null, null, new IProxyProvider() {
+ public Proxy getProxyForHost(String host, String proxyType) {
+ return proxy;
+ }
+ });
+ HostConfiguration hostConfiguration = WebUtil.createHostConfiguration(client, location, null);
+ ;
+ client.getParams().setAuthenticationPreemptive(true);
+
+ server.addResponse(MockServer.SERVICE_UNVAILABLE);
+
+ GetMethod method = new GetMethod("/");
+ int statusCode = client.executeMethod(hostConfiguration, method);
+ assertEquals(503, statusCode);
+
+ Message request = server.getRequest();
+ assertEquals("CONNECT foo:443 HTTP/1.1", request.request);
+ assertEquals("Basic cHJveHlVc2VyOnByb3h5UGFzcw==", request.getHeaderValue("Proxy-Authorization"));
+ }
+
+ public void testLocationSslConnectProxyNoProxyCredentials() throws Exception {
+ String url = "https://foo/bar";
+ final Proxy proxy = new Proxy(Type.HTTP, proxyAddress);
+ AbstractWebLocation location = new WebLocation(url, null, null, new IProxyProvider() {
+ public Proxy getProxyForHost(String host, String proxyType) {
+ return proxy;
+ }
+ });
+ HostConfiguration hostConfiguration = WebUtil.createHostConfiguration(client, location, null);
+ ;
+
+ Message response = new Message("HTTP/1.1 407 Proxy authentication required");
+ response.headers.add("Proxy-Authenticate: Basic realm=\"Foo\"");
+ server.addResponse(response);
+ server.addResponse(MockServer.SERVICE_UNVAILABLE);
+
+ GetMethod method = new GetMethod("/");
+ int statusCode = client.executeMethod(hostConfiguration, method);
+ assertEquals(407, statusCode);
+
+ Message request = server.getRequest();
+ assertEquals("CONNECT foo:443 HTTP/1.1", request.request);
+
+ assertFalse("Expected HttpClient to close connection", server.hasRequest());
+ }
+
+ public void testLocationSslConnectProxyTimeout() throws Exception {
+ String url = "https://foo/bar";
+ final Proxy proxy = new Proxy(Type.HTTP, proxyAddress);
+ AbstractWebLocation location = new WebLocation(url, null, null, new IProxyProvider() {
+ public Proxy getProxyForHost(String host, String proxyType) {
+ return proxy;
+ }
+ });
+ HostConfiguration hostConfiguration = WebUtil.createHostConfiguration(client, location, null);
+
+ server.addResponse(MockServer.OK);
+
+ GetMethod method = new GetMethod("/");
+ // avoid second attempt to connect to proxy to get exception right away
+ method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new HttpMethodRetryHandler() {
+ public boolean retryMethod(HttpMethod method, IOException exception, int executionCount) {
+ return false;
+ }
+ });
+ try {
+ int statusCode = client.executeMethod(hostConfiguration, method);
+ fail("Expected SSLHandshakeException, got status: " + statusCode);
+ } catch (SSLHandshakeException e) {
+ } catch (SocketException e) {
+ // connection reset, happens in some environments instead of SSLHandshakeExecption depending on how much data has been written before the socket is closed
+ }
+
+ Message request = server.getRequest();
+ assertEquals("CONNECT foo:443 HTTP/1.1", request.request);
+ }
+
+ public void testLocationConnectSslClientCert() throws Exception {
+ if (CommonTestUtil.isCertificateAuthBroken()) {
+ return; // skip test
+ }
+
+ String url = "https://mylyn.org/secure/";
+ AbstractWebLocation location = new WebLocation(url);
+ HostConfiguration hostConfiguration = WebUtil.createHostConfiguration(client, location, null);
+
+ if (!((PollingSslProtocolSocketFactory) hostConfiguration.getProtocol().getSocketFactory()).hasKeyManager()) {
+ return; // skip test if keystore property is not set
+ }
+
+ GetMethod method = new GetMethod(WebUtil.getRequestPath(url));
+ int statusCode = client.executeMethod(hostConfiguration, method);
+ assertEquals(200, statusCode);
+ }
+
+ public void testGetUserAgent() {
+ String userAgent = WebUtil.getUserAgent(null);
+ assertEquals(userAgent, WebUtil.getUserAgent(""));
+ assertEquals(-1, userAgent.indexOf("null"));
+ assertEquals(-1, userAgent.indexOf(" "));
+ assertEquals(0, userAgent.indexOf("Mylyn"));
+
+ userAgent = WebUtil.getUserAgent("abc");
+ assertEquals(-1, userAgent.indexOf("null"));
+ assertEquals(-1, userAgent.indexOf(" "));
+ assertEquals(0, userAgent.indexOf("Mylyn"));
+ assertTrue(userAgent.contains(" abc "));
+ }
+
+ public void testUrlParsers() {
+ String url = "https://example.com:444/folder/file.txt";
+ assertEquals(444, WebUtil.getPort(url));
+ assertEquals("example.com", WebUtil.getHost(url));
+ assertEquals("/folder/file.txt", WebUtil.getRequestPath(url));
+
+ url = "http://example.com/";
+ assertEquals(80, WebUtil.getPort(url));
+ assertEquals("example.com", WebUtil.getHost(url));
+ assertEquals("/", WebUtil.getRequestPath(url));
+
+ url = "http://example.com";
+ assertEquals(80, WebUtil.getPort(url));
+ assertEquals("example.com", WebUtil.getHost(url));
+ assertEquals("", WebUtil.getRequestPath(url));
+
+ url = "https://example.com:321";
+ assertEquals(321, WebUtil.getPort(url));
+ assertEquals("example.com", WebUtil.getHost(url));
+ assertEquals("", WebUtil.getRequestPath(url));
+
+ url = "example.com:321";
+ assertEquals(321, WebUtil.getPort(url));
+ assertEquals("example.com", WebUtil.getHost(url));
+ assertEquals("", WebUtil.getRequestPath(url));
+
+ url = "https://example.com:444/folder/file.txt?search=https://example.com:812/folder/file.txt";
+ assertEquals(444, WebUtil.getPort(url));
+ assertEquals("example.com", WebUtil.getHost(url));
+ assertEquals("/folder/file.txt?search=https://example.com:812/folder/file.txt", WebUtil.getRequestPath(url));
+
+ url = "https://example.com/folder/file.txt?search=https://example.com:812/folder/file.txt";
+ assertEquals(443, WebUtil.getPort(url));
+ assertEquals("example.com", WebUtil.getHost(url));
+ assertEquals("/folder/file.txt?search=https://example.com:812/folder/file.txt", WebUtil.getRequestPath(url));
+
+ url = "https://jira.codehaus.org/sr/jira.issueviews:searchrequest-xml/temp/SearchRequest.xml?&pid=11093&resolution=-1&sorter/field=updated&sorter/order=DESC&tempMax=1000";
+ assertEquals(443, WebUtil.getPort(url));
+ assertEquals("jira.codehaus.org", WebUtil.getHost(url));
+ assertEquals(
+ "/sr/jira.issueviews:searchrequest-xml/temp/SearchRequest.xml?&pid=11093&resolution=-1&sorter/field=updated&sorter/order=DESC&tempMax=1000",
+ WebUtil.getRequestPath(url));
+ }
+
+ public void testGetTitleFromUrl() throws Exception {
+ assertEquals("Eclipse Mylyn Open Source Project",
+ WebUtil.getTitleFromUrl(new WebLocation(TestUrl.DEFAULT.getHttpOk().toString()), null));
+ // disabled: fails in environments where the DNS resolver redirects for unknown hosts
+ // try {
+// String title = WebUtil.getTitleFromUrl(new WebLocation("http://invalidurl"), null);
+// fail("Expected UnknownHostException, got: " + title);
+// } catch (UnknownHostException e) {
+// }
+ String url = "http://" + proxyAddress.getHostName() + ":" + proxyAddress.getPort() + "/";
+ server.addResponse(MockServer.OK);
+ assertNull(WebUtil.getTitleFromUrl(new WebLocation(url), null));
+ }
+
+ /**
+ * Default encoding needs to be set to non-UTF8 encoding for this test to be meaningful, e.g.
+ * <code>-Dfile.encoding=ISO-8859-1</code>.
+ */
+ public void testGetTitleFromUrlUtf8() throws Exception {
+ String message = "HTTP/1.1 200 OK\n" + "Date: Sat, 03 Jan 2009 14:40:23 GMT\n" + "Connection: close\n"
+ + "Content-Type: text/html; charset=UTF-8\n" + "Content-Length: 30\n" + "\n"
+ + "<html><title>\u00C3\u00BC</title></html>";
+ server.addResponse(message);
+ String url = "http://" + proxyAddress.getHostName() + ":" + proxyAddress.getPort() + "/";
+ assertEquals("\u00FC", WebUtil.getTitleFromUrl(new WebLocation(url), null));
+ }
+
+ // FIXME
+// public void testGetPlatformProxyDefault() {
+// assertNull(WebUtil.getProxy("mylyn.eclipse.org", Type.HTTP));
+// assertNull(WebUtil.getProxy("mylyn.eclipse.org", Type.DIRECT));
+// assertNull(WebUtil.getProxy("mylyn.eclipse.org", Type.SOCKS));
+// }
+
+// public void testGetPlatformProxy() {
+// IProxyService defaultProxyService = WebUtil.getProxyService();
+// try {
+// StubProxyService proxyService = new StubProxyService();
+// WebUtil.setProxyService(proxyService);
+// proxyService.setProxy(IProxyData.HTTP_PROXY_TYPE, "proxy", 8080, false);
+// Proxy proxy = WebUtil.getProxy("mylyn.eclipse.org", Type.HTTP);
+// assertNotNull(proxy);
+// assertEquals(Proxy.Type.HTTP, proxy.type());
+// proxy = WebUtil.getProxy("mylyn.eclipse.org", Type.SOCKS);
+// assertNull(proxy);
+// } finally {
+// WebUtil.setProxyService(defaultProxyService);
+// }
+// }
+
+}
diff --git a/org.eclipse.mylyn.commons.tests/src/org/eclipse/mylyn/commons/tests/support/TestProxy.java b/org.eclipse.mylyn.commons.tests/src/org/eclipse/mylyn/commons/tests/support/TestProxy.java
deleted file mode 100644
index 295fe2e..0000000
--- a/org.eclipse.mylyn.commons.tests/src/org/eclipse/mylyn/commons/tests/support/TestProxy.java
+++ /dev/null
@@ -1,376 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2004, 2011 Tasktop Technologies and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- * Contributors:
- * Tasktop Technologies - initial API and implementation
- *******************************************************************************/
-
-package org.eclipse.mylyn.commons.tests.support;
-
-import java.io.BufferedReader;
-import java.io.BufferedWriter;
-import java.io.EOFException;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.io.InterruptedIOException;
-import java.io.OutputStream;
-import java.io.OutputStreamWriter;
-import java.net.ServerSocket;
-import java.net.Socket;
-import java.util.ArrayList;
-import java.util.List;
-
-import junit.framework.AssertionFailedError;
-
-/**
- * @deprecated use {@link org.eclipse.mylyn.commons.sdk.util.TestProxy} instead
- * @author Steffen Pingel
- */
-@Deprecated
-public class TestProxy implements Runnable {
-
- public static String CRLF = "\r\n";
-
- public static class Message {
-
- public List<String> headers = new ArrayList<String>();
-
- public String request;
-
- private String charset;
-
- public Message(String request) {
- this.request = request;
- this.charset = "ISO-8859-1";
- }
-
- public String getCharset() {
- return charset;
- }
-
- public String getHeader(String prefix) {
- if (headers != null) {
- for (String header : headers) {
- if (header.startsWith(prefix)) {
- return header;
- }
- }
- }
- return null;
- }
-
- public String getHeaderValue(String prefix) {
- String header = getHeader(prefix);
- if (header != null) {
- int i = header.indexOf(": ");
- return (i != -1) ? header.substring(i + 2) : "";
- }
- return null;
- }
-
- public String getMethod() {
- int i = request.indexOf(" ");
- return (i != -1) ? request.substring(0, i) : request;
- }
-
- public void setCharset(String charset) {
- this.charset = charset;
- }
-
- public String getStatusLine() {
- int i = request.indexOf("\n");
- return (i != -1) ? request.substring(0, i) : request;
- }
-
- @Override
- public String toString() {
- StringBuilder sb = new StringBuilder();
- sb.append(request);
- sb.append("\n");
- if (headers != null) {
- for (String header : headers) {
- sb.append(header);
- sb.append("\n");
- }
- }
- sb.append("\n");
- return sb.toString().replaceAll("\n", CRLF);
- }
-
- }
-
- public static final String HEADER_CONNECTION_CLOSE = "Connection: Close";
-
- public static final String HEADER_NO_CONTENT = "Content-Length: 0";
-
- public static final Message NOT_FOUND = new Message("HTTP/1.1 404 Not Found");
-
- public static final Message OK = new Message("HTTP/1.1 200 OK");
-
- public static final Message TIMEOUT = new Message("HTTP/1.1 200 OK");
-
- public static final Message SERVICE_UNVAILABLE = createEmptyMessage("HTTP/1.1 503 Service Unavailable");
-
- static {
- NOT_FOUND.headers.add(HEADER_CONNECTION_CLOSE);
- OK.headers.add(HEADER_CONNECTION_CLOSE);
- SERVICE_UNVAILABLE.headers.add(HEADER_CONNECTION_CLOSE);
- TIMEOUT.headers.add("Content-Length: 500");
- }
-
- private static Message createEmptyMessage(String status) {
- return new Message(status + "\n" + HEADER_NO_CONTENT + "\n\n");
- }
-
- private boolean autoClose;
-
- private IOException exception;
-
- private final int listenPort;
-
- private final List<Message> requests = new ArrayList<Message>();
-
- private final List<Message> responses = new ArrayList<Message>();
-
- private Thread runner;
-
- private volatile ServerSocket serverSocket;
-
- private volatile boolean stopped;
-
- private boolean waitForResponse;
-
- private boolean closeOnConnect;
-
- private boolean debugEnabled;
-
- public TestProxy() {
- this(0);
- }
-
- public TestProxy(int listenPort) {
- this.listenPort = listenPort;
- this.autoClose = true;
- }
-
- public synchronized void addRequest(Message request) {
- this.requests.add(request);
- notifyAll();
- }
-
- public synchronized void addResponse(Message response) {
- this.responses.add(response);
- notifyAll();
- }
-
- public synchronized void addResponse(String response) {
- this.responses.add(new Message(response));
- notifyAll();
- }
-
- public synchronized void checkForException() throws IOException {
- if (exception != null) {
- throw exception;
- }
- }
-
- public int getPort() {
- return serverSocket.getLocalPort();
- }
-
- public synchronized Message getRequest() throws InterruptedException {
- if (requests.isEmpty()) {
- throw new AssertionFailedError("Request list is empty");
- }
- return requests.remove(0);
- }
-
- private void handleConnection(Socket socket) {
- try {
- while (!closeOnConnect && !stopped) {
- Message request = readMessage(socket.getInputStream());
- if (stopped || request == null) {
- break;
- }
- addRequest(request);
-
- if (hasMoreResponses() || waitForResponse) {
- Message response = waitForResponse();
- if (stopped || response == null) {
- break;
- }
- writeMessage(response, socket.getOutputStream());
-
- if (autoClose && response.toString().contains(HEADER_CONNECTION_CLOSE)) {
- break;
- }
- } else {
- writeMessage(SERVICE_UNVAILABLE, socket.getOutputStream());
- System.err.println("Unexpected request: ");
- System.err.println(request.toString());
- break;
- }
- }
- } catch (IOException e) {
- setException(e);
- } catch (InterruptedException e) {
- } finally {
- try {
- socket.close();
- } catch (IOException e1) {
- }
- }
- }
-
- private synchronized boolean hasMoreResponses() {
- return !responses.isEmpty();
- }
-
- public synchronized boolean hasRequest() {
- return !requests.isEmpty();
- }
-
- public boolean isAutoClose() {
- return autoClose;
- }
-
- public boolean isCloseOnConnect() {
- return closeOnConnect;
- }
-
- private Message readMessage(InputStream in) throws IOException {
- BufferedReader reader = new BufferedReader(new InputStreamReader(in));
- Message message = null;
- String line;
- while ((line = reader.readLine()) != null) {
- if (line.length() == 0) {
- if (message == null) {
- throw new IOException("Incomplete message");
- }
- return message;
- }
-
- if (message == null) {
- if (isDebugEnabled()) {
- System.err.println("< " + line);
- }
- message = new Message(line);
- } else {
- message.headers.add(line);
- }
- }
- throw new EOFException();
- }
-
- public void run() {
- try {
- serverSocket = new ServerSocket(listenPort);
- while (!stopped) {
- Socket socket = serverSocket.accept();
- handleConnection(socket);
- }
- } catch (InterruptedIOException e) {
- // ignore
- } catch (IOException e) {
- setException(e);
- } finally {
- if (serverSocket != null) {
- try {
- serverSocket.close();
- } catch (IOException e) {
- }
- }
- }
-
- }
-
- public void setCloseOnConnect(boolean closeOnConnect) {
- this.closeOnConnect = closeOnConnect;
- }
-
- public void setAutoClose(boolean autoClose) {
- this.autoClose = autoClose;
- }
-
- private synchronized void setException(IOException exception) {
- this.exception = exception;
- notifyAll();
- }
-
- public void setWaitForResponse(boolean waitForResponse) {
- this.waitForResponse = waitForResponse;
- }
-
- public void start() {
- runner = new Thread(this, "TestProxy :" + listenPort);
- runner.start();
- }
-
- public int startAndWait() throws InterruptedException {
- start();
- while (serverSocket == null || serverSocket.getLocalPort() == -1) {
- Thread.sleep(100);
- }
- return serverSocket.getLocalPort();
- }
-
- public void stop() {
- stopped = true;
- try {
- if (serverSocket != null) {
- serverSocket.close();
- }
- } catch (IOException e1) {
- // ignore
- }
- runner.interrupt();
- try {
- runner.join(500);
- } catch (InterruptedException e) {
- }
- }
-
- public synchronized Message waitForRequest() throws InterruptedException {
- while (requests.isEmpty()) {
- if (stopped) {
- return null;
- }
- wait();
- }
- return requests.remove(0);
- }
-
- public synchronized Message waitForResponse() throws InterruptedException {
- while (!stopped && responses.isEmpty()) {
- if (stopped || autoClose) {
- return null;
- }
- wait();
- }
- return responses.remove(0);
- }
-
- private void writeMessage(Message message, OutputStream out) throws IOException {
- if (isDebugEnabled()) {
- System.err.println("> " + message.getStatusLine());
- }
-
- BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, message.getCharset()));
- writer.write(message.toString());
- writer.flush();
- }
-
- public boolean isDebugEnabled() {
- return debugEnabled;
- }
-
- public void setDebugEnabled(boolean debugEnabled) {
- this.debugEnabled = debugEnabled;
- }
-
-}