Search in sources :

Example 6 with ByteArrayOutputStream

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

the class GZIPContentDecoderTest method testBigBlockOneByteAtATime.

@Test
public void testBigBlockOneByteAtATime() throws Exception {
    String data = "0123456789ABCDEF";
    for (int i = 0; i < 10; ++i) data += data;
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    GZIPOutputStream output = new GZIPOutputStream(baos);
    output.write(data.getBytes(StandardCharsets.UTF_8));
    output.close();
    byte[] bytes = baos.toByteArray();
    String result = "";
    GZIPContentDecoder decoder = new GZIPContentDecoder(64);
    ByteBuffer buffer = ByteBuffer.wrap(bytes);
    while (buffer.hasRemaining()) {
        ByteBuffer decoded = decoder.decode(ByteBuffer.wrap(new byte[] { buffer.get() }));
        if (decoded.hasRemaining())
            result += StandardCharsets.UTF_8.decode(decoded).toString();
        decoder.release(decoded);
    }
    assertEquals(data, result);
    assertTrue(decoder.isFinished());
}
Also used : GZIPOutputStream(java.util.zip.GZIPOutputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ByteBuffer(java.nio.ByteBuffer) Test(org.junit.Test)

Example 7 with ByteArrayOutputStream

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

the class AsyncMiddleManServletTest method testDiscardUpstreamAndDownstreamKnownContentLengthGzipped.

@Test
public void testDiscardUpstreamAndDownstreamKnownContentLengthGzipped() throws Exception {
    final byte[] bytes = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".getBytes(StandardCharsets.UTF_8);
    startServer(new HttpServlet() {

        @Override
        protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            // decode input stream thru gzip
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            IO.copy(new GZIPInputStream(request.getInputStream()), bos);
            // ensure decompressed is 0 length
            Assert.assertEquals(0, bos.toByteArray().length);
            response.setHeader(HttpHeader.CONTENT_ENCODING.asString(), "gzip");
            response.getOutputStream().write(gzip(bytes));
        }
    });
    startProxy(new AsyncMiddleManServlet() {

        @Override
        protected ContentTransformer newClientRequestContentTransformer(HttpServletRequest clientRequest, Request proxyRequest) {
            return new GZIPContentTransformer(new DiscardContentTransformer());
        }

        @Override
        protected ContentTransformer newServerResponseContentTransformer(HttpServletRequest clientRequest, HttpServletResponse proxyResponse, Response serverResponse) {
            return new GZIPContentTransformer(new DiscardContentTransformer());
        }
    });
    startClient();
    ContentResponse response = client.newRequest("localhost", serverConnector.getLocalPort()).header(HttpHeader.CONTENT_ENCODING, "gzip").content(new BytesContentProvider(gzip(bytes))).timeout(5, TimeUnit.SECONDS).send();
    Assert.assertEquals(200, response.getStatus());
    Assert.assertEquals(0, response.getContent().length);
}
Also used : ContentResponse(org.eclipse.jetty.client.api.ContentResponse) HttpServlet(javax.servlet.http.HttpServlet) Request(org.eclipse.jetty.client.api.Request) HttpServletRequest(javax.servlet.http.HttpServletRequest) HttpServletResponse(javax.servlet.http.HttpServletResponse) RuntimeIOException(org.eclipse.jetty.io.RuntimeIOException) IOException(java.io.IOException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) BytesContentProvider(org.eclipse.jetty.client.util.BytesContentProvider) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletException(javax.servlet.ServletException) GZIPInputStream(java.util.zip.GZIPInputStream) ContentResponse(org.eclipse.jetty.client.api.ContentResponse) Response(org.eclipse.jetty.client.api.Response) HttpServletResponse(javax.servlet.http.HttpServletResponse) Test(org.junit.Test)

Example 8 with ByteArrayOutputStream

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

the class ProxyServletTest method testCachingProxy.

@Test
public void testCachingProxy() throws Exception {
    final byte[] content = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF };
    startServer(new HttpServlet() {

        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            if (req.getHeader("Via") != null)
                resp.addHeader(PROXIED_HEADER, "true");
            resp.getOutputStream().write(content);
        }
    });
    // Don't do this at home: this example is not concurrent, not complete,
    // it is only used for this test and to verify that ProxyServlet can be
    // subclassed enough to write your own caching servlet
    final String cacheHeader = "X-Cached";
    proxyServlet = new ProxyServlet() {

        private Map<String, ContentResponse> cache = new HashMap<>();

        private Map<String, ByteArrayOutputStream> temp = new HashMap<>();

        @Override
        protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            ContentResponse cachedResponse = cache.get(request.getRequestURI());
            if (cachedResponse != null) {
                response.setStatus(cachedResponse.getStatus());
                // Should copy headers too, but keep it simple
                response.addHeader(cacheHeader, "true");
                response.getOutputStream().write(cachedResponse.getContent());
            } else {
                super.service(request, response);
            }
        }

        @Override
        protected void onResponseContent(HttpServletRequest request, HttpServletResponse response, Response proxyResponse, byte[] buffer, int offset, int length, Callback callback) {
            // Accumulate the response content
            ByteArrayOutputStream baos = temp.get(request.getRequestURI());
            if (baos == null) {
                baos = new ByteArrayOutputStream();
                temp.put(request.getRequestURI(), baos);
            }
            baos.write(buffer, offset, length);
            super.onResponseContent(request, response, proxyResponse, buffer, offset, length, callback);
        }

        @Override
        protected void onProxyResponseSuccess(HttpServletRequest request, HttpServletResponse response, Response proxyResponse) {
            byte[] content = temp.remove(request.getRequestURI()).toByteArray();
            ContentResponse cached = new HttpContentResponse(proxyResponse, content, null, null);
            cache.put(request.getRequestURI(), cached);
            super.onProxyResponseSuccess(request, response, proxyResponse);
        }
    };
    startProxy();
    startClient();
    // First request
    ContentResponse response = client.newRequest("localhost", serverConnector.getLocalPort()).timeout(5, TimeUnit.SECONDS).send();
    Assert.assertEquals(200, response.getStatus());
    Assert.assertTrue(response.getHeaders().containsKey(PROXIED_HEADER));
    Assert.assertArrayEquals(content, response.getContent());
    // Second request should be cached
    response = client.newRequest("localhost", serverConnector.getLocalPort()).timeout(5, TimeUnit.SECONDS).send();
    Assert.assertEquals(200, response.getStatus());
    Assert.assertTrue(response.getHeaders().containsKey(cacheHeader));
    Assert.assertArrayEquals(content, response.getContent());
}
Also used : HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) HttpContentResponse(org.eclipse.jetty.client.HttpContentResponse) ContentResponse(org.eclipse.jetty.client.api.ContentResponse) HttpServlet(javax.servlet.http.HttpServlet) HttpServletResponse(javax.servlet.http.HttpServletResponse) InterruptedIOException(java.io.InterruptedIOException) IOException(java.io.IOException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletException(javax.servlet.ServletException) HttpContentResponse(org.eclipse.jetty.client.HttpContentResponse) ContentResponse(org.eclipse.jetty.client.api.ContentResponse) Response(org.eclipse.jetty.client.api.Response) ServletResponse(javax.servlet.ServletResponse) HttpServletResponse(javax.servlet.http.HttpServletResponse) Callback(org.eclipse.jetty.util.Callback) HttpContentResponse(org.eclipse.jetty.client.HttpContentResponse) Test(org.junit.Test)

Example 9 with ByteArrayOutputStream

use of java.io.ByteArrayOutputStream 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 10 with ByteArrayOutputStream

use of java.io.ByteArrayOutputStream 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

ByteArrayOutputStream (java.io.ByteArrayOutputStream)17705 ByteArrayInputStream (java.io.ByteArrayInputStream)4669 Test (org.junit.Test)4609 IOException (java.io.IOException)4326 InputStream (java.io.InputStream)1957 ObjectOutputStream (java.io.ObjectOutputStream)1679 PrintStream (java.io.PrintStream)1544 DataOutputStream (java.io.DataOutputStream)1303 ArrayList (java.util.ArrayList)875 ObjectInputStream (java.io.ObjectInputStream)818 OutputStream (java.io.OutputStream)807 File (java.io.File)770 HashMap (java.util.HashMap)558 Test (org.junit.jupiter.api.Test)526 FileInputStream (java.io.FileInputStream)460 Document (org.w3c.dom.Document)382 DataInputStream (java.io.DataInputStream)378 OutputStreamWriter (java.io.OutputStreamWriter)365 URL (java.net.URL)358 GZIPOutputStream (java.util.zip.GZIPOutputStream)338