Java Code Examples for org.apache.catalina.Wrapper#addInitParameter()

The following examples show how to use org.apache.catalina.Wrapper#addInitParameter() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Launcher.java    From lucene-geo-gazetteer with Apache License 2.0 6 votes vote down vote up
public static void launchService(int port, String indexPath)
        throws IOException, LifecycleException {

    Tomcat server = new Tomcat();
    Context context = server.addContext("/", new File(".").getAbsolutePath());
    System.setProperty(INDEX_PATH_PROP, indexPath);

    Wrapper servlet = context.createWrapper();
    servlet.setName("CXFNonSpringJaxrs");
    servlet.setServletClass(CXFNonSpringJaxrsServlet.class.getName());
    servlet.addInitParameter("jaxrs.serviceClasses", SearchResource.class.getName() + " " + HealthCheckAPI.class.getName());

    servlet.setLoadOnStartup(1);
    context.addChild(servlet);
    context.addServletMapping("/api/*", "CXFNonSpringJaxrs");

    System.out.println("Starting Embedded Tomcat on port : " + port );
    server.setPort(port);
    server.start();
    server.getServer().await();
}
 
Example 2
Source File: TestDefaultInstanceManager.java    From Tomcat7.0.67 with Apache License 2.0 6 votes vote down vote up
private DefaultInstanceManager doClassUnloadingPrep() throws Exception {
    Tomcat tomcat = getTomcatInstance();

    // Create the context (don't use addWebapp as we want to modify the
    // JSP Servlet settings).
    File appDir = new File("test/webapp-3.0");
    StandardContext ctxt = (StandardContext) tomcat.addContext(
            null, "/test", appDir.getAbsolutePath());

    // Configure the defaults and then tweak the JSP servlet settings
    // Note: Min value for maxLoadedJsps is 2
    Tomcat.initWebappDefaults(ctxt);
    Wrapper w = (Wrapper) ctxt.findChild("jsp");
    w.addInitParameter("maxLoadedJsps", "2");

    tomcat.start();

    return (DefaultInstanceManager) ctxt.getInstanceManager();
}
 
Example 3
Source File: TestDefaultInstanceManager.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
private DefaultInstanceManager doClassUnloadingPrep() throws Exception {
    Tomcat tomcat = getTomcatInstance();

    // Create the context (don't use addWebapp as we want to modify the
    // JSP Servlet settings).
    File appDir = new File("test/webapp");
    StandardContext ctxt = (StandardContext) tomcat.addContext(
            null, "/test", appDir.getAbsolutePath());

    ctxt.addServletContainerInitializer(new JasperInitializer(), null);

    // Configure the defaults and then tweak the JSP servlet settings
    // Note: Min value for maxLoadedJsps is 2
    Tomcat.initWebappDefaults(ctxt);
    Wrapper w = (Wrapper) ctxt.findChild("jsp");
    w.addInitParameter("maxLoadedJsps", "2");

    tomcat.start();

    return (DefaultInstanceManager) ctxt.getInstanceManager();
}
 
Example 4
Source File: TestDefaultInstanceManager.java    From tomcatsrc with Apache License 2.0 6 votes vote down vote up
private DefaultInstanceManager doClassUnloadingPrep() throws Exception {
    Tomcat tomcat = getTomcatInstance();

    // Create the context (don't use addWebapp as we want to modify the
    // JSP Servlet settings).
    File appDir = new File("test/webapp-3.0");
    StandardContext ctxt = (StandardContext) tomcat.addContext(
            null, "/test", appDir.getAbsolutePath());

    // Configure the defaults and then tweak the JSP servlet settings
    // Note: Min value for maxLoadedJsps is 2
    Tomcat.initWebappDefaults(ctxt);
    Wrapper w = (Wrapper) ctxt.findChild("jsp");
    w.addInitParameter("maxLoadedJsps", "2");

    tomcat.start();

    return (DefaultInstanceManager) ctxt.getInstanceManager();
}
 
Example 5
Source File: Tomcat.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
/**
 * Static version of {@link #initWebappDefaults(String)}
 * @param ctx   The context to set the defaults for
 */
public static void initWebappDefaults(Context ctx) {
    // Default servlet 
    Wrapper servlet = addServlet(
            ctx, "default", "org.apache.catalina.servlets.DefaultServlet");
    servlet.setLoadOnStartup(1);
    servlet.setOverridable(true);

    // JSP servlet (by class name - to avoid loading all deps)
    servlet = addServlet(
            ctx, "jsp", "org.apache.jasper.servlet.JspServlet");
    servlet.addInitParameter("fork", "false");
    servlet.setLoadOnStartup(3);
    servlet.setOverridable(true);

    // Servlet mappings
    ctx.addServletMapping("/", "default");
    ctx.addServletMapping("*.jsp", "jsp");
    ctx.addServletMapping("*.jspx", "jsp");

    // Sessions
    ctx.setSessionTimeout(30);
    
    // MIME mappings
    for (int i = 0; i < DEFAULT_MIME_MAPPINGS.length;) {
        ctx.addMimeMapping(DEFAULT_MIME_MAPPINGS[i++],
                DEFAULT_MIME_MAPPINGS[i++]);
    }
    
    // Welcome files
    ctx.addWelcomeFile("index.html");
    ctx.addWelcomeFile("index.htm");
    ctx.addWelcomeFile("index.jsp");
}
 
Example 6
Source File: AbstractTomcatServer.java    From cxf with Apache License 2.0 5 votes vote down vote up
protected void run() {
    server = new Tomcat();
    server.setPort(port);
    server.getConnector();

    try {
        base = Files.createTempDirectory("tmp-");
        server.setBaseDir(base.toString());

        if (resourcePath == null) {
            final Context context = server.addContext("", base.toString());
            final Wrapper cxfServlet = Tomcat.addServlet(context, "cxfServlet", new CXFNonSpringJaxrsServlet());
            cxfServlet.addInitParameter("jaxrs.serviceClasses", BookStore.class.getName());
            cxfServlet.addInitParameter("jaxrs.providers", String.join(",",
                JacksonJsonProvider.class.getName(),
                BookStoreResponseFilter.class.getName()
            ));
            cxfServlet.setAsyncSupported(true);
            context.addServletMappingDecoded("/rest/*", "cxfServlet");
        } else {
            server.getHost().setAppBase(base.toString());
            server.getHost().setAutoDeploy(true);
            server.getHost().setDeployOnStartup(true);
            server.addWebapp(contextPath, getClass().getResource(resourcePath).toURI().getPath().toString());
        }

        server.start();
    } catch (final Exception ex) {
        ex.printStackTrace();
        fail(ex.getMessage());
    }
}
 
Example 7
Source File: TomcatWsRegistry.java    From tomee with Apache License 2.0 5 votes vote down vote up
private void setWsContainer(final Context context, final Wrapper wrapper, final HttpListener wsContainer) {
    // Make up an ID for the WebServiceContainer
    // put a reference the ID in the init-params
    // put the WebServiceContainer in the webapp context keyed by its ID
    final String webServicecontainerID = wrapper.getName() + WsServlet.WEBSERVICE_CONTAINER + wsContainer.hashCode();
    context.getServletContext().setAttribute(webServicecontainerID, wsContainer);
    wrapper.addInitParameter(WsServlet.WEBSERVICE_CONTAINER, webServicecontainerID);
}
 
Example 8
Source File: Tomcat.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
/**
 * Static version of {@link #initWebappDefaults(String)}
 * @param ctx   The context to set the defaults for
 */
public static void initWebappDefaults(Context ctx) {
    // Default servlet 
    Wrapper servlet = addServlet(
            ctx, "default", "org.apache.catalina.servlets.DefaultServlet");
    servlet.setLoadOnStartup(1);
    servlet.setOverridable(true);

    // JSP servlet (by class name - to avoid loading all deps)
    servlet = addServlet(
            ctx, "jsp", "org.apache.jasper.servlet.JspServlet");
    servlet.addInitParameter("fork", "false");
    servlet.setLoadOnStartup(3);
    servlet.setOverridable(true);

    // Servlet mappings
    ctx.addServletMapping("/", "default");
    ctx.addServletMapping("*.jsp", "jsp");
    ctx.addServletMapping("*.jspx", "jsp");

    // Sessions
    ctx.setSessionTimeout(30);
    
    // MIME mappings
    for (int i = 0; i < DEFAULT_MIME_MAPPINGS.length;) {
        ctx.addMimeMapping(DEFAULT_MIME_MAPPINGS[i++],
                DEFAULT_MIME_MAPPINGS[i++]);
    }
    
    // Welcome files
    ctx.addWelcomeFile("index.html");
    ctx.addWelcomeFile("index.htm");
    ctx.addWelcomeFile("index.jsp");
}
 
Example 9
Source File: ArkTomcatServletWebServerFactory.java    From sofa-ark with Apache License 2.0 5 votes vote down vote up
private void addJspServlet(Context context) {
    Wrapper jspServlet = context.createWrapper();
    jspServlet.setName("jsp");
    jspServlet.setServletClass(getJsp().getClassName());
    jspServlet.addInitParameter("fork", "false");
    for (Map.Entry<String, String> entry : getJsp().getInitParameters().entrySet()) {
        jspServlet.addInitParameter(entry.getKey(), entry.getValue());
    }
    jspServlet.setLoadOnStartup(3);
    context.addChild(jspServlet);
    context.addServletMappingDecoded("*.jsp", "jsp");
    context.addServletMappingDecoded("*.jspx", "jsp");
}
 
Example 10
Source File: Tomcat.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
/**
 * Static version of {@link #initWebappDefaults(String)}
 * @param ctx   The context to set the defaults for
 */
public static void initWebappDefaults(Context ctx) {
    // Default servlet
    Wrapper servlet = addServlet(
            ctx, "default", "org.apache.catalina.servlets.DefaultServlet");
    servlet.setLoadOnStartup(1);
    servlet.setOverridable(true);

    // JSP servlet (by class name - to avoid loading all deps)
    servlet = addServlet(
            ctx, "jsp", "org.apache.jasper.servlet.JspServlet");
    servlet.addInitParameter("fork", "false");
    servlet.setLoadOnStartup(3);
    servlet.setOverridable(true);

    // Servlet mappings
    ctx.addServletMappingDecoded("/", "default");
    ctx.addServletMappingDecoded("*.jsp", "jsp");
    ctx.addServletMappingDecoded("*.jspx", "jsp");

    // Sessions
    ctx.setSessionTimeout(30);

    // MIME mappings
    for (int i = 0; i < DEFAULT_MIME_MAPPINGS.length;) {
        ctx.addMimeMapping(DEFAULT_MIME_MAPPINGS[i++],
                DEFAULT_MIME_MAPPINGS[i++]);
    }

    // Welcome files
    ctx.addWelcomeFile("index.html");
    ctx.addWelcomeFile("index.htm");
    ctx.addWelcomeFile("index.jsp");
}
 
Example 11
Source File: ServletOptionsBaseTest.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
@Test
public void testOptions() throws Exception {
    Tomcat tomcat = getTomcatInstance();

    tomcat.getConnector().setAllowTrace(trace);

    File docBase = new File(getTemporaryDirectory(), "webdav");
    File collection = new File(docBase, COLLECTION_NAME);
    Assert.assertTrue(collection.mkdirs());
    File file = new File(docBase, FILE_NAME);
    Assert.assertTrue(file.createNewFile());

    addDeleteOnTearDown(docBase);

    // app dir is relative to server home
    org.apache.catalina.Context ctx =
        tomcat.addWebapp(null, "/servlet", docBase.getAbsolutePath());

    Wrapper w = Tomcat.addServlet(ctx, "servlet", createServlet());
    w.addInitParameter("listings", Boolean.toString(listings));
    w.addInitParameter("readonly", Boolean.toString(readonly));

    ctx.addServletMappingDecoded("/*", "servlet");

    tomcat.start();

    OptionsHttpClient client = new OptionsHttpClient();
    client.setPort(getPort());
    client.setRequest(new String[] {
            "OPTIONS /servlet/" + url + " HTTP/1.1" + CRLF +
            "Host: localhost:" + getPort() + CRLF +
            "Connection: close" + CRLF +
            CRLF });

    client.connect();
    client.processRequest();

    Assert.assertTrue(client.isResponse200());
    Set<String> allowed = client.getAllowedMethods();

    client.disconnect();
    client.reset();

    client.setRequest(new String[] {
            method + " /servlet/" + url + " HTTP/1.1" + CRLF +
            "Host: localhost:" + getPort() + CRLF +
            "Connection: close" + CRLF +
            CRLF });

    client.connect();
    client.processRequest();

    String msg = "Listings[" + listings + "], readonly [" + readonly +
            "], trace[ " + trace + "], url[" + url + "], method[" + method + "]";

    Assert.assertNotNull(client.getResponseLine());

    if (allowed.contains(method)) {
        Assert.assertFalse(msg, client.isResponse405());
    } else {
        Assert.assertTrue(msg, client.isResponse405());
        allowed = client.getAllowedMethods();
        Assert.assertFalse(msg, allowed.contains(method));
    }
}
 
Example 12
Source File: TestELInJsp.java    From Tomcat7.0.67 with Apache License 2.0 4 votes vote down vote up
private void doTestELMisc(boolean quoteAttributeEL) throws Exception {
    Tomcat tomcat = getTomcatInstance();

    // Create the context (don't use addWebapp as we want to modify the
    // JSP Servlet settings).
    File appDir = new File("test/webapp-3.0");
    StandardContext ctxt = (StandardContext) tomcat.addContext(
            null, "/test", appDir.getAbsolutePath());

    // Configure the defaults and then tweak the JSP servlet settings
    // Note: Min value for maxLoadedJsps is 2
    Tomcat.initWebappDefaults(ctxt);
    Wrapper w = (Wrapper) ctxt.findChild("jsp");

    String jspName;
    if (quoteAttributeEL) {
        jspName = "/test/el-misc-with-quote-attribute-el.jsp";
        w.addInitParameter("quoteAttributeEL", "true");
    } else {
        jspName = "/test/el-misc-no-quote-attribute-el.jsp";
        w.addInitParameter("quoteAttributeEL", "false");
    }

    tomcat.start();

    ByteChunk res = getUrl("http://localhost:" + getPort() + jspName);
    String result = res.toString();
    assertEcho(result, "00-\\\\\\\"${'hello world'}");
    assertEcho(result, "01-\\\\\\\"\\${'hello world'}");
    assertEcho(result, "02-\\\"${'hello world'}");
    assertEcho(result, "03-\\\"\\hello world");
    assertEcho(result, "2az-04");
    assertEcho(result, "05-a2z");
    assertEcho(result, "06-az2");
    assertEcho(result, "2az-07");
    assertEcho(result, "08-a2z");
    assertEcho(result, "09-az2");
    assertEcho(result, "10-${'foo'}bar");
    assertEcho(result, "11-\\\"}");
    assertEcho(result, "12-foo\\bar\\baz");
    assertEcho(result, "13-foo\\bar\\baz");
    assertEcho(result, "14-foo\\bar\\baz");
    assertEcho(result, "15-foo\\bar\\baz");
    assertEcho(result, "16-foo\\bar\\baz");
    assertEcho(result, "17-foo\\&apos;bar&apos;\\&quot;baz&quot;");
}
 
Example 13
Source File: TestELInJsp.java    From tomcatsrc with Apache License 2.0 4 votes vote down vote up
private void doTestELMisc(boolean quoteAttributeEL) throws Exception {
    Tomcat tomcat = getTomcatInstance();

    // Create the context (don't use addWebapp as we want to modify the
    // JSP Servlet settings).
    File appDir = new File("test/webapp-3.0");
    StandardContext ctxt = (StandardContext) tomcat.addContext(
            null, "/test", appDir.getAbsolutePath());

    // Configure the defaults and then tweak the JSP servlet settings
    // Note: Min value for maxLoadedJsps is 2
    Tomcat.initWebappDefaults(ctxt);
    Wrapper w = (Wrapper) ctxt.findChild("jsp");

    String jspName;
    if (quoteAttributeEL) {
        jspName = "/test/el-misc-with-quote-attribute-el.jsp";
        w.addInitParameter("quoteAttributeEL", "true");
    } else {
        jspName = "/test/el-misc-no-quote-attribute-el.jsp";
        w.addInitParameter("quoteAttributeEL", "false");
    }

    tomcat.start();

    ByteChunk res = getUrl("http://localhost:" + getPort() + jspName);
    String result = res.toString();
    assertEcho(result, "00-\\\\\\\"${'hello world'}");
    assertEcho(result, "01-\\\\\\\"\\${'hello world'}");
    assertEcho(result, "02-\\\"${'hello world'}");
    assertEcho(result, "03-\\\"\\hello world");
    assertEcho(result, "2az-04");
    assertEcho(result, "05-a2z");
    assertEcho(result, "06-az2");
    assertEcho(result, "2az-07");
    assertEcho(result, "08-a2z");
    assertEcho(result, "09-az2");
    assertEcho(result, "10-${'foo'}bar");
    assertEcho(result, "11-\\\"}");
    assertEcho(result, "12-foo\\bar\\baz");
    assertEcho(result, "13-foo\\bar\\baz");
    assertEcho(result, "14-foo\\bar\\baz");
    assertEcho(result, "15-foo\\bar\\baz");
    assertEcho(result, "16-foo\\bar\\baz");
    assertEcho(result, "17-foo\\&apos;bar&apos;\\&quot;baz&quot;");
}
 
Example 14
Source File: TestELInJsp.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
private void doTestELMisc(boolean quoteAttributeEL) throws Exception {
    Tomcat tomcat = getTomcatInstance();

    // Create the context (don't use addWebapp as we want to modify the
    // JSP Servlet settings).
    File appDir = new File("test/webapp");
    StandardContext ctxt = (StandardContext) tomcat.addContext(
            null, "/test", appDir.getAbsolutePath());

    ctxt.addServletContainerInitializer(new JasperInitializer(), null);

    // Configure the defaults and then tweak the JSP servlet settings
    // Note: Min value for maxLoadedJsps is 2
    Tomcat.initWebappDefaults(ctxt);
    Wrapper w = (Wrapper) ctxt.findChild("jsp");

    String jspName;
    if (quoteAttributeEL) {
        jspName = "/test/el-misc-with-quote-attribute-el.jsp";
        w.addInitParameter("quoteAttributeEL", "true");
    } else {
        jspName = "/test/el-misc-no-quote-attribute-el.jsp";
        w.addInitParameter("quoteAttributeEL", "false");
    }

    tomcat.start();

    ByteChunk res = getUrl("http://localhost:" + getPort() + jspName);
    String result = res.toString();

    assertEcho(result, "00-\\\\\\\"${'hello world'}");
    assertEcho(result, "01-\\\\\\\"\\${'hello world'}");
    assertEcho(result, "02-\\\"${'hello world'}");
    assertEcho(result, "03-\\\"\\hello world");
    assertEcho(result, "2az-04");
    assertEcho(result, "05-a2z");
    assertEcho(result, "06-az2");
    assertEcho(result, "2az-07");
    assertEcho(result, "08-a2z");
    assertEcho(result, "09-az2");
    assertEcho(result, "10-${'foo'}bar");
    assertEcho(result, "11-\\\"}");
    assertEcho(result, "12-foo\\bar\\baz");
    assertEcho(result, "13-foo\\bar\\baz");
    assertEcho(result, "14-foo\\bar\\baz");
    assertEcho(result, "15-foo\\bar\\baz");
    assertEcho(result, "16-foo\\bar\\baz");
    assertEcho(result, "17-foo\\&apos;bar&apos;\\&quot;baz&quot;");
    assertEcho(result, "18-3");
    assertEcho(result, "19-4");
    assertEcho(result, "20-4");
    assertEcho(result, "21-[{value=11}, {value=12}, {value=13}, {value=14}]");
    assertEcho(result, "22-[{value=11}, {value=12}, {value=13}, {value=14}]");
}
 
Example 15
Source File: TomcatWsRegistry.java    From tomee with Apache License 2.0 4 votes vote down vote up
private void addServlet(final Container host, final Context context, final String mapping, final HttpListener httpListener, final String path,
                        final List<String> addresses, final boolean fakeDeployment, final String moduleId) {
    // build the servlet
    final Wrapper wrapper = context.createWrapper();
    wrapper.setName("webservice" + path.substring(1));
    wrapper.setServletClass(WsServlet.class.getName());

    // add servlet to context
    context.addChild(wrapper);
    context.addServletMappingDecoded(mapping, wrapper.getName());

    final String webServicecontainerID = wrapper.getName() + WsServlet.WEBSERVICE_CONTAINER + httpListener.hashCode();
    wrapper.addInitParameter(WsServlet.WEBSERVICE_CONTAINER, webServicecontainerID);

    setWsContainer(context, wrapper, httpListener);

    webserviceContexts.put(new Key(path, moduleId), context);

    // register wsdl locations for service-ref resolution
    for (final Connector connector : connectors) {
        final StringBuilder fullContextpath;
        if (!WEBSERVICE_OLDCONTEXT_ACTIVE && !fakeDeployment) {
            String contextPath = context.getPath();
            if (contextPath == null ||  !contextPath.isEmpty()) {
                if (contextPath != null && !contextPath.startsWith("/")) {
                    contextPath = "/" + contextPath;
                } else if (contextPath == null) {
                    contextPath = "/";
                }
            }

            fullContextpath = new StringBuilder(contextPath);
            if (!WEBSERVICE_SUB_CONTEXT.equals("/")) {
                fullContextpath.append(WEBSERVICE_SUB_CONTEXT);
            }
            fullContextpath.append(path);
        } else {
            fullContextpath = new StringBuilder(context.getPath()).append(path);
        }

        try {
            final URI address = new URI(connector.getScheme(), null, host.getName(), connector.getPort(), fullContextpath.toString(), null, null);
            addresses.add(address.toString());
        } catch (final URISyntaxException ignored) {
            // no-op
        }
    }
}
 
Example 16
Source File: TestDefaultServlet.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
@Test
public void testBrotliPreference() throws Exception {

    Tomcat tomcat = getTomcatInstance();

    File appDir = new File("test/webapp");

    long brSize = new File(appDir, "index.html.br").length();

    // app dir is relative to server home
    Context ctxt = tomcat.addContext("", appDir.getAbsolutePath());
    Wrapper defaultServlet = Tomcat.addServlet(ctxt, "default",
            DefaultServlet.class.getName());
    defaultServlet.addInitParameter("precompressed", "true");

    ctxt.addServletMappingDecoded("/", "default");
    ctxt.addMimeMapping("html", "text/html");

    tomcat.start();

    TestCompressedClient client = new TestCompressedClient(getPort());

    // Firefox 45 Accept-Encoding
    client.reset();
    client.setRequest(new String[] {
            "GET /index.html HTTP/1.1" + CRLF +
                    "Host: localhost" + CRLF +
                    "Connection: Close" + CRLF +
                    "Accept-Encoding: gzip, deflate, br" + CRLF + CRLF });
    client.connect();
    client.processRequest();
    Assert.assertTrue(client.isResponse200());
    List<String> responseHeaders = client.getResponseHeaders();
    Assert.assertTrue(responseHeaders.contains("Content-Encoding: br"));
    Assert.assertTrue(responseHeaders.contains("Content-Length: " + brSize));
    Assert.assertTrue(responseHeaders.contains("vary: accept-encoding"));

    // Chrome 50 Accept-Encoding
    client.reset();
    client.setRequest(new String[] {
            "GET /index.html HTTP/1.1" + CRLF +
                    "Host: localhost" + CRLF +
                    "Connection: Close" + CRLF +
                    "Accept-Encoding: gzip, deflate, sdch, br" + CRLF + CRLF });
    client.connect();
    client.processRequest();
    Assert.assertTrue(client.isResponse200());
    responseHeaders = client.getResponseHeaders();
    Assert.assertTrue(responseHeaders.contains("Content-Encoding: br"));
    Assert.assertTrue(responseHeaders.contains("Content-Length: " + brSize));
    Assert.assertTrue(responseHeaders.contains("vary: accept-encoding"));
}
 
Example 17
Source File: TestDefaultServlet.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
@Test
public void testIdentityAndStarAcceptEncodings() throws Exception {

    Tomcat tomcat = getTomcatInstance();

    File appDir = new File("test/webapp");

    long brSize = new File(appDir, "index.html.br").length();
    long indexSize = new File(appDir, "index.html").length();

    // app dir is relative to server home
    Context ctxt = tomcat.addContext("", appDir.getAbsolutePath());
    Wrapper defaultServlet = Tomcat.addServlet(ctxt, "default",
            DefaultServlet.class.getName());
    defaultServlet.addInitParameter("precompressed", "br=.br,gzip=.gz");
    defaultServlet.addInitParameter("fileEncoding", "ISO-8859-1");

    ctxt.addServletMappingDecoded("/", "default");
    ctxt.addMimeMapping("html", "text/html");

    tomcat.start();

    TestCompressedClient client = new TestCompressedClient(getPort());

    client.reset();
    client.setRequest(new String[] {
            "GET /index.html HTTP/1.1" + CRLF +
                    "Host: localhost" + CRLF +
                    "Connection: Close" + CRLF +
                    "Accept-Encoding: gzip;q=0.9,*" + CRLF + CRLF });
    client.connect();
    client.processRequest();
    Assert.assertTrue(client.isResponse200());
    List<String> responseHeaders = client.getResponseHeaders();
    Assert.assertTrue(responseHeaders.contains("Content-Encoding: br"));
    Assert.assertTrue(responseHeaders.contains("Content-Length: " + brSize));
    Assert.assertTrue(responseHeaders.contains("vary: accept-encoding"));

    client.reset();
    client.setRequest(new String[] {
            "GET /index.html HTTP/1.1" + CRLF +
                    "Host: localhost" + CRLF +
                    "Connection: Close" + CRLF +
                    "Accept-Encoding: gzip;q=0.9,br;q=0,identity," + CRLF + CRLF });
    client.connect();
    client.processRequest();
    Assert.assertTrue(client.isResponse200());
    responseHeaders = client.getResponseHeaders();
    Assert.assertFalse(responseHeaders.contains("Content-Encoding"));
    Assert.assertTrue(responseHeaders.contains("Content-Length: " + indexSize));
    Assert.assertTrue(responseHeaders.contains("vary: accept-encoding"));
}
 
Example 18
Source File: TestDefaultServlet.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
@Test
public void testCustomCompressedFile() throws Exception {

    Tomcat tomcat = getTomcatInstance();

    File appDir = new File("test/webapp");

    long brSize = new File(appDir, "index.html.br").length();
    long gzSize = new File(appDir, "index.html.gz").length();

    // app dir is relative to server home
    Context ctxt = tomcat.addContext("", appDir.getAbsolutePath());
    Wrapper defaultServlet = Tomcat.addServlet(ctxt, "default",
            DefaultServlet.class.getName());
    defaultServlet.addInitParameter("precompressed", "gzip=.gz,custom=.br");

    ctxt.addServletMappingDecoded("/", "default");
    ctxt.addMimeMapping("html", "text/html");

    tomcat.start();

    TestCompressedClient client = new TestCompressedClient(getPort());

    client.reset();
    client.setRequest(new String[] {
            "GET /index.html HTTP/1.1" + CRLF +
                    "Host: localhost" + CRLF +
                    "Connection: Close" + CRLF +
                    "Accept-Encoding: br, gzip ; q = 0.5 , custom" + CRLF + CRLF });
    client.connect();
    client.processRequest();
    Assert.assertTrue(client.isResponse200());
    List<String> responseHeaders = client.getResponseHeaders();
    Assert.assertTrue(responseHeaders.contains("Content-Encoding: custom"));
    Assert.assertTrue(responseHeaders.contains("Content-Length: " + brSize));
    Assert.assertTrue(responseHeaders.contains("vary: accept-encoding"));

    client.reset();
    client.setRequest(new String[] {
            "GET /index.html HTTP/1.1" + CRLF +
                    "Host: localhost" + CRLF +
                    "Connection: Close" + CRLF +
                    "Accept-Encoding: br;q=1,gzip,custom" + CRLF + CRLF });
    client.connect();
    client.processRequest();
    Assert.assertTrue(client.isResponse200());
    responseHeaders = client.getResponseHeaders();
    Assert.assertTrue(responseHeaders.contains("Content-Encoding: gzip"));
    Assert.assertTrue(responseHeaders.contains("Content-Length: " + gzSize));
    Assert.assertTrue(responseHeaders.contains("vary: accept-encoding"));
}
 
Example 19
Source File: TestDefaultServlet.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
@Test
public void testGzippedFile() throws Exception {

    Tomcat tomcat = getTomcatInstance();

    File appDir = new File("test/webapp");

    File gzipIndex = new File(appDir, "index.html.gz");
    long gzipSize = gzipIndex.length();

    File index = new File(appDir, "index.html");
    long indexSize = index.length();

    // app dir is relative to server home
    Context ctxt = tomcat.addContext("", appDir.getAbsolutePath());
    Wrapper defaultServlet = Tomcat.addServlet(ctxt, "default",
            "org.apache.catalina.servlets.DefaultServlet");
    defaultServlet.addInitParameter("gzip", "true");
    defaultServlet.addInitParameter("fileEncoding", "ISO-8859-1");
    ctxt.addServletMappingDecoded("/", "default");

    ctxt.addMimeMapping("html", "text/html");

    tomcat.start();

    TestCompressedClient gzipClient = new TestCompressedClient(getPort());

    gzipClient.reset();
    gzipClient.setRequest(new String[] {
            "GET /index.html HTTP/1.1" + CRLF +
            "Host: localhost" + CRLF +
            "Connection: Close" + CRLF +
            "Accept-Encoding: gzip, br" + CRLF + CRLF });
    gzipClient.connect();
    gzipClient.processRequest();
    Assert.assertTrue(gzipClient.isResponse200());
    List<String> responseHeaders = gzipClient.getResponseHeaders();
    Assert.assertTrue(responseHeaders.contains("Content-Encoding: gzip"));
    Assert.assertTrue(responseHeaders.contains("Content-Length: " + gzipSize));
    Assert.assertTrue(responseHeaders.contains("vary: accept-encoding"));

    gzipClient.reset();
    gzipClient.setRequest(new String[] {
            "GET /index.html HTTP/1.1" + CRLF +
            "Host: localhost" + CRLF +
            "Connection: Close" + CRLF+ CRLF });
    gzipClient.connect();
    gzipClient.processRequest();
    Assert.assertTrue(gzipClient.isResponse200());
    responseHeaders = gzipClient.getResponseHeaders();
    Assert.assertTrue(responseHeaders.contains("Content-Type: text/html"));
    Assert.assertFalse(responseHeaders.contains("Content-Encoding: gzip"));
    Assert.assertTrue(responseHeaders.contains("Content-Length: " + indexSize));
    Assert.assertTrue(responseHeaders.contains("vary: accept-encoding"));
}
 
Example 20
Source File: ApplicationContext.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
private ServletRegistration.Dynamic addServlet(String servletName, String servletClass,
        Servlet servlet, Map<String,String> initParams) throws IllegalStateException {

    if (servletName == null || servletName.equals("")) {
        throw new IllegalArgumentException(sm.getString(
                "applicationContext.invalidServletName", servletName));
    }

    if (!context.getState().equals(LifecycleState.STARTING_PREP)) {
        //TODO Spec breaking enhancement to ignore this restriction
        throw new IllegalStateException(
                sm.getString("applicationContext.addServlet.ise",
                        getContextPath()));
    }

    Wrapper wrapper = (Wrapper) context.findChild(servletName);

    // Assume a 'complete' ServletRegistration is one that has a class and
    // a name
    if (wrapper == null) {
        wrapper = context.createWrapper();
        wrapper.setName(servletName);
        context.addChild(wrapper);
    } else {
        if (wrapper.getName() != null &&
                wrapper.getServletClass() != null) {
            if (wrapper.isOverridable()) {
                wrapper.setOverridable(false);
            } else {
                return null;
            }
        }
    }

    ServletSecurity annotation = null;
    if (servlet == null) {
        wrapper.setServletClass(servletClass);
        Class<?> clazz = Introspection.loadClass(context, servletClass);
        if (clazz != null) {
            annotation = clazz.getAnnotation(ServletSecurity.class);
        }
    } else {
        wrapper.setServletClass(servlet.getClass().getName());
        wrapper.setServlet(servlet);
        if (context.wasCreatedDynamicServlet(servlet)) {
            annotation = servlet.getClass().getAnnotation(ServletSecurity.class);
        }
    }

    if (initParams != null) {
        for (Map.Entry<String, String> initParam: initParams.entrySet()) {
            wrapper.addInitParameter(initParam.getKey(), initParam.getValue());
        }
    }

    ServletRegistration.Dynamic registration =
            new ApplicationServletRegistration(wrapper, context);
    if (annotation != null) {
        registration.setServletSecurity(new ServletSecurityElement(annotation));
    }
    return registration;
}