Skip to main content
summaryrefslogtreecommitdiffstats
blob: 915d1bbd9b5c82ed53b38aa2e786a38177c81e29 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
/*******************************************************************************
 * Copyright (c) 2004, 2010 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.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
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;
	}

}

Back to the top