org.apache.catalina.Wrapper Java Examples

The following examples show how to use org.apache.catalina.Wrapper. 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: TomEEMyFacesContainerInitializer.java    From tomee with Apache License 2.0 6 votes vote down vote up
private boolean isFacesServletPresent(final ServletContext ctx) {
    if (ctx instanceof ApplicationContextFacade) {
        try {
            final ApplicationContext appCtx = (ApplicationContext) get(ApplicationContextFacade.class, ctx);
            final Context tomcatCtx = (Context) get(ApplicationContext.class, appCtx);
            if (tomcatCtx instanceof StandardContext) {
                final Container[] servlets = tomcatCtx.findChildren();
                if (servlets != null) {
                    for (final Container s : servlets) {
                        if (s instanceof Wrapper) {
                            if ("javax.faces.webapp.FacesServlet".equals(((Wrapper) s).getServletClass())
                                    || "Faces Servlet".equals(s.getName())) {
                                return true;
                            }
                        }
                    }
                }
            }
        } catch (final Exception e) {
            // no-op
        }
    }
    return false;
}
 
Example #2
Source File: MapperListener.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
/**
 * Unregister wrapper.
 */
private void unregisterWrapper(Wrapper wrapper) {

    Context context = ((Context) wrapper.getParent());
    String contextPath = context.getPath();
    String wrapperName = wrapper.getName();

    if ("/".equals(contextPath)) {
        contextPath = "";
    }
    String version = context.getWebappVersion();
    String hostName = context.getParent().getName();

    String[] mappings = wrapper.findMappings();

    for (String mapping : mappings) {
        mapper.removeWrapper(hostName, contextPath, version,  mapping);
    }

    if(log.isDebugEnabled()) {
        log.debug(sm.getString("mapperListener.unregisterWrapper",
                wrapperName, contextPath, service));
    }
}
 
Example #3
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 #4
Source File: TestErrorReportValve.java    From Tomcat7.0.67 with Apache License 2.0 6 votes vote down vote up
@Test
public void testBug56042() throws Exception {
    // Setup Tomcat instance
    Tomcat tomcat = getTomcatInstance();

    // No file system docBase required
    Context ctx = tomcat.addContext("", null);

    Bug56042Servlet bug56042Servlet = new Bug56042Servlet();
    Wrapper wrapper =
        Tomcat.addServlet(ctx, "bug56042Servlet", bug56042Servlet);
    wrapper.setAsyncSupported(true);
    ctx.addServletMapping("/bug56042Servlet", "bug56042Servlet");

    tomcat.start();

    StringBuilder url = new StringBuilder(48);
    url.append("http://localhost:");
    url.append(getPort());
    url.append("/bug56042Servlet");

    ByteChunk res = new ByteChunk();
    int rc = getUrl(url.toString(), res, null);

    Assert.assertEquals(HttpServletResponse.SC_BAD_REQUEST, rc);
}
 
Example #5
Source File: ApplicationContext.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
/**
 * Return a <code>RequestDispatcher</code> object that acts as a
 * wrapper for the named servlet.
 *
 * @param name Name of the servlet for which a dispatcher is requested
 */
@Override
public RequestDispatcher getNamedDispatcher(String name) {

    // Validate the name argument
    if (name == null)
        return null;

    // Create and return a corresponding request dispatcher
    Wrapper wrapper = (Wrapper) context.findChild(name);
    if (wrapper == null)
        return null;

    return new ApplicationDispatcher(wrapper, null, null, null, null, null, name);

}
 
Example #6
Source File: TomcatWebAppBuilder.java    From tomee with Apache License 2.0 6 votes vote down vote up
private void ensureMyFacesDontLooseFacesContext(final StandardContext standardContext) {
    for (final Container w : standardContext.findChildren()) {
        if (!Wrapper.class.isInstance(w)) {
            continue;
        }
        final Wrapper wrapper = Wrapper.class.cast(w);
        if ("FacesServlet".equals(wrapper.getName()) && "javax.faces.webapp.FacesServlet".equals(wrapper.getServletClass())) {
            final ClassLoader loader = standardContext.getLoader().getClassLoader();
            try {
                if (Files.toFile(loader.getResource("javax/faces/webapp/FacesServlet.class")).getName().startsWith("myfaces")) {
                    loader.loadClass("org.apache.tomee.myfaces.TomEEWorkaroundFacesServlet");
                    wrapper.setServletClass("org.apache.tomee.myfaces.TomEEWorkaroundFacesServlet");
                    break;
                }
            } catch (final Throwable t) {
                // not there, not a big deal in most of cases
            }
        }
    }
}
 
Example #7
Source File: TestErrorReportValve.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
@Test
public void testBug56042() throws Exception {
    // Setup Tomcat instance
    Tomcat tomcat = getTomcatInstance();

    // No file system docBase required
    Context ctx = tomcat.addContext("", null);

    Bug56042Servlet bug56042Servlet = new Bug56042Servlet();
    Wrapper wrapper =
        Tomcat.addServlet(ctx, "bug56042Servlet", bug56042Servlet);
    wrapper.setAsyncSupported(true);
    ctx.addServletMappingDecoded("/bug56042Servlet", "bug56042Servlet");

    tomcat.start();

    StringBuilder url = new StringBuilder(48);
    url.append("http://localhost:");
    url.append(getPort());
    url.append("/bug56042Servlet");

    ByteChunk res = new ByteChunk();
    int rc = getUrl(url.toString(), res, null);

    Assert.assertEquals(HttpServletResponse.SC_BAD_REQUEST, rc);
}
 
Example #8
Source File: TestAsyncContextImpl.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
private void doTestAsyncIoEnd(boolean useThread, boolean useComplete) throws Exception {
    Tomcat tomcat = getTomcatInstance();

    // No file system docBase required
    Context ctx = tomcat.addContext("", null);

    AsyncIoEndServlet asyncIoEndServlet = new AsyncIoEndServlet(useThread, useComplete);
    Wrapper wrapper = Tomcat.addServlet(ctx, "asyncIoEndServlet", asyncIoEndServlet);
    wrapper.setAsyncSupported(true);
    ctx.addServletMappingDecoded("/asyncIoEndServlet", "asyncIoEndServlet");

    SimpleServlet simpleServlet = new SimpleServlet();
    Tomcat.addServlet(ctx, "simpleServlet", simpleServlet);
    ctx.addServletMappingDecoded("/simpleServlet", "simpleServlet");

    tomcat.start();

    ByteChunk body = new ByteChunk();
    int rc = getUrl("http://localhost:" + getPort() + "/asyncIoEndServlet", body, null);

    Assert.assertEquals(HttpServletResponse.SC_OK, rc);
    Assert.assertEquals("OK", body.toString());

    Assert.assertFalse(asyncIoEndServlet.getInvalidStateDetected());
}
 
Example #9
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 #10
Source File: ApplicationDispatcher.java    From tomcatsrc with Apache License 2.0 6 votes vote down vote up
/**
 * Construct a new instance of this class, configured according to the
 * specified parameters.  If both servletPath and pathInfo are
 * <code>null</code>, it will be assumed that this RequestDispatcher
 * was acquired by name, rather than by path.
 *
 * @param wrapper The Wrapper associated with the resource that will
 *  be forwarded to or included (required)
 * @param requestURI The request URI to this resource (if any)
 * @param servletPath The revised servlet path to this resource (if any)
 * @param pathInfo The revised extra path information to this resource
 *  (if any)
 * @param queryString Query string parameters included with this request
 *  (if any)
 * @param name Servlet name (if a named dispatcher was created)
 *  else <code>null</code>
 */
public ApplicationDispatcher
    (Wrapper wrapper, String requestURI, String servletPath,
     String pathInfo, String queryString, String name) {

    super();

    // Save all of our configuration parameters
    this.wrapper = wrapper;
    this.context = (Context) wrapper.getParent();
    this.requestURI = requestURI;
    this.servletPath = servletPath;
    this.pathInfo = pathInfo;
    this.queryString = queryString;
    this.name = name;
    if (wrapper instanceof StandardWrapper)
        this.support = ((StandardWrapper) wrapper).getInstanceSupport();
    else
        this.support = new InstanceSupport(wrapper);

}
 
Example #11
Source File: ManualDeploymentTest.java    From tomee with Apache License 2.0 6 votes vote down vote up
@Test
public void run() throws IOException {
    final Configuration configuration = new Configuration().randomHttpPort();
    configuration.setDir(Files.mkdirs(new File("target/" + getClass().getSimpleName() + "-tomcat")).getAbsolutePath());

    try (final Container container = new Container(configuration)) {
        // tomee-embedded (this "container url" is filtered: name prefix + it is a directory (target/test-classes)
        final File parent = Files.mkdirs(new File("target/" + getClass().getSimpleName()));
        final File war = ShrinkWrap.create(WebArchive.class, "the-webapp")
                .addClass(Foo.class)
                .addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml") // activate CDI
                .as(ExplodedExporter.class)
                .exportExploded(parent);

        final Context ctx = container.addContext("", war.getAbsolutePath());

        final Wrapper wrapper = Tomcat.addServlet(ctx, "awesome", AServlet.class.getName());
        ctx.addServletMappingDecoded("/awesome", wrapper.getName());

        assertEquals("Awesome", IO.slurp(new URL("http://localhost:" + configuration.getHttpPort() + "/awesome")).trim());
    } catch (final Exception e) {
        e.printStackTrace();
        fail(e.getMessage());
    }
}
 
Example #12
Source File: ExploreSpring5URLPatternUsingRouterFunctions.java    From tutorials with MIT License 6 votes vote down vote up
WebServer start() throws Exception {
    WebHandler webHandler = (WebHandler) toHttpHandler(routingFunction());
    HttpHandler httpHandler = WebHttpHandlerBuilder.webHandler(webHandler)
        .filter(new IndexRewriteFilter())
        .build();

    Tomcat tomcat = new Tomcat();
    tomcat.setHostname("localhost");
    tomcat.setPort(9090);
    Context rootContext = tomcat.addContext("", System.getProperty("java.io.tmpdir"));
    ServletHttpHandlerAdapter servlet = new ServletHttpHandlerAdapter(httpHandler);
    Wrapper servletWrapper = Tomcat.addServlet(rootContext, "httpHandlerServlet", servlet);
    servletWrapper.setAsyncSupported(true);
    rootContext.addServletMappingDecoded("/", "httpHandlerServlet");

    TomcatWebServer server = new TomcatWebServer(tomcat);
    server.start();
    return server;

}
 
Example #13
Source File: TestAsyncContextImpl.java    From tomcatsrc with Apache License 2.0 6 votes vote down vote up
private void doTestDispatchWithSpaces(boolean async) throws Exception {
    Tomcat tomcat = getTomcatInstance();
    Context context = tomcat.addContext("", null);
    if (async) {
        Servlet s = new AsyncDispatchUrlWithSpacesServlet();
        Wrapper w = Tomcat.addServlet(context, "space", s);
        w.setAsyncSupported(true);
    } else {
        Tomcat.addServlet(context, "space", new ForwardDispatchUrlWithSpacesServlet());
    }
    context.addServletMapping("/space/*", "space");
    tomcat.start();

    ByteChunk responseBody = new ByteChunk();
    int rc = getUrl("http://localhost:" + getPort() + "/sp%61ce/foo%20bar", responseBody, null);

    Assert.assertEquals(200, rc);
}
 
Example #14
Source File: TestAsyncContextImplDispatch.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@Test
public void testSendError() throws Exception {
    // Setup Tomcat instance
    Tomcat tomcat = getTomcatInstance();

    // No file system docBase required
    Context ctx = tomcat.addContext("", null);

    Wrapper w1 = Tomcat.addServlet(ctx, "target", new TesterServlet());
    w1.setAsyncSupported(targetAsyncSupported);
    ctx.addServletMappingDecoded("/target", "target");

    Wrapper w2 = Tomcat.addServlet(ctx, "dispatch", new TesterDispatchServlet(dispatchAsyncStart));
    w2.setAsyncSupported(dispatchAsyncSupported);
    ctx.addServletMappingDecoded("/dispatch", "dispatch");

    tomcat.start();

    ByteChunk bc = new ByteChunk();
    int rc;

    rc = getUrl("http://localhost:" + getPort() + "/target", bc, null, null);

    String body = bc.toString();

    if (allowed) {
        Assert.assertEquals(200, rc);
        Assert.assertEquals("OK", body);
    } else {
        Assert.assertEquals(500, rc);
    }
}
 
Example #15
Source File: OpenEJBContextConfig.java    From tomee with Apache License 2.0 5 votes vote down vote up
private void addAddedJAXWsServices() {
    final WebAppInfo webAppInfo = info.get();
    final AppInfo appInfo = info.app();
    if (webAppInfo == null || appInfo == null || "false".equalsIgnoreCase(appInfo.properties.getProperty("openejb.jaxws.add-missing-servlets", "true"))) {
        return;
    }

    try { // if no jaxws classes are here don't try anything
        OpenEJBContextConfig.class.getClassLoader().loadClass("org.apache.openejb.server.webservices.WsServlet");
    } catch (final ClassNotFoundException | NoClassDefFoundError e) {
        return;
    }

    for (final ServletInfo servlet : webAppInfo.servlets) {
        if (!servlet.mappings.iterator().hasNext()) { // no need to do anything
            continue;
        }

        for (final ParamValueInfo pv : servlet.initParams) {
            if ("openejb-internal".equals(pv.name) && "true".equals(pv.value)) {
                if (context.findChild(servlet.servletName) == null) {
                    final Wrapper wrapper = context.createWrapper();
                    wrapper.setName(servlet.servletName);
                    wrapper.setServletClass("org.apache.openejb.server.webservices.WsServlet");

                    // add servlet to context
                    context.addChild(wrapper);
                    context.addServletMappingDecoded(servlet.mappings.iterator().next(), wrapper.getName());
                }
                break;
            }
        }
    }
}
 
Example #16
Source File: TestConnector.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
@Test
public void testStop() throws Exception {
    Tomcat tomcat = getTomcatInstance();

    // No file system docBase required
    Context root = tomcat.addContext("", null);
    Wrapper w =
        Tomcat.addServlet(root, "tester", new TesterServlet());
    w.setAsyncSupported(true);
    root.addServletMapping("/", "tester");

    Connector connector = tomcat.getConnector();

    tomcat.start();

    ByteChunk bc = new ByteChunk();
    int rc = getUrl("http://localhost:" + getPort() + "/", bc, null, null);

    assertEquals(200, rc);
    assertEquals("OK", bc.toString());

    rc = -1;
    bc.recycle();

    connector.stop();

    try {
        rc = getUrl("http://localhost:" + getPort() + "/", bc, 1000,
                null, null);
    } catch (SocketTimeoutException ste) {
        // May also see this with NIO
        // Make sure the test passes if we do
        rc = 503;
    }
    assertEquals(503, rc);
}
 
Example #17
Source File: TestApplicationContextGetRequestDispatcherB.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@Test
public void doTest() throws Exception {

    // Setup Tomcat instance
    Tomcat tomcat = getTomcatInstance();

    // No file system docBase required
    Context ctx = tomcat.addContext("/test", null);
    ctx.setDispatchersUseEncodedPaths(useEncodedDispatchPaths);
    ctx.addWelcomeFile("index.html");

    // Add a target servlet to dispatch to
    Tomcat.addServlet(ctx, "target", new Target());
    ctx.addServletMappingDecoded(targetMapping, "target");

    Wrapper w = Tomcat.addServlet(ctx, "rd", new Dispatch());
    w.setAsyncSupported(true);
    ctx.addServletMappingDecoded(startMapping, "rd");

    tomcat.start();

    StringBuilder url = new StringBuilder("http://localhost:");
    url.append(getPort());
    url.append("/test");
    url.append(startUri);

    ByteChunk bc = getUrl(url.toString());
    String body = bc.toString();

    Assert.assertEquals(expectedBody, body);
}
 
Example #18
Source File: TestSwallowAbortedUploads.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
private synchronized void init(boolean limited, boolean swallow)
        throws Exception {

    Tomcat tomcat = getTomcatInstance();
    context = tomcat.addContext("", TEMP_DIR);
    Wrapper w;
    w = Tomcat.addServlet(context, servletName,
                          new AbortedUploadServlet());
    // Tomcat.addServlet does not respect annotations, so we have
    // to set our own MultipartConfigElement.
    // Choose upload file size limit.
    if (limited) {
        w.setMultipartConfigElement(new MultipartConfigElement("",
                limitSize, -1, -1));
    } else {
        w.setMultipartConfigElement(new MultipartConfigElement(""));
    }
    context.addServletMappingDecoded(URI, servletName);
    context.setSwallowAbortedUploads(swallow);

    Connector c = tomcat.getConnector();
    c.setMaxPostSize(2 * hugeSize);
    c.setProperty("maxSwallowSize", Integer.toString(hugeSize));

    tomcat.start();
    setPort(c.getLocalPort());
}
 
Example #19
Source File: TomcatWsRegistry.java    From tomee with Apache License 2.0 5 votes vote down vote up
@Override
public void clearWsContainer(final String contextRoot, String virtualHost, final ServletInfo servletInfo, final String moduleId) {
    if (virtualHost == null) {
        virtualHost = engine.getDefaultHost();
    }

    final Container host = engine.findChild(virtualHost);
    if (host == null) {
        throw new IllegalArgumentException("Invalid virtual host '" + virtualHost + "'.  Do you have a matchiing Host entry in the server.xml?");
    }

    final Context context = (Context) host.findChild("/" + contextRoot);
    if (context == null) {
        throw new IllegalArgumentException("Could not find web application context " + contextRoot + " in host " + host.getName());
    }

    final Wrapper wrapper = (Wrapper) context.findChild(servletInfo.servletName);
    if (wrapper == null) {
        throw new IllegalArgumentException("Could not find servlet " + servletInfo.servletName + " in web application context " + context.getName());
    }

    // clear the webservice ref in the servlet context
    final String webServicecontainerId = wrapper.findInitParameter(WsServlet.WEBSERVICE_CONTAINER);
    if (webServicecontainerId != null) {
        context.getServletContext().removeAttribute(webServicecontainerId);
        wrapper.removeInitParameter(WsServlet.WEBSERVICE_CONTAINER);
    }
}
 
Example #20
Source File: TestAsyncContextImpl.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@Test
public void testAsyncStartWithComplete() throws Exception {
    // Setup Tomcat instance
    Tomcat tomcat = getTomcatInstance();

    // No file system docBase required
    Context ctx = tomcat.addContext("", null);

    AsyncStartWithCompleteServlet servlet =
        new AsyncStartWithCompleteServlet();

    Wrapper wrapper = Tomcat.addServlet(ctx, "servlet", servlet);
    wrapper.setAsyncSupported(true);
    ctx.addServletMappingDecoded("/", "servlet");

    TesterAccessLogValve alv = new TesterAccessLogValve();
    ctx.getPipeline().addValve(alv);

    tomcat.start();

    // Call the servlet once
    ByteChunk bc = new ByteChunk();
    Map<String,List<String>> headers = new CaseInsensitiveKeyMap<>();
    getUrl("http://localhost:" + getPort() + "/", bc, headers);

    Assert.assertEquals("OK", bc.toString());
    String contentLength = getSingleHeader("Content-Length", headers);
    Assert.assertEquals("2", contentLength);

    // Check the access log
    alv.validateAccessLog(1, 200, 0, REQUEST_TIME);
}
 
Example #21
Source File: TestAsyncContextImpl.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
@Test
public void testAsyncStartWithComplete() throws Exception {
    // Setup Tomcat instance
    Tomcat tomcat = getTomcatInstance();

    // No file system docBase required
    Context ctx = tomcat.addContext("", null);

    AsyncStartWithCompleteServlet servlet =
        new AsyncStartWithCompleteServlet();

    Wrapper wrapper = Tomcat.addServlet(ctx, "servlet", servlet);
    wrapper.setAsyncSupported(true);
    ctx.addServletMapping("/", "servlet");

    TesterAccessLogValve alv = new TesterAccessLogValve();
    ctx.getPipeline().addValve(alv);

    tomcat.start();

    // Call the servlet once
    ByteChunk bc = new ByteChunk();
    Map<String,List<String>> headers = new HashMap<String,List<String>>();
    getUrl("http://localhost:" + getPort() + "/", bc, headers);

    assertEquals("OK", bc.toString());
    List<String> contentLength = headers.get("Content-Length");
    Assert.assertNotNull(contentLength);
    Assert.assertEquals(1,  contentLength.size());
    Assert.assertEquals("2", contentLength.get(0));

    // Check the access log
    alv.validateAccessLog(1, 200, 0, REQUEST_TIME);
}
 
Example #22
Source File: TestAsyncContextImpl.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
@Test
public void testAsyncContextListenerClearing() throws Exception {
    resetTracker();

    // Setup Tomcat instance
    Tomcat tomcat = getTomcatInstance();

    // No file system docBase required
    Context ctx = tomcat.addContext("", null);

    Servlet stage1 = new DispatchingServletTracking("/stage2", true);
    Wrapper wrapper1 = Tomcat.addServlet(ctx, "stage1", stage1);
    wrapper1.setAsyncSupported(true);
    ctx.addServletMapping("/stage1", "stage1");

    Servlet stage2 = new DispatchingServletTracking("/stage3", false);
    Wrapper wrapper2 = Tomcat.addServlet(ctx, "stage2", stage2);
    wrapper2.setAsyncSupported(true);
    ctx.addServletMapping("/stage2", "stage2");

    Servlet stage3 = new NonAsyncServlet();
    Tomcat.addServlet(ctx, "stage3", stage3);
    ctx.addServletMapping("/stage3", "stage3");

    TesterAccessLogValve alv = new TesterAccessLogValve();
    ctx.getPipeline().addValve(alv);

    tomcat.start();

    getUrl("http://localhost:" + getPort()+ "/stage1");

    assertEquals("doGet-startAsync-doGet-startAsync-onStartAsync-NonAsyncServletGet-onComplete-", getTrack());

    // Check the access log
    alv.validateAccessLog(1, 200, 0, REQUEST_TIME);
}
 
Example #23
Source File: MapperListener.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
/**
 * Populate <code>wrappers</code> list with information for registration of
 * mappings for this wrapper in this context.
 *
 * @param context
 * @param wrapper
 * @param list
 */
private void prepareWrapperMappingInfo(Context context, Wrapper wrapper,
        List<WrapperMappingInfo> wrappers) {
    String wrapperName = wrapper.getName();
    boolean resourceOnly = context.isResourceOnlyServlet(wrapperName);
    String[] mappings = wrapper.findMappings();
    for (String mapping : mappings) {
        boolean jspWildCard = (wrapperName.equals("jsp")
                               && mapping.endsWith("/*"));
        wrappers.add(new WrapperMappingInfo(mapping, wrapper, jspWildCard,
                resourceOnly));
    }
}
 
Example #24
Source File: MapperListener.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
/**
 * Register context.
 */
private void registerContext(Context context) {

    String contextPath = context.getPath();
    if ("/".equals(contextPath)) {
        contextPath = "";
    }
    Container host = context.getParent();

    javax.naming.Context resources = context.getResources();
    String[] welcomeFiles = context.findWelcomeFiles();
    List<WrapperMappingInfo> wrappers = new ArrayList<WrapperMappingInfo>();

    for (Container container : context.findChildren()) {
        prepareWrapperMappingInfo(context, (Wrapper) container, wrappers);

        if(log.isDebugEnabled()) {
            log.debug(sm.getString("mapperListener.registerWrapper",
                    container.getName(), contextPath, connector));
        }
    }

    mapper.addContextVersion(host.getName(), host, contextPath,
            context.getWebappVersion(), context, welcomeFiles, resources,
            wrappers, context.getMapperContextRootRedirectEnabled(),
            context.getMapperDirectoryRedirectEnabled());

    if(log.isDebugEnabled()) {
        log.debug(sm.getString("mapperListener.registerContext",
                contextPath, connector));
    }
}
 
Example #25
Source File: TestAsyncContextImpl.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
@Test
public void testBug53337() throws Exception {
    // Setup Tomcat instance
    Tomcat tomcat = getTomcatInstance();

    // No file system docBase required
    Context ctx = tomcat.addContext("", null);
    Wrapper a = Tomcat.addServlet(ctx, "ServletA", new Bug53337ServletA());
    a.setAsyncSupported(true);
    Wrapper b = Tomcat.addServlet(ctx, "ServletB", new Bug53337ServletB());
    b.setAsyncSupported(true);
    Tomcat.addServlet(ctx, "ServletC", new Bug53337ServletC());
    ctx.addServletMapping("/ServletA", "ServletA");
    ctx.addServletMapping("/ServletB", "ServletB");
    ctx.addServletMapping("/ServletC", "ServletC");

    tomcat.start();

    StringBuilder url = new StringBuilder(48);
    url.append("http://localhost:");
    url.append(getPort());
    url.append("/ServletA");

    ByteChunk body = new ByteChunk();
    int rc = getUrl(url.toString(), body, null);

    assertEquals(HttpServletResponse.SC_OK, rc);
    assertEquals("OK", body.toString());
}
 
Example #26
Source File: TestSwallowAbortedUploads.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
private synchronized void init(boolean limited, boolean swallow)
        throws Exception {
    if (init)
        return;

    Tomcat tomcat = getTomcatInstance();
    context = tomcat.addContext("", TEMP_DIR);
    Wrapper w;
    w = Tomcat.addServlet(context, servletName,
                          new AbortedUploadServlet());
    // Tomcat.addServlet does not respect annotations, so we have
    // to set our own MultipartConfigElement.
    // Choose upload file size limit.
    if (limited) {
        w.setMultipartConfigElement(new MultipartConfigElement("",
                limitSize, -1, -1));
    } else {
        w.setMultipartConfigElement(new MultipartConfigElement(""));
    }
    context.addServletMapping(URI, servletName);
    context.setSwallowAbortedUploads(swallow);

    tomcat.start();
    setPort(tomcat.getConnector().getLocalPort());

    init = true;
}
 
Example #27
Source File: TestAsyncContextImpl.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@Test
public void testBug50753() throws Exception {
    // Setup Tomcat instance
    Tomcat tomcat = getTomcatInstance();

    // No file system docBase required
    Context ctx = tomcat.addContext("", null);

    Bug50753Servlet servlet = new Bug50753Servlet();

    Wrapper wrapper = Tomcat.addServlet(ctx, "servlet", servlet);
    wrapper.setAsyncSupported(true);
    ctx.addServletMappingDecoded("/", "servlet");

    TesterAccessLogValve alv = new TesterAccessLogValve();
    ctx.getPipeline().addValve(alv);

    tomcat.start();

    // Call the servlet once
    Map<String,List<String>> headers = new CaseInsensitiveKeyMap<>();
    ByteChunk bc = new ByteChunk();
    int rc = getUrl("http://localhost:" + getPort() + "/", bc, headers);
    Assert.assertEquals(200, rc);
    Assert.assertEquals("OK", bc.toString());
    String testHeader = getSingleHeader("A", headers);
    Assert.assertEquals("xyz",testHeader);

    // Check the access log
    alv.validateAccessLog(1, 200, Bug50753Servlet.THREAD_SLEEP_TIME,
            Bug50753Servlet.THREAD_SLEEP_TIME + REQUEST_TIME);
}
 
Example #28
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 #29
Source File: ContainerBase.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@Override
public String getMBeanKeyProperties() {
    Container c = this;
    StringBuilder keyProperties = new StringBuilder();
    int containerCount = 0;

    // Work up container hierarchy, add a component to the name for
    // each container
    while (!(c instanceof Engine)) {
        if (c instanceof Wrapper) {
            keyProperties.insert(0, ",servlet=");
            keyProperties.insert(9, c.getName());
        } else if (c instanceof Context) {
            keyProperties.insert(0, ",context=");
            ContextName cn = new ContextName(c.getName(), false);
            keyProperties.insert(9,cn.getDisplayName());
        } else if (c instanceof Host) {
            keyProperties.insert(0, ",host=");
            keyProperties.insert(6, c.getName());
        } else if (c == null) {
            // May happen in unit testing and/or some embedding scenarios
            keyProperties.append(",container");
            keyProperties.append(containerCount++);
            keyProperties.append("=null");
            break;
        } else {
            // Should never happen...
            keyProperties.append(",container");
            keyProperties.append(containerCount++);
            keyProperties.append('=');
            keyProperties.append(c.getName());
        }
        c = c.getParent();
    }
    return keyProperties.toString();
}
 
Example #30
Source File: TestAbstractHttp11Processor.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
@Test
public void testBug57621() throws Exception {

    Tomcat tomcat = getTomcatInstance();
    
    // Must have a real docBase - just use temp
    Context root = tomcat.addContext("", System.getProperty("java.io.tmpdir"));
    
    Wrapper w = Tomcat.addServlet(root, "Bug57621", new Bug57621Servlet());
    w.setAsyncSupported(true);
    root.addServletMapping("/test", "Bug57621");

    tomcat.start();

    Bug57621Client client = new Bug57621Client();
    client.setPort(tomcat.getConnector().getLocalPort());

    client.setUseContentLength(true);

    client.connect();

    client.doRequest();
    assertTrue(client.getResponseLine(), client.isResponse200());
    assertTrue(client.isResponseBodyOK());

    // Do the request again to ensure that the remaining body was swallowed
    client.resetResponse();
    client.processRequest();
    assertTrue(client.isResponse200());
    assertTrue(client.isResponseBodyOK());

    client.disconnect();
}