Search in sources :

Example 21 with InputStream

use of java.io.InputStream in project jetty.project by eclipse.

the class ProxyServletFailureTest method testClientRequestStallsHeadersProxyIdlesTimeout.

@Test
public void testClientRequestStallsHeadersProxyIdlesTimeout() throws Exception {
    prepareProxy();
    int idleTimeout = 2000;
    proxyConnector.setIdleTimeout(idleTimeout);
    prepareServer(new EchoHttpServlet());
    try (Socket socket = new Socket("localhost", proxyConnector.getLocalPort())) {
        String serverHostPort = "localhost:" + serverConnector.getLocalPort();
        String request = "" + "GET http://" + serverHostPort + " HTTP/1.1\r\n" + "Host: " + serverHostPort + "\r\n";
        // Don't sent the \r\n that would signal the end of the headers.
        OutputStream output = socket.getOutputStream();
        output.write(request.getBytes("UTF-8"));
        output.flush();
        // Wait for idle timeout to fire.
        socket.setSoTimeout(2 * idleTimeout);
        InputStream input = socket.getInputStream();
        Assert.assertEquals(-1, input.read());
    }
}
Also used : InputStream(java.io.InputStream) OutputStream(java.io.OutputStream) Socket(java.net.Socket) Test(org.junit.Test)

Example 22 with InputStream

use of java.io.InputStream in project jetty.project by eclipse.

the class RequestTest method testMultiPartFormDataReadInputThenParams.

@Test
@Ignore("See issue #1175")
public void testMultiPartFormDataReadInputThenParams() throws Exception {
    final File tmpdir = MavenTestingUtils.getTargetTestingDir("multipart");
    FS.ensureEmpty(tmpdir);
    Handler handler = new AbstractHandler() {

        @Override
        public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
            if (baseRequest.getDispatcherType() != DispatcherType.REQUEST)
                return;
            // Fake a @MultiPartConfig'd servlet endpoint
            MultipartConfigElement multipartConfig = new MultipartConfigElement(tmpdir.getAbsolutePath());
            request.setAttribute(Request.__MULTIPART_CONFIG_ELEMENT, multipartConfig);
            // Normal processing
            baseRequest.setHandled(true);
            // Fake the commons-fileupload behavior
            int length = request.getContentLength();
            InputStream in = request.getInputStream();
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            // KEY STEP (Don't Change!) commons-fileupload does not read to EOF
            IO.copy(in, out, length);
            // Record what happened as servlet response headers
            response.setIntHeader("x-request-content-length", request.getContentLength());
            response.setIntHeader("x-request-content-read", out.size());
            // uri query parameter
            String foo = request.getParameter("foo");
            // form-data content parameter
            String bar = request.getParameter("bar");
            response.setHeader("x-foo", foo == null ? "null" : foo);
            response.setHeader("x-bar", bar == null ? "null" : bar);
        }
    };
    _server.stop();
    _server.setHandler(handler);
    _server.start();
    String multipart = "--AaBbCc\r\n" + "content-disposition: form-data; name=\"bar\"\r\n" + "\r\n" + "BarContent\r\n" + "--AaBbCc\r\n" + "content-disposition: form-data; name=\"stuff\"\r\n" + "Content-Type: text/plain;charset=ISO-8859-1\r\n" + "\r\n" + "000000000000000000000000000000000000000000000000000\r\n" + "--AaBbCc--\r\n";
    String request = "POST /?foo=FooUri HTTP/1.1\r\n" + "Host: whatever\r\n" + "Content-Type: multipart/form-data; boundary=\"AaBbCc\"\r\n" + "Content-Length: " + multipart.getBytes().length + "\r\n" + "Connection: close\r\n" + "\r\n" + multipart;
    HttpTester.Response response = HttpTester.parseResponse(_connector.getResponse(request));
    // It should always be possible to read query string
    assertThat("response.x-foo", response.get("x-foo"), is("FooUri"));
    // Not possible to read request content parameters?
    // TODO: should this work?
    assertThat("response.x-bar", response.get("x-bar"), is("null"));
}
Also used : ServletInputStream(javax.servlet.ServletInputStream) InputStream(java.io.InputStream) HttpServletRequest(javax.servlet.http.HttpServletRequest) AbstractHandler(org.eclipse.jetty.server.handler.AbstractHandler) ContextHandler(org.eclipse.jetty.server.handler.ContextHandler) HttpServletResponse(javax.servlet.http.HttpServletResponse) ByteArrayOutputStream(java.io.ByteArrayOutputStream) AbstractHandler(org.eclipse.jetty.server.handler.AbstractHandler) LocalEndPoint(org.eclipse.jetty.server.LocalConnector.LocalEndPoint) HttpTester(org.eclipse.jetty.http.HttpTester) HttpServletRequest(javax.servlet.http.HttpServletRequest) MultipartConfigElement(javax.servlet.MultipartConfigElement) File(java.io.File) Ignore(org.junit.Ignore) Test(org.junit.Test)

Example 23 with InputStream

use of java.io.InputStream in project jetty.project by eclipse.

the class HttpServerTestBase method testCloseWhileWriteBlocked.

@Test
public void testCloseWhileWriteBlocked() throws Exception {
    configureServer(new DataHandler());
    try (Socket client = newSocket(_serverURI.getHost(), _serverURI.getPort())) {
        OutputStream os = client.getOutputStream();
        InputStream is = client.getInputStream();
        os.write(("GET /data?encoding=iso-8859-1&writes=100&block=100000 HTTP/1.1\r\n" + "host: " + _serverURI.getHost() + ":" + _serverURI.getPort() + "\r\n" + "connection: close\r\n" + "content-type: unknown\r\n" + "\r\n").getBytes());
        os.flush();
        // Read the first part of the response
        byte[] buf = new byte[1024 * 8];
        is.read(buf);
        // sleep to ensure server is blocking
        Thread.sleep(500);
        // Close the client
        client.close();
    }
    Thread.sleep(200);
    // check server is still handling requests quickly
    try (Socket client = newSocket(_serverURI.getHost(), _serverURI.getPort())) {
        client.setSoTimeout(500);
        OutputStream os = client.getOutputStream();
        InputStream is = client.getInputStream();
        os.write(("GET /data?writes=1&block=1024 HTTP/1.1\r\n" + "host: " + _serverURI.getHost() + ":" + _serverURI.getPort() + "\r\n" + "connection: close\r\n" + "content-type: unknown\r\n" + "\r\n").getBytes());
        os.flush();
        String response = IO.toString(is);
        assertThat(response, startsWith("HTTP/1.1 200 OK"));
    }
}
Also used : ServletInputStream(javax.servlet.ServletInputStream) InputStream(java.io.InputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ServletOutputStream(javax.servlet.ServletOutputStream) OutputStream(java.io.OutputStream) Matchers.containsString(org.hamcrest.Matchers.containsString) Socket(java.net.Socket) Test(org.junit.Test)

Example 24 with InputStream

use of java.io.InputStream in project jetty.project by eclipse.

the class NetworkTrafficListenerTest method testTrafficWithBigRequestContentOnPersistentConnection.

@Test
public void testTrafficWithBigRequestContentOnPersistentConnection() throws Exception {
    initConnector(new AbstractHandler() {

        @Override
        public void handle(String uri, Request request, HttpServletRequest servletRequest, HttpServletResponse servletResponse) throws IOException, ServletException {
            // Read and discard the request body to make the test more
            // reliable, otherwise there is a race between request body
            // upload and response download
            InputStream input = servletRequest.getInputStream();
            byte[] buffer = new byte[4096];
            while (true) {
                int read = input.read(buffer);
                if (read < 0)
                    break;
            }
            request.setHandled(true);
        }
    });
    final AtomicReference<String> incomingData = new AtomicReference<>("");
    final AtomicReference<String> outgoingData = new AtomicReference<>("");
    final CountDownLatch outgoingLatch = new CountDownLatch(1);
    connector.addNetworkTrafficListener(new NetworkTrafficListener.Adapter() {

        @Override
        public void incoming(Socket socket, ByteBuffer bytes) {
            incomingData.set(incomingData.get() + BufferUtil.toString(bytes, StandardCharsets.UTF_8));
        }

        @Override
        public void outgoing(Socket socket, ByteBuffer bytes) {
            outgoingData.set(outgoingData.get() + BufferUtil.toString(bytes, StandardCharsets.UTF_8));
            outgoingLatch.countDown();
        }
    });
    int port = connector.getLocalPort();
    // Generate 32 KiB of request content
    String requestContent = "0123456789ABCDEF";
    for (int i = 0; i < 11; ++i) requestContent += requestContent;
    String request = "" + "POST / HTTP/1.1\r\n" + "Host: localhost:" + port + "\r\n" + "Content-Type: text/plain\r\n" + "Content-Length: " + requestContent.length() + "\r\n" + "\r\n" + requestContent;
    String expectedResponse = "" + "HTTP/1.1 200 OK\r\n" + "Content-Length: 0\r\n" + "\r\n";
    Socket socket = new Socket("localhost", port);
    OutputStream output = socket.getOutputStream();
    output.write(request.getBytes(StandardCharsets.UTF_8));
    output.flush();
    assertTrue(outgoingLatch.await(1, TimeUnit.SECONDS));
    assertEquals(expectedResponse, outgoingData.get());
    byte[] responseBytes = readResponse(socket);
    String response = new String(responseBytes, StandardCharsets.UTF_8);
    assertEquals(expectedResponse, response);
    assertEquals(request, incomingData.get());
    socket.close();
}
Also used : InputStream(java.io.InputStream) OutputStream(java.io.OutputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ServletOutputStream(javax.servlet.ServletOutputStream) HttpServletRequest(javax.servlet.http.HttpServletRequest) HttpServletResponse(javax.servlet.http.HttpServletResponse) AtomicReference(java.util.concurrent.atomic.AtomicReference) IOException(java.io.IOException) CountDownLatch(java.util.concurrent.CountDownLatch) ByteBuffer(java.nio.ByteBuffer) AbstractHandler(org.eclipse.jetty.server.handler.AbstractHandler) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletException(javax.servlet.ServletException) NetworkTrafficListener(org.eclipse.jetty.io.NetworkTrafficListener) Socket(java.net.Socket) Test(org.junit.Test)

Example 25 with InputStream

use of java.io.InputStream in project jetty.project by eclipse.

the class NetworkTrafficListenerTest method readResponse.

private byte[] readResponse(Socket socket) throws IOException {
    socket.setSoTimeout(5000);
    InputStream input = socket.getInputStream();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    int read;
    while ((read = input.read()) >= 0) {
        baos.write(read);
        // Handle non-chunked end of response
        if (read == END_OF_CONTENT)
            break;
        // Handle chunked end of response
        String response = baos.toString("UTF-8");
        if (response.endsWith("\r\n0\r\n\r\n"))
            break;
        // Handle non-content responses
        if (response.contains("Content-Length: 0") && response.endsWith("\r\n\r\n"))
            break;
    }
    return baos.toByteArray();
}
Also used : InputStream(java.io.InputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream)

Aggregations

InputStream (java.io.InputStream)33681 IOException (java.io.IOException)12617 ByteArrayInputStream (java.io.ByteArrayInputStream)7643 Test (org.junit.Test)7105 FileInputStream (java.io.FileInputStream)6956 File (java.io.File)5058 InputStreamReader (java.io.InputStreamReader)3045 URL (java.net.URL)3010 OutputStream (java.io.OutputStream)2893 BufferedInputStream (java.io.BufferedInputStream)2558 ByteArrayOutputStream (java.io.ByteArrayOutputStream)2228 ArrayList (java.util.ArrayList)2193 FileOutputStream (java.io.FileOutputStream)2191 BufferedReader (java.io.BufferedReader)2039 Properties (java.util.Properties)1679 FileNotFoundException (java.io.FileNotFoundException)1503 HashMap (java.util.HashMap)1264 HttpURLConnection (java.net.HttpURLConnection)1144 Map (java.util.Map)866 Document (org.w3c.dom.Document)847