Search in sources :

Example 16 with HashMap

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

the class ProxyServletTest method testTransparentProxyWithoutPrefix.

@Test
public void testTransparentProxyWithoutPrefix() 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);
        }
    });
    final String proxyTo = "http://localhost:" + serverConnector.getLocalPort();
    proxyServlet = new ProxyServlet.Transparent();
    Map<String, String> initParams = new HashMap<>();
    initParams.put("proxyTo", proxyTo);
    startProxy(initParams);
    startClient();
    // Make the request to the proxy, it should transparently forward to the server
    ContentResponse response = client.newRequest("localhost", proxyConnector.getLocalPort()).path(target).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 17 with HashMap

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

the class ProxyServletTest method testTransparentProxyWithQuery.

private void testTransparentProxyWithQuery(String proxyToContext, String prefix, String target) throws Exception {
    final String query = "a=1&b=2";
    startServer(new HttpServlet() {

        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            if (req.getHeader("Via") != null)
                resp.addHeader(PROXIED_HEADER, "true");
            String expectedURI = proxyToContext + target;
            if (expectedURI.isEmpty())
                expectedURI = "/";
            if (expectedURI.equals(req.getRequestURI())) {
                if (query.equals(req.getQueryString())) {
                    resp.setStatus(200);
                    return;
                }
            }
            resp.setStatus(404);
        }
    });
    String proxyTo = "http://localhost:" + serverConnector.getLocalPort() + proxyToContext;
    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)

Example 18 with HashMap

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

the class ProxyServletTest method testProxyRequestFailureInTheMiddleOfProxyingSmallContent.

@Test
public void testProxyRequestFailureInTheMiddleOfProxyingSmallContent() throws Exception {
    final CountDownLatch chunk1Latch = new CountDownLatch(1);
    final int chunk1 = 'q';
    final int chunk2 = 'w';
    startServer(new HttpServlet() {

        @Override
        protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            ServletOutputStream output = response.getOutputStream();
            output.write(chunk1);
            response.flushBuffer();
            // Wait for the client to receive this chunk.
            await(chunk1Latch, 5000);
            // Send second chunk, must not be received by proxy.
            output.write(chunk2);
        }

        private boolean await(CountDownLatch latch, long ms) throws IOException {
            try {
                return latch.await(ms, TimeUnit.MILLISECONDS);
            } catch (InterruptedException x) {
                throw new InterruptedIOException();
            }
        }
    });
    final long proxyTimeout = 1000;
    Map<String, String> proxyParams = new HashMap<>();
    proxyParams.put("timeout", String.valueOf(proxyTimeout));
    startProxy(proxyParams);
    startClient();
    InputStreamResponseListener listener = new InputStreamResponseListener();
    int port = serverConnector.getLocalPort();
    client.newRequest("localhost", port).send(listener);
    // Make the proxy request fail; given the small content, the
    // proxy-to-client response is not committed yet so it will be reset.
    TimeUnit.MILLISECONDS.sleep(2 * proxyTimeout);
    Response response = listener.get(5, TimeUnit.SECONDS);
    Assert.assertEquals(504, response.getStatus());
    // Make sure there is no content, as the proxy-to-client response has been reset.
    InputStream input = listener.getInputStream();
    Assert.assertEquals(-1, input.read());
    chunk1Latch.countDown();
    // Result succeeds because a 504 is a valid HTTP response.
    Result result = listener.await(5, TimeUnit.SECONDS);
    Assert.assertTrue(result.isSucceeded());
    // Make sure the proxy does not receive chunk2.
    Assert.assertEquals(-1, input.read());
    HttpDestinationOverHTTP destination = (HttpDestinationOverHTTP) client.getDestination("http", "localhost", port);
    DuplexConnectionPool connectionPool = (DuplexConnectionPool) destination.getConnectionPool();
    Assert.assertEquals(0, connectionPool.getIdleConnections().size());
}
Also used : InterruptedIOException(java.io.InterruptedIOException) InputStreamResponseListener(org.eclipse.jetty.client.util.InputStreamResponseListener) DuplexConnectionPool(org.eclipse.jetty.client.DuplexConnectionPool) ServletOutputStream(javax.servlet.ServletOutputStream) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) HttpServlet(javax.servlet.http.HttpServlet) ServletInputStream(javax.servlet.ServletInputStream) InputStream(java.io.InputStream) HttpServletResponse(javax.servlet.http.HttpServletResponse) InterruptedIOException(java.io.InterruptedIOException) IOException(java.io.IOException) CountDownLatch(java.util.concurrent.CountDownLatch) Result(org.eclipse.jetty.client.api.Result) 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) HttpDestinationOverHTTP(org.eclipse.jetty.client.http.HttpDestinationOverHTTP) Test(org.junit.Test)

Example 19 with HashMap

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

the class Invoker method init.

/* ------------------------------------------------------------ */
public void init() {
    ServletContext config = getServletContext();
    _contextHandler = ((ContextHandler.Context) config).getContextHandler();
    Handler handler = _contextHandler.getHandler();
    while (handler != null && !(handler instanceof ServletHandler) && (handler instanceof HandlerWrapper)) handler = ((HandlerWrapper) handler).getHandler();
    _servletHandler = (ServletHandler) handler;
    Enumeration<String> e = getInitParameterNames();
    while (e.hasMoreElements()) {
        String param = e.nextElement();
        String value = getInitParameter(param);
        String lvalue = value.toLowerCase(Locale.ENGLISH);
        if ("nonContextServlets".equals(param)) {
            _nonContextServlets = value.length() > 0 && lvalue.startsWith("t");
        }
        if ("verbose".equals(param)) {
            _verbose = value.length() > 0 && lvalue.startsWith("t");
        } else {
            if (_parameters == null)
                _parameters = new HashMap<String, String>();
            _parameters.put(param, value);
        }
    }
}
Also used : ContextHandler(org.eclipse.jetty.server.handler.ContextHandler) HashMap(java.util.HashMap) ServletContext(javax.servlet.ServletContext) Handler(org.eclipse.jetty.server.Handler) ContextHandler(org.eclipse.jetty.server.handler.ContextHandler) HandlerWrapper(org.eclipse.jetty.server.handler.HandlerWrapper)

Example 20 with HashMap

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

the class ServletHandler method updateMappings.

/* ------------------------------------------------------------ */
protected synchronized void updateMappings() {
    // update filter mappings
    if (_filterMappings == null) {
        _filterPathMappings = null;
        _filterNameMappings = null;
    } else {
        _filterPathMappings = new ArrayList<>();
        _filterNameMappings = new MultiMap<>();
        for (FilterMapping filtermapping : _filterMappings) {
            FilterHolder filter_holder = _filterNameMap.get(filtermapping.getFilterName());
            if (filter_holder == null)
                throw new IllegalStateException("No filter named " + filtermapping.getFilterName());
            filtermapping.setFilterHolder(filter_holder);
            if (filtermapping.getPathSpecs() != null)
                _filterPathMappings.add(filtermapping);
            if (filtermapping.getServletNames() != null) {
                String[] names = filtermapping.getServletNames();
                for (String name : names) {
                    if (name != null)
                        _filterNameMappings.add(name, filtermapping);
                }
            }
        }
    }
    // Map servlet paths to holders
    if (_servletMappings == null || _servletNameMap == null) {
        _servletPathMap = null;
    } else {
        PathMappings<ServletHolder> pm = new PathMappings<>();
        Map<String, ServletMapping> servletPathMappings = new HashMap<>();
        //create a map of paths to set of ServletMappings that define that mapping
        HashMap<String, List<ServletMapping>> sms = new HashMap<>();
        for (ServletMapping servletMapping : _servletMappings) {
            String[] pathSpecs = servletMapping.getPathSpecs();
            if (pathSpecs != null) {
                for (String pathSpec : pathSpecs) {
                    List<ServletMapping> mappings = sms.get(pathSpec);
                    if (mappings == null) {
                        mappings = new ArrayList<>();
                        sms.put(pathSpec, mappings);
                    }
                    mappings.add(servletMapping);
                }
            }
        }
        //evaluate path to servlet map based on servlet mappings
        for (String pathSpec : sms.keySet()) {
            //for each path, look at the mappings where it is referenced
            //if a mapping is for a servlet that is not enabled, skip it
            List<ServletMapping> mappings = sms.get(pathSpec);
            ServletMapping finalMapping = null;
            for (ServletMapping mapping : mappings) {
                //Get servlet associated with the mapping and check it is enabled
                ServletHolder servlet_holder = _servletNameMap.get(mapping.getServletName());
                if (servlet_holder == null)
                    throw new IllegalStateException("No such servlet: " + mapping.getServletName());
                //if the servlet related to the mapping is not enabled, skip it from consideration
                if (!servlet_holder.isEnabled())
                    continue;
                //only accept a default mapping if we don't have any other
                if (finalMapping == null)
                    finalMapping = mapping;
                else {
                    //if the candidate is a default, or we're allowing duplicate mappings
                    if (finalMapping.isDefault())
                        finalMapping = mapping;
                    else if (isAllowDuplicateMappings()) {
                        LOG.warn("Multiple servlets map to path {}: {} and {}, choosing {}", pathSpec, finalMapping.getServletName(), mapping.getServletName(), mapping);
                        finalMapping = mapping;
                    } else {
                        //existing candidate isn't a default, if the one we're looking at isn't a default either, then its an error
                        if (!mapping.isDefault()) {
                            ServletHolder finalMappedServlet = _servletNameMap.get(finalMapping.getServletName());
                            throw new IllegalStateException("Multiple servlets map to path " + pathSpec + ": " + finalMappedServlet.getName() + "[mapped:" + finalMapping.getSource() + "]," + mapping.getServletName() + "[mapped:" + mapping.getSource() + "]");
                        }
                    }
                }
            }
            if (finalMapping == null)
                throw new IllegalStateException("No acceptable servlet mappings for " + pathSpec);
            if (LOG.isDebugEnabled())
                LOG.debug("Path={}[{}] mapped to servlet={}[{}]", pathSpec, finalMapping.getSource(), finalMapping.getServletName(), _servletNameMap.get(finalMapping.getServletName()).getSource());
            servletPathMappings.put(pathSpec, finalMapping);
            pm.put(new ServletPathSpec(pathSpec), _servletNameMap.get(finalMapping.getServletName()));
        }
        _servletPathMap = pm;
    }
    // flush filter chain cache
    if (_chainCache != null) {
        for (int i = _chainCache.length; i-- > 0; ) {
            if (_chainCache[i] != null)
                _chainCache[i].clear();
        }
    }
    if (LOG.isDebugEnabled()) {
        LOG.debug("filterNameMap=" + _filterNameMap);
        LOG.debug("pathFilters=" + _filterPathMappings);
        LOG.debug("servletFilterMap=" + _filterNameMappings);
        LOG.debug("servletPathMap=" + _servletPathMap);
        LOG.debug("servletNameMap=" + _servletNameMap);
    }
    try {
        if (_contextHandler != null && _contextHandler.isStarted() || _contextHandler == null && isStarted())
            initialize();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
Also used : ServletPathSpec(org.eclipse.jetty.http.pathmap.ServletPathSpec) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) ServletException(javax.servlet.ServletException) MultiException(org.eclipse.jetty.util.MultiException) IOException(java.io.IOException) List(java.util.List) ArrayList(java.util.ArrayList) LazyList(org.eclipse.jetty.util.LazyList) PathMappings(org.eclipse.jetty.http.pathmap.PathMappings)

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