org.apache.catalina.Context Java Examples

The following examples show how to use org.apache.catalina.Context. 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: TestRequest.java    From tomcatsrc with Apache License 2.0 6 votes vote down vote up
private void doBug56501(String deployPath, String requestPath, String expected)
        throws Exception {

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

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

    Tomcat.addServlet(ctx, "servlet", new Bug56501Servelet());
    ctx.addServletMapping("/*", "servlet");

    tomcat.start();

    ByteChunk res = getUrl("http://localhost:" + getPort() + requestPath);
    String resultPath = res.toString();
    if (resultPath == null) {
        resultPath = "";
    }
    assertEquals(expected, resultPath);
}
 
Example #2
Source File: TestHandlerIntegration.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
@Test
public void testToURI() throws Exception {
    Tomcat tomcat = getTomcatInstance();

    File docBase = new File("test/webresources/war-url-connection.war");
    Context ctx = tomcat.addWebapp("/test", docBase.getAbsolutePath());
    skipTldsForResourceJars(ctx);

    ((StandardHost) tomcat.getHost()).setUnpackWARs(false);

    tomcat.start();

    URL url = ctx.getServletContext().getResource("/index.html");
    try {
        url.toURI();
    } catch (Exception e) {
        e.printStackTrace();
        Assert.fail();
    }
}
 
Example #3
Source File: MBeanFactory.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
/**
 * Create a new Web Application Loader.
 *
 * @param parent MBean Name of the associated parent component
 * @return the object name of the created loader
 *
 * @exception Exception if an MBean cannot be created or registered
 */
public String createWebappLoader(String parent)
    throws Exception {

    // Create a new WebappLoader instance
    WebappLoader loader = new WebappLoader();

    // Add the new instance to its parent component
    ObjectName pname = new ObjectName(parent);
    Container container = getParentContainerFromParent(pname);
    if (container instanceof Context) {
        ((Context) container).setLoader(loader);
    }
    // FIXME add Loader.getObjectName
    //ObjectName oname = loader.getObjectName();
    ObjectName oname =
        MBeanUtils.createObjectName(pname.getDomain(), loader);
    return oname.toString();

}
 
Example #4
Source File: OpenEJBContextConfig.java    From tomee with Apache License 2.0 6 votes vote down vote up
private Set<Class<?>> getJsfClasses(final Context context) {
    final WebAppBuilder builder = SystemInstance.get().getComponent(WebAppBuilder.class);
    final ClassLoader cl = context.getLoader().getClassLoader();
    final Map<String, Set<String>> scanned = builder.getJsfClasses().get(cl);

    if (scanned == null || scanned.isEmpty()) {
        return null;
    }

    final Set<Class<?>> classes = new HashSet<>();
    for (final Set<String> entry : scanned.values()) {
        for (final String name : entry) {
            try {
                classes.add(cl.loadClass(name));
            } catch (final ClassNotFoundException ignored) {
                logger.warning("class '" + name + "' was found but can't be loaded as a JSF class");
            }
        }
    }

    return classes;
}
 
Example #5
Source File: TestCoyoteInputStream.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
@Test
public void testReadWithByteBuffer() throws Exception {
    Tomcat tomcat = getTomcatInstance();

    Context root = tomcat.addContext("", TEMP_DIR);
    Tomcat.addServlet(root, "testServlet", new TestServlet());
    root.addServletMappingDecoded("/", "testServlet");

    tomcat.start();

    ByteChunk bc = new ByteChunk();
    String requestBody = "HelloWorld";
    int rc = postUrl(requestBody.getBytes(StandardCharsets.UTF_8),
            "http://localhost:" + getPort() + "/", bc, null);
    Assert.assertEquals(HttpServletResponse.SC_OK, rc);
    Assert.assertTrue(requestBody.equals(bc.toString()));
}
 
Example #6
Source File: TestResponse.java    From Tomcat7.0.67 with Apache License 2.0 6 votes vote down vote up
/**
 * Tests an issue noticed during the investigation of BZ 52811.
 */
@Test
public void testCharset() throws Exception {
    // Setup Tomcat instance
    Tomcat tomcat = getTomcatInstance();

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

    Tomcat.addServlet(ctx, "servlet", new CharsetServlet());
    ctx.addServletMapping("/", "servlet");

    tomcat.start();

    ByteChunk bc = getUrl("http://localhost:" + getPort() + "/");

    assertEquals("OK", bc.toString());
}
 
Example #7
Source File: TestWsWebSocketContainer.java    From Tomcat7.0.67 with Apache License 2.0 6 votes vote down vote up
@Test(expected=javax.websocket.DeploymentException.class)
public void testConnectToServerEndpointInvalidScheme() throws Exception {
    Tomcat tomcat = getTomcatInstance();
    // No file system docBase required
    Context ctx = tomcat.addContext("", null);
    ctx.addApplicationListener(TesterEchoServer.Config.class.getName());

    tomcat.start();

    WebSocketContainer wsContainer =
            ContainerProvider.getWebSocketContainer();
    wsContainer.connectToServer(TesterProgrammaticEndpoint.class,
            ClientEndpointConfig.Builder.create().build(),
            new URI("ftp://" + getHostName() + ":" + getPort() +
                    TesterEchoServer.Config.PATH_ASYNC));
}
 
Example #8
Source File: TestNamingContextListener.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
@Test
public void testBug49132() throws Exception {
    Tomcat tomcat = getTomcatInstance();

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

    // Enable JNDI - it is disabled by default
    tomcat.enableNaming();

    ContextEnvironment environment = new ContextEnvironment();
    environment.setType(BUG49132_VALUE.getClass().getName());
    environment.setName(BUG49132_NAME);
    environment.setValue(BUG49132_VALUE);
    ctx.getNamingResources().addEnvironment(environment);

    ctx.addApplicationListener(Bug49132Listener.class.getName());

    tomcat.start();

    Assert.assertEquals(LifecycleState.STARTED, ctx.getState());
}
 
Example #9
Source File: StandardHostValve.java    From tomcatsrc with Apache License 2.0 6 votes vote down vote up
/**
 * Find and return the ErrorPage instance for the specified exception's
 * class, or an ErrorPage instance for the closest superclass for which
 * there is such a definition.  If no associated ErrorPage instance is
 * found, return <code>null</code>.
 *
 * @param context The Context in which to search
 * @param exception The exception for which to find an ErrorPage
 */
private static ErrorPage findErrorPage
    (Context context, Throwable exception) {

    if (exception == null)
        return (null);
    Class<?> clazz = exception.getClass();
    String name = clazz.getName();
    while (!Object.class.equals(clazz)) {
        ErrorPage errorPage = context.findErrorPage(name);
        if (errorPage != null)
            return (errorPage);
        clazz = clazz.getSuperclass();
        if (clazz == null)
            break;
        name = clazz.getName();
    }
    return (null);

}
 
Example #10
Source File: Tomcat.java    From tomcatsrc with Apache License 2.0 6 votes vote down vote up
@Override
public void lifecycleEvent(LifecycleEvent event) {
    try {
        Context context = (Context) event.getLifecycle();
        if (event.getType().equals(Lifecycle.CONFIGURE_START_EVENT)) {
            context.setConfigured(true);
        }
        // LoginConfig is required to process @ServletSecurity
        // annotations
        if (context.getLoginConfig() == null) {
            context.setLoginConfig(
                    new LoginConfig("NONE", null, null, null));
            context.getPipeline().addValve(new NonLoginAuthenticator());
        }
    } catch (ClassCastException e) {
        return;
    }
}
 
Example #11
Source File: SetNextNamingRule.java    From Tomcat7.0.67 with Apache License 2.0 6 votes vote down vote up
/**
 * Process the end of this element.
 * 
 * @param namespace the namespace URI of the matching element, or an 
 *   empty string if the parser is not namespace aware or the element has
 *   no namespace
 * @param name the local name if the parser is namespace aware, or just 
 *   the element name otherwise
 */
@Override
public void end(String namespace, String name) throws Exception {

    // Identify the objects to be used
    Object child = digester.peek(0);
    Object parent = digester.peek(1);

    NamingResources namingResources = null;
    if (parent instanceof Context) {
        namingResources = ((Context) parent).getNamingResources();
    } else {
        namingResources = (NamingResources) parent;
    }
    
    // Call the specified method
    IntrospectionUtils.callMethod1(namingResources, methodName,
            child, paramType, digester.getClassLoader());

}
 
Example #12
Source File: TestStandardContext.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
private static void configureTest46243Context(Context context, boolean fail) {
    // Add a test filter that fails
    FilterDef filterDef = new FilterDef();
    filterDef.setFilterClass(Bug46243Filter.class.getName());
    filterDef.setFilterName("Bug46243");
    filterDef.addInitParameter("fail", Boolean.toString(fail));
    context.addFilterDef(filterDef);
    FilterMap filterMap = new FilterMap();
    filterMap.setFilterName("Bug46243");
    filterMap.addURLPatternDecoded("*");
    context.addFilterMap(filterMap);

    // Add a test servlet so there is something to generate a response if
    // it works (although it shouldn't)
    Tomcat.addServlet(context, "Bug46243", new HelloWorldServlet());
    context.addServletMappingDecoded("/", "Bug46243");
}
 
Example #13
Source File: ManagerServlet.java    From tomcatsrc with Apache License 2.0 6 votes vote down vote up
private void writeDeployResult(PrintWriter writer, StringManager smClient,
        String name, String displayPath) {
    Context deployed = (Context) host.findChild(name);
    if (deployed != null && deployed.getConfigured() &&
            deployed.getState().isAvailable()) {
        writer.println(smClient.getString(
                "managerServlet.deployed", displayPath));
    } else if (deployed!=null && !deployed.getState().isAvailable()) {
        writer.println(smClient.getString(
                "managerServlet.deployedButNotStarted", displayPath));
    } else {
        // Something failed
        writer.println(smClient.getString(
                "managerServlet.deployFailed", displayPath));
    }
}
 
Example #14
Source File: InvokeJaxwsWebServiceInTomcat.java    From glowroot with Apache License 2.0 6 votes vote down vote up
public void executeApp(String webapp, String contextPath, String url) throws Exception {
    int port = getAvailablePort();
    Tomcat tomcat = new Tomcat();
    tomcat.setBaseDir("target/tomcat");
    tomcat.setPort(port);
    Context context = tomcat.addWebapp(contextPath,
            new File("src/test/resources/" + webapp).getAbsolutePath());

    WebappLoader webappLoader =
            new WebappLoader(InvokeJaxwsWebServiceInTomcat.class.getClassLoader());
    context.setLoader(webappLoader);

    tomcat.start();

    JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();
    factory.setServiceClass(ForBothHelloAndRootService.class);
    factory.setAddress("http://localhost:" + port + contextPath + url);
    ForBothHelloAndRootService client = (ForBothHelloAndRootService) factory.create();
    client.echo("abc");

    checkForRequestThreads(webappLoader);
    tomcat.stop();
    tomcat.destroy();
}
 
Example #15
Source File: TomcatPolyfill.java    From Milkomeda with MIT License 5 votes vote down vote up
/**
 * 动态删除过滤器
 * @param name              过滤器名
 * @param servletContext    ServletContext
 * @return  删除是否成功
 */
public static boolean removeDynamicFilter(String name, ServletContext servletContext) {
    Context standContext = ReflectUtil.invokeFieldPath(servletContext, "context.context");
    if (standContext == null) {
        log.warn("Hydrogen filter find path '((ApplicationContextFacade) servletContext).context.context' fail.");
        return false;
    }

    // ((ApplicationContextFacade) servletContext).context.context.filterMaps(在filterChain里根据映射的filterMaps转filterConfigs)
    FilterMap[] filterMaps = ReflectUtil.invokeMethod(standContext, "findFilterMaps", null);
    if (filterMaps == null) {
        log.warn("Hydrogen filter find path '((ApplicationContextFacade) servletContext).context.context.findFilterMaps()' fail.");
        return false;
    }
    for (FilterMap filterMap : filterMaps) {
        if (filterMap.getFilterName().equals(name)) {
            ReflectUtil.invokeMethod(standContext, "removeFilterMap", new Class[]{FilterMap.class}, filterMap);
            break;
        }
    }

    // ((ApplicationContextFacade) servletContext).context.context.filterDefs(filterMaps和filterConfigs的数据源,并提供给外部接口访问)
    FilterDef filterDef = ReflectUtil.invokeMethod(standContext, "findFilterDef", new Class[]{String.class}, name);
    if (filterDef != null) {
        ReflectUtil.invokeMethod(standContext, "removeFilterDef", new Class[]{FilterDef.class}, filterDef);
    }

    // ((ApplicationContextFacade) servletContext).context.context.filterConfigs (FilterChain具体会读这个属性里的过滤器)
    Map<String, ApplicationFilterConfig> filterConfigs = ReflectUtil.invokeFieldPath(standContext, "filterConfigs");
    if (filterConfigs == null) {
        log.warn("Hydrogen filter find path '((ApplicationContextFacade) servletContext).context.context.filterConfigs' fail.");
        return false;
    }
    filterConfigs.remove(name);

    // boolean ((ApplicationContextFacade) servletContext).context.context.filterStart() (把filterDefs加载到filterConfigs)
    return (boolean) ReflectUtil.invokeMethod(standContext, "filterStart", null);
}
 
Example #16
Source File: TestAsyncContextImpl.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@Test
public void testErrorHandling() throws Exception {
    resetTracker();
    // Setup Tomcat instance
    Tomcat tomcat = getTomcatInstance();

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

    ErrorServlet error = new ErrorServlet();
    Tomcat.addServlet(ctx, "error", error);
    ctx.addServletMappingDecoded("/error", "error");

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

    tomcat.start();

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

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

    Assert.assertEquals(500, rc);

    // Without this test may complete before access log has a chance to log
    // the request
    Thread.sleep(REQUEST_TIME);

    // Check the access log
    alv.validateAccessLog(1, 500, 0, REQUEST_TIME);
}
 
Example #17
Source File: TestResponse.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@Test
public void testBug49598() throws Exception {
    // Setup Tomcat instance
    Tomcat tomcat = getTomcatInstance();

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

    Tomcat.addServlet(ctx, "servlet", new Bug49598Servlet());
    ctx.addServletMappingDecoded("/", "servlet");

    tomcat.start();

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

    // Check for headers without a name
    for (Map.Entry<String,List<String>> header : headers.entrySet()) {
        if (header.getKey() == null) {
            // Expected if this is the response line
            List<String> values = header.getValue();
            if (values.size() == 1 &&
                    values.get(0).startsWith("HTTP/1.1")) {
                continue;
            }
            Assert.fail("Null header name detected for value " + values);
        }
    }

    // Check for exactly one Set-Cookie header
    int count = 0;
    for (String headerName : headers.keySet()) {
        if ("Set-Cookie".equals(headerName)) {
            count ++;
        }
    }
    Assert.assertEquals(1, count);
}
 
Example #18
Source File: ManagerBase.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
@Override
public int getMaxInactiveInterval() {
    Container container = getContainer();
    if (container instanceof Context) {
        // This method returns seconds, the Context uses minutes
        return ((Context) container).getSessionTimeout() * 60;
    }
    return -1;
}
 
Example #19
Source File: InvokeSpringControllerInTomcat.java    From glowroot with Apache License 2.0 5 votes vote down vote up
public void executeApp(String webapp, String contextPath, RunnableWithPort runnable)
        throws Exception {
    int port = getAvailablePort();
    Tomcat tomcat = new Tomcat();
    tomcat.setBaseDir("target/tomcat");
    tomcat.setPort(port);
    Context context = tomcat.addWebapp(contextPath,
            new File("src/test/resources/" + webapp).getAbsolutePath());

    WebappLoader webappLoader =
            new WebappLoader(InvokeSpringControllerInTomcat.class.getClassLoader());
    context.setLoader(webappLoader);

    tomcat.start();

    runnable.run(port);

    // spring still does a bit of work after the response is concluded,
    // see org.springframework.web.servlet.FrameworkServlet.publishRequestHandledEvent(),
    // so give a bit of time here, otherwise end up with sporadic test failures due to
    // ERROR logged by org.apache.catalina.loader.WebappClassLoaderBase, e.g.
    // "The web application [] is still processing a request that has yet to finish"
    MILLISECONDS.sleep(200);
    checkForRequestThreads(webappLoader);
    tomcat.stop();
    tomcat.destroy();
}
 
Example #20
Source File: StatsServer.java    From cxf with Apache License 2.0 5 votes vote down vote up
public static void main(final String[] args) throws Exception {
    // Register and map the dispatcher servlet
    final File base = new File(System.getProperty("java.io.tmpdir"));

    final Tomcat server = new Tomcat();
    server.setPort(8686);
    server.setBaseDir(base.getAbsolutePath());

    final StandardContext context = (StandardContext)server.addWebapp("/", base.getAbsolutePath());
    context.setConfigFile(StatsServer.class.getResource("/META-INF/context.xml"));
    context.addApplicationListener(ContextLoaderListener.class.getName());
    context.setAddWebinfClassesResources(true);
    context.setResources(resourcesFrom(context, "target/classes"));
    context.setParentClassLoader(Thread.currentThread().getContextClassLoader());

    final Wrapper cxfServlet = Tomcat.addServlet(context, "cxfServlet", new CXFServlet());
    cxfServlet.setAsyncSupported(true);
    context.addServletMappingDecoded("/rest/*", "cxfServlet");

    final Context staticContext = server.addWebapp("/static", base.getAbsolutePath());
    Tomcat.addServlet(staticContext, "cxfStaticServlet", new DefaultServlet());
    staticContext.addServletMappingDecoded("/static/*", "cxfStaticServlet");
    staticContext.setResources(resourcesFrom(staticContext, "target/classes/web-ui"));
    staticContext.setParentClassLoader(Thread.currentThread().getContextClassLoader());

    server.start();
    server.getServer().await();
}
 
Example #21
Source File: TestRewriteValve.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
private void doTestRedirect(String config, String request, String expectedURI,
    int expectedStatusCode) throws Exception {

    Tomcat tomcat = getTomcatInstance();

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

    RewriteValve rewriteValve = new RewriteValve();
    ctx.getPipeline().addValve(rewriteValve);

    rewriteValve.setConfiguration(config);

    Tomcat.addServlet(ctx, "tester", new TesterServlet());
    ctx.addServletMappingDecoded("/from/a", "tester");
    ctx.addServletMappingDecoded("/to/b", "tester");

    tomcat.start();

    ByteChunk res = new ByteChunk();
    Map<String, List<String>> resHead = new HashMap<>();
    int rc = methodUrl("http://localhost:" + getPort() + request, res,
            DEFAULT_CLIENT_TIMEOUT_MS, null, resHead, "GET", false);
    res.setCharset(StandardCharsets.UTF_8);

    if (expectedURI == null) {
        // Rewrite is expected to fail. Probably because invalid characters
        // were written into the request target
        Assert.assertEquals(400, rc);
    } else {
        List<String> locations = resHead.get("Location");
        Assert.assertFalse(locations.isEmpty());
        String redirectURI = locations.get(0);
        Assert.assertEquals(expectedURI, redirectURI);
        Assert.assertEquals(expectedStatusCode, rc);
    }
}
 
Example #22
Source File: ThreadLocalLeakPreventionListener.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
protected void processContainerAddChild(Container parent, Container child) {
    if (log.isDebugEnabled())
        log.debug("Process addChild[parent=" + parent + ",child=" + child +
            "]");

    if (child instanceof Context) {
        registerContextListener((Context) child);
    } else if (child instanceof Engine) {
        registerListenersForEngine((Engine) child);
    } else if (child instanceof Host) {
        registerListenersForHost((Host) child);
    }

}
 
Example #23
Source File: ThreadLocalLeakPreventionListener.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
/**
 * Listens for {@link LifecycleEvent} for the start of the {@link Server} to
 * initialize itself and then for after_stop events of each {@link Context}.
 */
@Override
public void lifecycleEvent(LifecycleEvent event) {
    try {
        Lifecycle lifecycle = event.getLifecycle();
        if (Lifecycle.AFTER_START_EVENT.equals(event.getType()) &&
                lifecycle instanceof Server) {
            // when the server starts, we register ourself as listener for
            // all context
            // as well as container event listener so that we know when new
            // Context are deployed
            Server server = (Server) lifecycle;
            registerListenersForServer(server);
        }

        if (Lifecycle.BEFORE_STOP_EVENT.equals(event.getType()) &&
                lifecycle instanceof Server) {
            // Server is shutting down, so thread pools will be shut down so
            // there is no need to clean the threads
            serverStopping = true;
        }

        if (Lifecycle.AFTER_STOP_EVENT.equals(event.getType()) &&
                lifecycle instanceof Context) {
            stopIdleThreads((Context) lifecycle);
        }
    } catch (Exception e) {
        String msg =
            sm.getString(
                "threadLocalLeakPreventionListener.lifecycleEvent.error",
                event);
        log.error(msg, e);
    }
}
 
Example #24
Source File: StandardWrapper.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
/**
 * Set the parent Container of this Wrapper, but only if it is a Context.
 *
 * @param container Proposed parent Container
 */
@Override
public void setParent(Container container) {

    if ((container != null) &&
        !(container instanceof Context))
        throw new IllegalArgumentException
            (sm.getString("standardWrapper.notContext"));
    if (container instanceof StandardContext) {
        swallowOutput = ((StandardContext)container).getSwallowOutput();
        unloadDelay = ((StandardContext)container).getUnloadDelay();
    }
    super.setParent(container);

}
 
Example #25
Source File: TestStandardContext.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@Test
public void testBug56903() {
    Context context = new StandardContext();

    context.setResourceOnlyServlets("a,b,c");
    Assert.assertThat(Arrays.asList(context.getResourceOnlyServlets().split(",")),
            CoreMatchers.hasItems("a", "b", "c"));
}
 
Example #26
Source File: LowTypedRealm.java    From tomee with Apache License 2.0 5 votes vote down vote up
@Override
public SecurityConstraint[] findSecurityConstraints(final Request request, final Context context) {
    final Map<String, ServletSecurityElement> map = (Map<String, ServletSecurityElement>) invoke(findSecurityConstraintsMethod, request.getRequest(), context.getPath());
    final List<SecurityConstraint> constraints = new ArrayList<SecurityConstraint>();
    for (final Map.Entry<String, ServletSecurityElement> entry : map.entrySet()) {
        constraints.addAll(Arrays.asList(SecurityConstraint.createConstraints(entry.getValue(), entry.getKey())));
    }
    return constraints.toArray(new SecurityConstraint[constraints.size()]);
}
 
Example #27
Source File: TestRequest.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
@Test
public void testBug49424WithChunking() throws Exception {
    Tomcat tomcat = getTomcatInstance();
    // No file system docBase required
    Context root = tomcat.addContext("", null);
    Tomcat.addServlet(root, "Bug37794", new Bug37794Servlet());
    root.addServletMapping("/", "Bug37794");
    tomcat.start();

    HttpURLConnection conn = getConnection("http://localhost:" + getPort() + "/");
    conn.setChunkedStreamingMode(8 * 1024);
    InputStream is = conn.getInputStream();
    assertNotNull(is);
}
 
Example #28
Source File: TestConnector.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@Test
public void testStop() throws Exception {
    Tomcat tomcat = getTomcatInstance();

    Context root = tomcat.addContext("", TEMP_DIR);
    Wrapper w =
        Tomcat.addServlet(root, "tester", new TesterServlet());
    w.setAsyncSupported(true);
    root.addServletMappingDecoded("/", "tester");

    Connector connector = tomcat.getConnector();

    tomcat.start();

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

    Assert.assertEquals(200, rc);
    Assert.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;
    }
    Assert.assertEquals(503, rc);
}
 
Example #29
Source File: Request.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
/**
 * @return the extra path information for this request, translated
 * to a real path.
 */
@Override
public String getPathTranslated() {

    Context context = getContext();
    if (context == null) {
        return null;
    }

    if (getPathInfo() == null) {
        return null;
    }

    return context.getServletContext().getRealPath(getPathInfo());
}
 
Example #30
Source File: TestWsWebSocketContainer.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
@Test
public void testConnectToServerEndpoint() throws Exception {
    Tomcat tomcat = getTomcatInstance();
    // No file system docBase required
    Context ctx = tomcat.addContext("", null);
    ctx.addApplicationListener(TesterEchoServer.Config.class.getName());
    Tomcat.addServlet(ctx, "default", new DefaultServlet());
    ctx.addServletMapping("/", "default");

    tomcat.start();

    WebSocketContainer wsContainer =
            ContainerProvider.getWebSocketContainer();
    // Set this artificially small to trigger
    // https://bz.apache.org/bugzilla/show_bug.cgi?id=57054
    wsContainer.setDefaultMaxBinaryMessageBufferSize(64);
    Session wsSession = wsContainer.connectToServer(
            TesterProgrammaticEndpoint.class,
            ClientEndpointConfig.Builder.create().build(),
            new URI("ws://" + getHostName() + ":" + getPort() +
                    TesterEchoServer.Config.PATH_ASYNC));
    CountDownLatch latch = new CountDownLatch(1);
    BasicText handler = new BasicText(latch);
    wsSession.addMessageHandler(handler);
    wsSession.getBasicRemote().sendText(MESSAGE_STRING_1);

    boolean latchResult = handler.getLatch().await(10, TimeUnit.SECONDS);

    Assert.assertTrue(latchResult);

    Queue<String> messages = handler.getMessages();
    Assert.assertEquals(1, messages.size());
    Assert.assertEquals(MESSAGE_STRING_1, messages.peek());

    ((WsWebSocketContainer) wsContainer).destroy();
}