Search in sources :

Example 11 with HashMap

use of java.util.HashMap in project jetty.project by eclipse.

the class CloseTest method testClientAbruptlyClosesConnection.

@Test
public void testClientAbruptlyClosesConnection() throws Exception {
    final CountDownLatch closeLatch = new CountDownLatch(1);
    final AtomicReference<Session> sessionRef = new AtomicReference<>();
    startServer(new ServerSessionListener.Adapter() {

        @Override
        public Stream.Listener onNewStream(Stream stream, HeadersFrame frame) {
            try {
                sessionRef.set(stream.getSession());
                MetaData.Response response = new MetaData.Response(HttpVersion.HTTP_2, 200, new HttpFields());
                // Reply with HEADERS.
                stream.headers(new HeadersFrame(stream.getId(), response, null, true), Callback.NOOP);
                closeLatch.await(5, TimeUnit.SECONDS);
                return null;
            } catch (InterruptedException x) {
                return null;
            }
        }
    });
    ByteBufferPool.Lease lease = new ByteBufferPool.Lease(byteBufferPool);
    generator.control(lease, new PrefaceFrame());
    generator.control(lease, new SettingsFrame(new HashMap<>(), false));
    MetaData.Request metaData = newRequest("GET", new HttpFields());
    generator.control(lease, new HeadersFrame(1, metaData, null, true));
    try (Socket client = new Socket("localhost", connector.getLocalPort())) {
        OutputStream output = client.getOutputStream();
        for (ByteBuffer buffer : lease.getByteBuffers()) {
            output.write(BufferUtil.toArray(buffer));
        }
        Parser parser = new Parser(byteBufferPool, new Parser.Listener.Adapter() {

            @Override
            public void onHeaders(HeadersFrame frame) {
                try {
                    // Close the connection just after
                    // receiving the response headers.
                    client.close();
                    closeLatch.countDown();
                } catch (IOException x) {
                    throw new RuntimeIOException(x);
                }
            }
        }, 4096, 8192);
        parseResponse(client, parser);
        // We need to give some time to the server to receive and process the TCP FIN.
        Thread.sleep(1000);
        Session session = sessionRef.get();
        Assert.assertTrue(session.isClosed());
        Assert.assertTrue(((HTTP2Session) session).isDisconnected());
    }
}
Also used : ByteBufferPool(org.eclipse.jetty.io.ByteBufferPool) ServerSessionListener(org.eclipse.jetty.http2.api.server.ServerSessionListener) HashMap(java.util.HashMap) OutputStream(java.io.OutputStream) HeadersFrame(org.eclipse.jetty.http2.frames.HeadersFrame) SettingsFrame(org.eclipse.jetty.http2.frames.SettingsFrame) MetaData(org.eclipse.jetty.http.MetaData) HttpFields(org.eclipse.jetty.http.HttpFields) Stream(org.eclipse.jetty.http2.api.Stream) OutputStream(java.io.OutputStream) RuntimeIOException(org.eclipse.jetty.io.RuntimeIOException) AtomicReference(java.util.concurrent.atomic.AtomicReference) RuntimeIOException(org.eclipse.jetty.io.RuntimeIOException) IOException(java.io.IOException) CountDownLatch(java.util.concurrent.CountDownLatch) ByteBuffer(java.nio.ByteBuffer) Parser(org.eclipse.jetty.http2.parser.Parser) PrefaceFrame(org.eclipse.jetty.http2.frames.PrefaceFrame) ServerSessionListener(org.eclipse.jetty.http2.api.server.ServerSessionListener) Socket(java.net.Socket) HTTP2Session(org.eclipse.jetty.http2.HTTP2Session) Session(org.eclipse.jetty.http2.api.Session) Test(org.junit.Test)

Example 12 with HashMap

use of java.util.HashMap in project jetty.project by eclipse.

the class CloseTest method testClientSendsGoAwayButDoesNotCloseConnectionServerCloses.

@Test
public void testClientSendsGoAwayButDoesNotCloseConnectionServerCloses() throws Exception {
    final AtomicReference<Session> sessionRef = new AtomicReference<>();
    startServer(new ServerSessionListener.Adapter() {

        @Override
        public Stream.Listener onNewStream(Stream stream, HeadersFrame frame) {
            sessionRef.set(stream.getSession());
            MetaData.Response response = new MetaData.Response(HttpVersion.HTTP_2, 200, new HttpFields());
            stream.headers(new HeadersFrame(stream.getId(), response, null, true), Callback.NOOP);
            return null;
        }
    });
    ByteBufferPool.Lease lease = new ByteBufferPool.Lease(byteBufferPool);
    generator.control(lease, new PrefaceFrame());
    generator.control(lease, new SettingsFrame(new HashMap<>(), false));
    MetaData.Request metaData = newRequest("GET", new HttpFields());
    generator.control(lease, new HeadersFrame(1, metaData, null, true));
    generator.control(lease, new GoAwayFrame(1, ErrorCode.NO_ERROR.code, "OK".getBytes("UTF-8")));
    try (Socket client = new Socket("localhost", connector.getLocalPort())) {
        OutputStream output = client.getOutputStream();
        for (ByteBuffer buffer : lease.getByteBuffers()) {
            output.write(BufferUtil.toArray(buffer));
        }
        // Don't close the connection; the server should close.
        final CountDownLatch responseLatch = new CountDownLatch(1);
        Parser parser = new Parser(byteBufferPool, new Parser.Listener.Adapter() {

            @Override
            public void onHeaders(HeadersFrame frame) {
                // Even if we sent the GO_AWAY immediately after the
                // HEADERS, the server is able to send us the response.
                responseLatch.countDown();
            }
        }, 4096, 8192);
        parseResponse(client, parser);
        Assert.assertTrue(responseLatch.await(5, TimeUnit.SECONDS));
        // Wait for the server to close.
        Thread.sleep(1000);
        // Client received the TCP FIN from server.
        Assert.assertEquals(-1, client.getInputStream().read());
        // Server is closed.
        Session session = sessionRef.get();
        Assert.assertTrue(session.isClosed());
        Assert.assertTrue(((HTTP2Session) session).isDisconnected());
    }
}
Also used : ByteBufferPool(org.eclipse.jetty.io.ByteBufferPool) ServerSessionListener(org.eclipse.jetty.http2.api.server.ServerSessionListener) HashMap(java.util.HashMap) OutputStream(java.io.OutputStream) HeadersFrame(org.eclipse.jetty.http2.frames.HeadersFrame) SettingsFrame(org.eclipse.jetty.http2.frames.SettingsFrame) MetaData(org.eclipse.jetty.http.MetaData) HttpFields(org.eclipse.jetty.http.HttpFields) Stream(org.eclipse.jetty.http2.api.Stream) OutputStream(java.io.OutputStream) AtomicReference(java.util.concurrent.atomic.AtomicReference) CountDownLatch(java.util.concurrent.CountDownLatch) ByteBuffer(java.nio.ByteBuffer) GoAwayFrame(org.eclipse.jetty.http2.frames.GoAwayFrame) Parser(org.eclipse.jetty.http2.parser.Parser) PrefaceFrame(org.eclipse.jetty.http2.frames.PrefaceFrame) ServerSessionListener(org.eclipse.jetty.http2.api.server.ServerSessionListener) Socket(java.net.Socket) HTTP2Session(org.eclipse.jetty.http2.HTTP2Session) Session(org.eclipse.jetty.http2.api.Session) Test(org.junit.Test)

Example 13 with HashMap

use of java.util.HashMap 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 14 with HashMap

use of java.util.HashMap in project jetty.project by eclipse.

the class ProxyServletTest method testTransparentProxyWithQueryWithSpaces.

@Test
public void testTransparentProxyWithQueryWithSpaces() throws Exception {
    final String target = "/test";
    final String query = "a=1&b=2&c=1234%205678&d=hello+world";
    startServer(new HttpServlet() {

        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            if (req.getHeader("Via") != null)
                resp.addHeader(PROXIED_HEADER, "true");
            if (target.equals(req.getRequestURI())) {
                if (query.equals(req.getQueryString())) {
                    resp.setStatus(200);
                    return;
                }
            }
            resp.setStatus(404);
        }
    });
    String proxyTo = "http://localhost:" + serverConnector.getLocalPort();
    String prefix = "/proxy";
    proxyServlet = new ProxyServlet.Transparent();
    Map<String, String> params = new HashMap<>();
    params.put("proxyTo", proxyTo);
    params.put("prefix", prefix);
    startProxy(params);
    startClient();
    // Make the request to the proxy, it should transparently forward to the server
    ContentResponse response = client.newRequest("localhost", proxyConnector.getLocalPort()).path(prefix + target + "?" + query).timeout(5, TimeUnit.SECONDS).send();
    Assert.assertEquals(200, response.getStatus());
    Assert.assertTrue(response.getHeaders().containsKey(PROXIED_HEADER));
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletException(javax.servlet.ServletException) 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) Test(org.junit.Test)

Example 15 with HashMap

use of java.util.HashMap in project jetty.project by eclipse.

the class ProxyServletTest method testTransparentProxyWithPrefix.

private void testTransparentProxyWithPrefix(String prefix) throws Exception {
    final String target = "/test";
    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.setStatus(target.equals(req.getRequestURI()) ? 200 : 404);
        }
    });
    String proxyTo = "http://localhost:" + serverConnector.getLocalPort();
    proxyServlet = new ProxyServlet.Transparent();
    Map<String, String> params = new HashMap<>();
    params.put("proxyTo", proxyTo);
    params.put("prefix", prefix);
    startProxy(params);
    startClient();
    // Make the request to the proxy, it should transparently forward to the server
    ContentResponse response = client.newRequest("localhost", proxyConnector.getLocalPort()).path((prefix + target).replaceAll("//", "/")).timeout(5, TimeUnit.SECONDS).send();
    Assert.assertEquals(200, response.getStatus());
    Assert.assertTrue(response.getHeaders().containsKey(PROXIED_HEADER));
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) ServletException(javax.servlet.ServletException) 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)

Aggregations

HashMap (java.util.HashMap)69230 Test (org.junit.Test)16584 ArrayList (java.util.ArrayList)16269 Map (java.util.Map)14814 List (java.util.List)8655 IOException (java.io.IOException)5791 HashSet (java.util.HashSet)5215 LinkedHashMap (java.util.LinkedHashMap)3834 File (java.io.File)3597 Set (java.util.Set)3468 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)1946 Iterator (java.util.Iterator)1890 Date (java.util.Date)1815 Test (org.junit.jupiter.api.Test)1788 Test (org.testng.annotations.Test)1747 LinkedList (java.util.LinkedList)1641 URI (java.net.URI)1558 Collection (java.util.Collection)1173 Properties (java.util.Properties)1072 InputStream (java.io.InputStream)1067