diff --git a/COPYING b/COPYING new file mode 100644 index 000000000..d64569567 --- /dev/null +++ b/COPYING @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/build.xml b/build.xml new file mode 100644 index 000000000..d058f1f58 --- /dev/null +++ b/build.xml @@ -0,0 +1,22 @@ + + + + + + + + + + + + + + + + + + + + + diff --git a/src/main/java/com/google/mockwebserver/MockResponse.java b/src/main/java/com/google/mockwebserver/MockResponse.java new file mode 100644 index 000000000..5d06275cc --- /dev/null +++ b/src/main/java/com/google/mockwebserver/MockResponse.java @@ -0,0 +1,146 @@ +/* + * Copyright (C) 2011 Google Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.google.mockwebserver; + +import static com.google.mockwebserver.MockWebServer.ASCII; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.util.ArrayList; +import java.util.List; + +/** + * A scripted response to be replayed by the mock web server. + */ +public final class MockResponse implements Cloneable { + private static final String EMPTY_BODY_HEADER = "Content-Length: 0"; + private static final String CHUNKED_BODY_HEADER = "Transfer-encoding: chunked"; + private static final byte[] EMPTY_BODY = new byte[0]; + + private String status = "HTTP/1.1 200 OK"; + private List headers = new ArrayList(); + private byte[] body = EMPTY_BODY; + private SocketPolicy socketPolicy = SocketPolicy.KEEP_OPEN; + + public MockResponse() { + headers.add(EMPTY_BODY_HEADER); + } + + @Override public MockResponse clone() { + try { + MockResponse result = (MockResponse) super.clone(); + result.headers = new ArrayList(result.headers); + return result; + } catch (CloneNotSupportedException e) { + throw new AssertionError(); + } + } + + /** + * Returns the HTTP response line, such as "HTTP/1.1 200 OK". + */ + public String getStatus() { + return status; + } + + public MockResponse setResponseCode(int code) { + this.status = "HTTP/1.1 " + code + " OK"; + return this; + } + + public MockResponse setStatus(String status) { + this.status = status; + return this; + } + + /** + * Returns the HTTP headers, such as "Content-Length: 0". + */ + public List getHeaders() { + return headers; + } + + public MockResponse clearHeaders() { + headers.clear(); + return this; + } + + public MockResponse addHeader(String header) { + headers.add(header); + return this; + } + + /** + * Returns an input stream containing the raw HTTP payload. + */ + public byte[] getBody() { + return body; + } + + public MockResponse setBody(byte[] body) { + if (this.body == EMPTY_BODY) { + headers.remove(EMPTY_BODY_HEADER); + } + this.headers.add("Content-Length: " + body.length); + this.body = body; + return this; + } + + public MockResponse setBody(String body) { + try { + return setBody(body.getBytes(ASCII)); + } catch (UnsupportedEncodingException e) { + throw new AssertionError(); + } + } + + public MockResponse setChunkedBody(byte[] body, int maxChunkSize) throws IOException { + headers.remove(EMPTY_BODY_HEADER); + headers.add(CHUNKED_BODY_HEADER); + + ByteArrayOutputStream bytesOut = new ByteArrayOutputStream(); + int pos = 0; + while (pos < body.length) { + int chunkSize = Math.min(body.length - pos, maxChunkSize); + bytesOut.write(Integer.toHexString(chunkSize).getBytes(ASCII)); + bytesOut.write("\r\n".getBytes(ASCII)); + bytesOut.write(body, pos, chunkSize); + bytesOut.write("\r\n".getBytes(ASCII)); + pos += chunkSize; + } + bytesOut.write("0\r\n\r\n".getBytes(ASCII)); // last chunk + empty trailer + crlf + this.body = bytesOut.toByteArray(); + return this; + } + + public MockResponse setChunkedBody(String body, int maxChunkSize) throws IOException { + return setChunkedBody(body.getBytes(ASCII), maxChunkSize); + } + + public SocketPolicy getSocketPolicy() { + return socketPolicy; + } + + public MockResponse setSocketPolicy(SocketPolicy socketPolicy) { + this.socketPolicy = socketPolicy; + return this; + } + + @Override public String toString() { + return status; + } +} diff --git a/src/main/java/com/google/mockwebserver/MockWebServer.java b/src/main/java/com/google/mockwebserver/MockWebServer.java new file mode 100644 index 000000000..a938a2779 --- /dev/null +++ b/src/main/java/com/google/mockwebserver/MockWebServer.java @@ -0,0 +1,503 @@ +/* + * Copyright (C) 2011 Google Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.google.mockwebserver; + +import static com.google.mockwebserver.SocketPolicy.DISCONNECT_AT_START; +import java.io.BufferedInputStream; +import java.io.BufferedOutputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.HttpURLConnection; +import java.net.InetAddress; +import java.net.InetSocketAddress; +import java.net.MalformedURLException; +import java.net.Proxy; +import java.net.ServerSocket; +import java.net.Socket; +import java.net.SocketException; +import java.net.URL; +import java.net.UnknownHostException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Iterator; +import java.util.List; +import java.util.Set; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.LinkedBlockingDeque; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.atomic.AtomicInteger; +import java.util.logging.Level; +import java.util.logging.Logger; +import javax.net.ssl.SSLSocket; +import javax.net.ssl.SSLSocketFactory; + +/** + * A scriptable web server. Callers supply canned responses and the server + * replays them upon request in sequence. + */ +public final class MockWebServer { + + static final String ASCII = "US-ASCII"; + + private static final Logger logger = Logger.getLogger(MockWebServer.class.getName()); + private final BlockingQueue requestQueue + = new LinkedBlockingQueue(); + private final BlockingQueue responseQueue + = new LinkedBlockingDeque(); + private final Set openClientSockets + = Collections.newSetFromMap(new ConcurrentHashMap()); + private boolean singleResponse; + private final AtomicInteger requestCount = new AtomicInteger(); + private int bodyLimit = Integer.MAX_VALUE; + private ServerSocket serverSocket; + private SSLSocketFactory sslSocketFactory; + private ExecutorService executor; + private boolean tunnelProxy; + + private int port = -1; + + public int getPort() { + if (port == -1) { + throw new IllegalStateException("Cannot retrieve port before calling play()"); + } + return port; + } + + public String getHostName() { + try { + return InetAddress.getLocalHost().getHostName(); + } catch (UnknownHostException e) { + throw new AssertionError(); + } + } + + public Proxy toProxyAddress() { + return new Proxy(Proxy.Type.HTTP, new InetSocketAddress(getHostName(), getPort())); + } + + /** + * Returns a URL for connecting to this server. + * + * @param path the request path, such as "/". + */ + public URL getUrl(String path) throws MalformedURLException, UnknownHostException { + return sslSocketFactory != null + ? new URL("https://" + getHostName() + ":" + getPort() + path) + : new URL("http://" + getHostName() + ":" + getPort() + path); + } + + /** + * Sets the number of bytes of the POST body to keep in memory to the given + * limit. + */ + public void setBodyLimit(int maxBodyLength) { + this.bodyLimit = maxBodyLength; + } + + /** + * Serve requests with HTTPS rather than otherwise. + * + * @param tunnelProxy whether to expect the HTTP CONNECT method before + * negotiating TLS. + */ + public void useHttps(SSLSocketFactory sslSocketFactory, boolean tunnelProxy) { + this.sslSocketFactory = sslSocketFactory; + this.tunnelProxy = tunnelProxy; + } + + /** + * Awaits the next HTTP request, removes it, and returns it. Callers should + * use this to verify the request sent was as intended. + */ + public RecordedRequest takeRequest() throws InterruptedException { + return requestQueue.take(); + } + + /** + * Returns the number of HTTP requests received thus far by this server. + * This may exceed the number of HTTP connections when connection reuse is + * in practice. + */ + public int getRequestCount() { + return requestCount.get(); + } + + public void enqueue(MockResponse response) { + responseQueue.add(response.clone()); + } + + /** + * By default, this class processes requests coming in by adding them to a + * queue and serves responses by removing them from another queue. This mode + * is appropriate for correctness testing. + * + *

Serving a single response causes the server to be stateless: requests + * are not enqueued, and responses are not dequeued. This mode is appropriate + * for benchmarking. + */ + public void setSingleResponse(boolean singleResponse) { + this.singleResponse = singleResponse; + } + + /** + * Equivalent to {@code play(0)}. + */ + public void play() throws IOException { + play(0); + } + + /** + * Starts the server, serves all enqueued requests, and shuts the server + * down. + * + * @param port the port to listen to, or 0 for any available port. + * Automated tests should always use port 0 to avoid flakiness when a + * specific port is unavailable. + */ + public void play(int port) throws IOException { + executor = Executors.newCachedThreadPool(); + serverSocket = new ServerSocket(port); + serverSocket.setReuseAddress(true); + + this.port = serverSocket.getLocalPort(); + executor.execute(namedRunnable("MockWebServer-accept-" + port, new Runnable() { + public void run() { + try { + acceptConnections(); + } catch (Throwable e) { + logger.log(Level.WARNING, "MockWebServer connection failed", e); + } + + /* + * This gnarly block of code will release all sockets and + * all thread, even if any close fails. + */ + try { + serverSocket.close(); + } catch (Throwable e) { + logger.log(Level.WARNING, "MockWebServer server socket close failed", e); + } + for (Iterator s = openClientSockets.iterator(); s.hasNext();) { + try { + s.next().close(); + s.remove(); + } catch (Throwable e) { + logger.log(Level.WARNING, "MockWebServer socket close failed", e); + } + } + try { + executor.shutdown(); + } catch (Throwable e) { + logger.log(Level.WARNING, "MockWebServer executor shutdown failed", e); + } + } + + private void acceptConnections() throws Exception { + do { + Socket socket; + try { + socket = serverSocket.accept(); + } catch (SocketException ignored) { + continue; + } + MockResponse peek = responseQueue.peek(); + if (peek != null && peek.getSocketPolicy() == DISCONNECT_AT_START) { + responseQueue.take(); + socket.close(); + } else { + openClientSockets.add(socket); + serveConnection(socket); + } + } while (!responseQueue.isEmpty()); + } + })); + } + + public void shutdown() throws IOException { + if (serverSocket != null) { + serverSocket.close(); // should cause acceptConnections() to break out + } + } + + private void serveConnection(final Socket raw) { + String name = "MockWebServer-" + raw.getRemoteSocketAddress(); + executor.execute(namedRunnable(name, new Runnable() { + int sequenceNumber = 0; + + public void run() { + try { + processConnection(); + } catch (Exception e) { + logger.log(Level.WARNING, "MockWebServer connection failed", e); + } + } + + public void processConnection() throws Exception { + Socket socket; + if (sslSocketFactory != null) { + if (tunnelProxy) { + createTunnel(); + } + socket = sslSocketFactory.createSocket( + raw, raw.getInetAddress().getHostAddress(), raw.getPort(), true); + ((SSLSocket) socket).setUseClientMode(false); + openClientSockets.add(socket); + openClientSockets.remove(raw); + } else { + socket = raw; + } + + InputStream in = new BufferedInputStream(socket.getInputStream()); + OutputStream out = new BufferedOutputStream(socket.getOutputStream()); + + while (!responseQueue.isEmpty() && processOneRequest(in, out, socket)) {} + + if (sequenceNumber == 0) { + logger.warning("MockWebServer connection didn't make a request"); + } + + in.close(); + out.close(); + socket.close(); + if (responseQueue.isEmpty()) { + shutdown(); + } + openClientSockets.remove(socket); + } + + /** + * Respond to CONNECT requests until a SWITCH_TO_SSL_AT_END response + * is dispatched. + */ + private void createTunnel() throws IOException, InterruptedException { + while (true) { + MockResponse connect = responseQueue.peek(); + if (!processOneRequest(raw.getInputStream(), raw.getOutputStream(), raw)) { + throw new IllegalStateException("Tunnel without any CONNECT!"); + } + if (connect.getSocketPolicy() == SocketPolicy.UPGRADE_TO_SSL_AT_END) { + return; + } + } + } + + /** + * Reads a request and writes its response. Returns true if a request + * was processed. + */ + private boolean processOneRequest(InputStream in, OutputStream out, Socket socket) + throws IOException, InterruptedException { + RecordedRequest request = readRequest(in, sequenceNumber); + if (request == null) { + return false; + } + MockResponse response = dispatch(request); + writeResponse(out, response); + if (response.getSocketPolicy() == SocketPolicy.DISCONNECT_AT_END) { + in.close(); + out.close(); + } else if (response.getSocketPolicy() == SocketPolicy.SHUTDOWN_INPUT_AT_END) { + socket.shutdownInput(); + } else if (response.getSocketPolicy() == SocketPolicy.SHUTDOWN_OUTPUT_AT_END) { + socket.shutdownOutput(); + } + sequenceNumber++; + return true; + } + })); + } + + /** + * @param sequenceNumber the index of this request on this connection. + */ + private RecordedRequest readRequest(InputStream in, int sequenceNumber) throws IOException { + String request; + try { + request = readAsciiUntilCrlf(in); + } catch (IOException streamIsClosed) { + return null; // no request because we closed the stream + } + if (request.isEmpty()) { + return null; // no request because the stream is exhausted + } + + List headers = new ArrayList(); + int contentLength = -1; + boolean chunked = false; + String header; + while (!(header = readAsciiUntilCrlf(in)).isEmpty()) { + headers.add(header); + String lowercaseHeader = header.toLowerCase(); + if (contentLength == -1 && lowercaseHeader.startsWith("content-length:")) { + contentLength = Integer.parseInt(header.substring(15).trim()); + } + if (lowercaseHeader.startsWith("transfer-encoding:") && + lowercaseHeader.substring(18).trim().equals("chunked")) { + chunked = true; + } + } + + boolean hasBody = false; + TruncatingOutputStream requestBody = new TruncatingOutputStream(); + List chunkSizes = new ArrayList(); + if (contentLength != -1) { + hasBody = true; + transfer(contentLength, in, requestBody); + } else if (chunked) { + hasBody = true; + while (true) { + int chunkSize = Integer.parseInt(readAsciiUntilCrlf(in).trim(), 16); + if (chunkSize == 0) { + readEmptyLine(in); + break; + } + chunkSizes.add(chunkSize); + transfer(chunkSize, in, requestBody); + readEmptyLine(in); + } + } + + if (request.startsWith("OPTIONS ") || request.startsWith("GET ") + || request.startsWith("HEAD ") || request.startsWith("DELETE ") + || request .startsWith("TRACE ") || request.startsWith("CONNECT ")) { + if (hasBody) { + throw new IllegalArgumentException("Request must not have a body: " + request); + } + } else if (request.startsWith("POST ") || request.startsWith("PUT ")) { + if (!hasBody) { + throw new IllegalArgumentException("Request must have a body: " + request); + } + } else { + throw new UnsupportedOperationException("Unexpected method: " + request); + } + + return new RecordedRequest(request, headers, chunkSizes, + requestBody.numBytesReceived, requestBody.toByteArray(), sequenceNumber); + } + + /** + * Returns a response to satisfy {@code request}. + */ + private MockResponse dispatch(RecordedRequest request) throws InterruptedException { + if (responseQueue.isEmpty()) { + throw new IllegalStateException("Unexpected request: " + request); + } + + // to permit interactive/browser testing, ignore requests for favicons + if (request.getRequestLine().equals("GET /favicon.ico HTTP/1.1")) { + System.out.println("served " + request.getRequestLine()); + return new MockResponse() + .setResponseCode(HttpURLConnection.HTTP_NOT_FOUND); + } + + if (singleResponse) { + return responseQueue.peek(); + } else { + requestCount.incrementAndGet(); + requestQueue.add(request); + return responseQueue.take(); + } + } + + private void writeResponse(OutputStream out, MockResponse response) throws IOException { + out.write((response.getStatus() + "\r\n").getBytes(ASCII)); + for (String header : response.getHeaders()) { + out.write((header + "\r\n").getBytes(ASCII)); + } + out.write(("\r\n").getBytes(ASCII)); + out.write(response.getBody()); + out.flush(); + } + + /** + * Transfer bytes from {@code in} to {@code out} until either {@code length} + * bytes have been transferred or {@code in} is exhausted. + */ + private void transfer(int length, InputStream in, OutputStream out) throws IOException { + byte[] buffer = new byte[1024]; + while (length > 0) { + int count = in.read(buffer, 0, Math.min(buffer.length, length)); + if (count == -1) { + return; + } + out.write(buffer, 0, count); + length -= count; + } + } + + /** + * Returns the text from {@code in} until the next "\r\n", or null if + * {@code in} is exhausted. + */ + private String readAsciiUntilCrlf(InputStream in) throws IOException { + StringBuilder builder = new StringBuilder(); + while (true) { + int c = in.read(); + if (c == '\n' && builder.length() > 0 && builder.charAt(builder.length() - 1) == '\r') { + builder.deleteCharAt(builder.length() - 1); + return builder.toString(); + } else if (c == -1) { + return builder.toString(); + } else { + builder.append((char) c); + } + } + } + + private void readEmptyLine(InputStream in) throws IOException { + String line = readAsciiUntilCrlf(in); + if (!line.isEmpty()) { + throw new IllegalStateException("Expected empty but was: " + line); + } + } + + /** + * An output stream that drops data after bodyLimit bytes. + */ + private class TruncatingOutputStream extends ByteArrayOutputStream { + private int numBytesReceived = 0; + @Override public void write(byte[] buffer, int offset, int len) { + numBytesReceived += len; + super.write(buffer, offset, Math.min(len, bodyLimit - count)); + } + @Override public void write(int oneByte) { + numBytesReceived++; + if (count < bodyLimit) { + super.write(oneByte); + } + } + } + + private static Runnable namedRunnable(final String name, final Runnable runnable) { + return new Runnable() { + public void run() { + String originalName = Thread.currentThread().getName(); + Thread.currentThread().setName(name); + try { + runnable.run(); + } finally { + Thread.currentThread().setName(originalName); + } + } + }; + } +} diff --git a/src/main/java/com/google/mockwebserver/RecordedRequest.java b/src/main/java/com/google/mockwebserver/RecordedRequest.java new file mode 100644 index 000000000..8f0908457 --- /dev/null +++ b/src/main/java/com/google/mockwebserver/RecordedRequest.java @@ -0,0 +1,85 @@ +/* + * Copyright (C) 2011 Google Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.google.mockwebserver; + +import java.util.List; + +/** + * An HTTP request that came into the mock web server. + */ +public final class RecordedRequest { + private final String requestLine; + private final List headers; + private final List chunkSizes; + private final int bodySize; + private final byte[] body; + private final int sequenceNumber; + + RecordedRequest(String requestLine, List headers, List chunkSizes, + int bodySize, byte[] body, int sequenceNumber) { + this.requestLine = requestLine; + this.headers = headers; + this.chunkSizes = chunkSizes; + this.bodySize = bodySize; + this.body = body; + this.sequenceNumber = sequenceNumber; + } + + public String getRequestLine() { + return requestLine; + } + + public List getHeaders() { + return headers; + } + + /** + * Returns the sizes of the chunks of this request's body, or an empty list + * if the request's body was empty or unchunked. + */ + public List getChunkSizes() { + return chunkSizes; + } + + /** + * Returns the total size of the body of this POST request (before + * truncation). + */ + public int getBodySize() { + return bodySize; + } + + /** + * Returns the body of this POST request. This may be truncated. + */ + public byte[] getBody() { + return body; + } + + /** + * Returns the index of this request on its HTTP connection. Since a single + * HTTP connection may serve multiple requests, each request is assigned its + * own sequence number. + */ + public int getSequenceNumber() { + return sequenceNumber; + } + + @Override public String toString() { + return requestLine; + } +} diff --git a/src/main/java/com/google/mockwebserver/SocketPolicy.java b/src/main/java/com/google/mockwebserver/SocketPolicy.java new file mode 100644 index 000000000..d256a45ba --- /dev/null +++ b/src/main/java/com/google/mockwebserver/SocketPolicy.java @@ -0,0 +1,64 @@ +/* + * Copyright (C) 2011 Google Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.google.mockwebserver; + +/** + * What should be done with the incoming socket. + */ +public enum SocketPolicy { + + /** + * Keep the socket open after the response. This is the default HTTP/1.1 + * behavior. + */ + KEEP_OPEN, + + /** + * Close the socket after the response. This is the default HTTP/1.0 + * behavior. + */ + DISCONNECT_AT_END, + + /** + * Wrap the socket with SSL at the completion of this request/response + * pair. Used for CONNECT messages to tunnel SSL over an HTTP proxy. + */ + UPGRADE_TO_SSL_AT_END, + + /** + * Request immediate close of connection without even reading the + * request. + * + *

Use to simulate the real life case of losing connection + * because of bugger SSL server close connection when it seems + * something like a compression method or TLS extension it doesn't + * understand, instead of simply ignoring it like it should. + */ + DISCONNECT_AT_START, + + /** + * Shutdown the socket input after sending the response. For testing bad + * behavior. + */ + SHUTDOWN_INPUT_AT_END, + + /** + * Shutdown the socket output after sending the response. For testing bad + * behavior. + */ + SHUTDOWN_OUTPUT_AT_END +}