Search in sources :

Example 11 with InputStream

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

the class AsyncMiddleManServletTest method testAfterContentTransformerDoNoTransform.

private void testAfterContentTransformerDoNoTransform(final boolean readSource, final boolean useDisk) throws Exception {
    final String key0 = "id";
    long value0 = 1;
    final String key1 = "channel";
    String value1 = "foo";
    final String json = "{ \"" + key0 + "\":" + value0 + ", \"" + key1 + "\":\"" + value1 + "\" }";
    startServer(new HttpServlet() {

        @Override
        protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            response.getOutputStream().write(json.getBytes(StandardCharsets.UTF_8));
        }
    });
    startProxy(new AsyncMiddleManServlet() {

        @Override
        protected ContentTransformer newServerResponseContentTransformer(HttpServletRequest clientRequest, HttpServletResponse proxyResponse, Response serverResponse) {
            return new AfterContentTransformer() {

                {
                    if (useDisk)
                        setMaxInputBufferSize(0);
                }

                @Override
                public boolean transform(Source source, Sink sink) throws IOException {
                    if (readSource) {
                        InputStream input = source.getInputStream();
                        JSON.parse(new InputStreamReader(input, "UTF-8"));
                    }
                    // No transformation.
                    return false;
                }
            };
        }
    });
    startClient();
    ContentResponse response = client.newRequest("localhost", serverConnector.getLocalPort()).timeout(5, TimeUnit.SECONDS).send();
    Assert.assertEquals(200, response.getStatus());
    @SuppressWarnings("unchecked") Map<String, Object> obj = (Map<String, Object>) JSON.parse(response.getContentAsString());
    Assert.assertNotNull(obj);
    Assert.assertEquals(2, obj.size());
    Assert.assertEquals(value0, obj.get(key0));
    Assert.assertEquals(value1, obj.get(key1));
}
Also used : InputStreamReader(java.io.InputStreamReader) ContentResponse(org.eclipse.jetty.client.api.ContentResponse) HttpServlet(javax.servlet.http.HttpServlet) GZIPInputStream(java.util.zip.GZIPInputStream) ServletInputStream(javax.servlet.ServletInputStream) InputStream(java.io.InputStream) HttpServletResponse(javax.servlet.http.HttpServletResponse) RuntimeIOException(org.eclipse.jetty.io.RuntimeIOException) IOException(java.io.IOException) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletException(javax.servlet.ServletException) ContentResponse(org.eclipse.jetty.client.api.ContentResponse) Response(org.eclipse.jetty.client.api.Response) HttpServletResponse(javax.servlet.http.HttpServletResponse) Map(java.util.Map) HashMap(java.util.HashMap)

Example 12 with InputStream

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

the class AsyncMiddleManServletTest method testAfterContentTransformerInputStreamReset.

private void testAfterContentTransformerInputStreamReset(final boolean overflow) throws Exception {
    final byte[] data = new byte[] { 'c', 'o', 'f', 'f', 'e', 'e' };
    startServer(new HttpServlet() {

        @Override
        protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            // Write the content in two chunks.
            int chunk = data.length / 2;
            ServletOutputStream output = response.getOutputStream();
            output.write(data, 0, chunk);
            sleep(1000);
            output.write(data, chunk, data.length - chunk);
        }
    });
    startProxy(new AsyncMiddleManServlet() {

        @Override
        protected ContentTransformer newServerResponseContentTransformer(HttpServletRequest clientRequest, HttpServletResponse proxyResponse, Response serverResponse) {
            return new AfterContentTransformer() {

                {
                    setMaxInputBufferSize(overflow ? data.length / 2 : data.length * 2);
                }

                @Override
                public boolean transform(Source source, Sink sink) throws IOException {
                    // Consume the stream once.
                    InputStream input = source.getInputStream();
                    IO.copy(input, IO.getNullStream());
                    // Reset the stream and re-read it.
                    input.reset();
                    IO.copy(input, sink.getOutputStream());
                    return true;
                }
            };
        }
    });
    startClient();
    ContentResponse response = client.newRequest("localhost", serverConnector.getLocalPort()).timeout(5, TimeUnit.SECONDS).send();
    Assert.assertEquals(HttpStatus.OK_200, response.getStatus());
    Assert.assertArrayEquals(data, response.getContent());
}
Also used : ServletOutputStream(javax.servlet.ServletOutputStream) ContentResponse(org.eclipse.jetty.client.api.ContentResponse) HttpServlet(javax.servlet.http.HttpServlet) GZIPInputStream(java.util.zip.GZIPInputStream) ServletInputStream(javax.servlet.ServletInputStream) InputStream(java.io.InputStream) HttpServletResponse(javax.servlet.http.HttpServletResponse) RuntimeIOException(org.eclipse.jetty.io.RuntimeIOException) IOException(java.io.IOException) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletException(javax.servlet.ServletException) ContentResponse(org.eclipse.jetty.client.api.ContentResponse) Response(org.eclipse.jetty.client.api.Response) HttpServletResponse(javax.servlet.http.HttpServletResponse)

Example 13 with InputStream

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

the class AsyncMiddleManServletTest method testAfterContentTransformer.

@Test
public void testAfterContentTransformer() throws Exception {
    final String key0 = "id";
    long value0 = 1;
    final String key1 = "channel";
    String value1 = "foo";
    final String json = "{ \"" + key0 + "\":" + value0 + ", \"" + key1 + "\":\"" + value1 + "\" }";
    startServer(new HttpServlet() {

        @Override
        protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            response.getOutputStream().write(json.getBytes(StandardCharsets.UTF_8));
        }
    });
    final String key2 = "c";
    startProxy(new AsyncMiddleManServlet() {

        @Override
        protected ContentTransformer newServerResponseContentTransformer(HttpServletRequest clientRequest, HttpServletResponse proxyResponse, Response serverResponse) {
            return new AfterContentTransformer() {

                @Override
                public boolean transform(Source source, Sink sink) throws IOException {
                    InputStream input = source.getInputStream();
                    @SuppressWarnings("unchecked") Map<String, Object> obj = (Map<String, Object>) JSON.parse(new InputStreamReader(input, "UTF-8"));
                    // Transform the object.
                    obj.put(key2, obj.remove(key1));
                    try (OutputStream output = sink.getOutputStream()) {
                        output.write(JSON.toString(obj).getBytes(StandardCharsets.UTF_8));
                        return true;
                    }
                }
            };
        }
    });
    startClient();
    ContentResponse response = client.newRequest("localhost", serverConnector.getLocalPort()).timeout(5, TimeUnit.SECONDS).send();
    Assert.assertEquals(200, response.getStatus());
    @SuppressWarnings("unchecked") Map<String, Object> obj = (Map<String, Object>) JSON.parse(response.getContentAsString());
    Assert.assertNotNull(obj);
    Assert.assertEquals(2, obj.size());
    Assert.assertEquals(value0, obj.get(key0));
    Assert.assertEquals(value1, obj.get(key2));
}
Also used : InputStreamReader(java.io.InputStreamReader) ContentResponse(org.eclipse.jetty.client.api.ContentResponse) HttpServlet(javax.servlet.http.HttpServlet) GZIPInputStream(java.util.zip.GZIPInputStream) ServletInputStream(javax.servlet.ServletInputStream) InputStream(java.io.InputStream) GZIPOutputStream(java.util.zip.GZIPOutputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ServletOutputStream(javax.servlet.ServletOutputStream) OutputStream(java.io.OutputStream) HttpServletResponse(javax.servlet.http.HttpServletResponse) RuntimeIOException(org.eclipse.jetty.io.RuntimeIOException) IOException(java.io.IOException) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletException(javax.servlet.ServletException) ContentResponse(org.eclipse.jetty.client.api.ContentResponse) Response(org.eclipse.jetty.client.api.Response) HttpServletResponse(javax.servlet.http.HttpServletResponse) Map(java.util.Map) HashMap(java.util.HashMap) Test(org.junit.Test)

Example 14 with InputStream

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

the class ConnectHandlerTest method testCONNECTAndPOSTWithContext.

@Test
public void testCONNECTAndPOSTWithContext() throws Exception {
    final String contextKey = "contextKey";
    final String contextValue = "contextValue";
    // Replace the default ProxyHandler with a subclass to test context information passing
    disposeProxy();
    proxy.setHandler(new ConnectHandler() {

        @Override
        protected boolean handleAuthentication(HttpServletRequest request, HttpServletResponse response, String address) {
            request.setAttribute(contextKey, contextValue);
            return super.handleAuthentication(request, response, address);
        }

        @Override
        protected void connectToServer(HttpServletRequest request, String host, int port, Promise<SocketChannel> promise) {
            Assert.assertEquals(contextValue, request.getAttribute(contextKey));
            super.connectToServer(request, host, port, promise);
        }

        @Override
        protected void prepareContext(HttpServletRequest request, ConcurrentMap<String, Object> context) {
            // Transfer data from the HTTP request to the connection context
            Assert.assertEquals(contextValue, request.getAttribute(contextKey));
            context.put(contextKey, request.getAttribute(contextKey));
        }

        @Override
        protected int read(EndPoint endPoint, ByteBuffer buffer, ConcurrentMap<String, Object> context) throws IOException {
            Assert.assertEquals(contextValue, context.get(contextKey));
            return super.read(endPoint, buffer, context);
        }

        @Override
        protected void write(EndPoint endPoint, ByteBuffer buffer, Callback callback, ConcurrentMap<String, Object> context) {
            Assert.assertEquals(contextValue, context.get(contextKey));
            super.write(endPoint, buffer, callback, context);
        }
    });
    proxy.start();
    String hostPort = "localhost:" + serverConnector.getLocalPort();
    String request = "" + "CONNECT " + hostPort + " HTTP/1.1\r\n" + "Host: " + hostPort + "\r\n" + "\r\n";
    try (Socket socket = newSocket()) {
        OutputStream output = socket.getOutputStream();
        InputStream input = socket.getInputStream();
        output.write(request.getBytes(StandardCharsets.UTF_8));
        output.flush();
        // Expect 200 OK from the CONNECT request
        HttpTester.Response response = readResponse(input);
        Assert.assertEquals(HttpStatus.OK_200, response.getStatus());
        String body = "0123456789ABCDEF";
        request = "" + "POST /echo HTTP/1.1\r\n" + "Host: " + hostPort + "\r\n" + "Content-Length: " + body.length() + "\r\n" + "\r\n" + body;
        output.write(request.getBytes(StandardCharsets.UTF_8));
        output.flush();
        response = readResponse(input);
        Assert.assertEquals(HttpStatus.OK_200, response.getStatus());
        Assert.assertEquals("POST /echo\r\n" + body, response.getContent());
    }
}
Also used : SocketChannel(java.nio.channels.SocketChannel) InputStream(java.io.InputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ServletOutputStream(javax.servlet.ServletOutputStream) OutputStream(java.io.OutputStream) HttpServletResponse(javax.servlet.http.HttpServletResponse) EndPoint(org.eclipse.jetty.io.EndPoint) IOException(java.io.IOException) ByteBuffer(java.nio.ByteBuffer) EndPoint(org.eclipse.jetty.io.EndPoint) HttpTester(org.eclipse.jetty.http.HttpTester) HttpServletRequest(javax.servlet.http.HttpServletRequest) Callback(org.eclipse.jetty.util.Callback) Socket(java.net.Socket) Test(org.junit.Test)

Example 15 with InputStream

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

the class ConnectHandlerTest method testCONNECTAndGETAndServerSideClose.

@Test
public void testCONNECTAndGETAndServerSideClose() throws Exception {
    String hostPort = "localhost:" + serverConnector.getLocalPort();
    String request = "" + "CONNECT " + hostPort + " HTTP/1.1\r\n" + "Host: " + hostPort + "\r\n" + "\r\n";
    try (Socket socket = newSocket()) {
        OutputStream output = socket.getOutputStream();
        InputStream input = socket.getInputStream();
        output.write(request.getBytes(StandardCharsets.UTF_8));
        output.flush();
        // Expect 200 OK from the CONNECT request
        HttpTester.Response response = readResponse(input);
        Assert.assertEquals(HttpStatus.OK_200, response.getStatus());
        request = "" + "GET /close HTTP/1.1\r\n" + "Host: " + hostPort + "\r\n" + "\r\n";
        output.write(request.getBytes(StandardCharsets.UTF_8));
        output.flush();
        int read = input.read();
        Assert.assertEquals(-1, read);
    }
}
Also used : InputStream(java.io.InputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ServletOutputStream(javax.servlet.ServletOutputStream) OutputStream(java.io.OutputStream) Socket(java.net.Socket) EndPoint(org.eclipse.jetty.io.EndPoint) HttpTester(org.eclipse.jetty.http.HttpTester) Test(org.junit.Test)

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