Java Code Examples for org.apache.catalina.Context

The following are top voted examples for showing how to use org.apache.catalina.Context. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: lams   File: PersistentManagerBase.java   View source code 6 votes vote down vote up
/**
 * Set the Container with which this Manager has been associated. If it is a
 * Context (the usual case), listen for changes to the session timeout
 * property.
 * 
 * @param container
 *            The associated Container
 */
public void setContainer(Container container) {

    // De-register from the old Container (if any)
    if ((this.container != null) && (this.container instanceof Context))
        ((Context) this.container).removePropertyChangeListener(this);

    // Default processing provided by our superclass
    super.setContainer(container);

    // Register with the new Container (if any)
    if ((this.container != null) && (this.container instanceof Context)) {
        setMaxInactiveInterval
            ( ((Context) this.container).getSessionTimeout()*60 );
        ((Context) this.container).addPropertyChangeListener(this);
    }

}
 
Example 2
Project: apache-tomcat-7.0.73-with-comment   File: TestWebSocketFrameClient.java   View source code 6 votes vote down vote up
@Test
public void testConnectToRootEndpoint() 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");
    Context ctx2 = tomcat.addContext("/foo", null);
    ctx2.addApplicationListener(TesterEchoServer.Config.class.getName());
    Tomcat.addServlet(ctx2, "default", new DefaultServlet());
    ctx2.addServletMapping("/", "default");

    tomcat.start();

    echoTester("");
    echoTester("/");
    // FIXME: The ws client doesn't handle any response other than the upgrade,
    // which may or may not be allowed. In that case, the server will return
    // a redirect to the root of the webapp to avoid possible broken relative
    // paths.
    // echoTester("/foo");
    echoTester("/foo/");
}
 
Example 3
Project: lazycat   File: SingleSignOnListener.java   View source code 6 votes vote down vote up
@Override
public void sessionEvent(SessionEvent event) {
	if (!Session.SESSION_DESTROYED_EVENT.equals(event.getType())) {
		return;
	}

	Session session = event.getSession();
	Manager manager = session.getManager();
	if (manager == null) {
		return;
	}
	Context context = (Context) manager.getContainer();
	Authenticator authenticator = context.getAuthenticator();
	if (!(authenticator instanceof AuthenticatorBase)) {
		return;
	}
	SingleSignOn sso = ((AuthenticatorBase) authenticator).sso;
	if (sso == null) {
		return;
	}
	sso.sessionDestroyed(ssoId, session);
}
 
Example 4
Project: tomcat7   File: WebappLoader.java   View source code 6 votes vote down vote up
/**
 * Set the Container with which this Logger has been associated.
 *
 * @param container The associated Container
 */
@Override
public void setContainer(Container container) {

    // Deregister from the old Container (if any)
    if ((this.container != null) && (this.container instanceof Context))
        ((Context) this.container).removePropertyChangeListener(this);

    // Process this property change
    Container oldContainer = this.container;
    this.container = container;
    support.firePropertyChange("container", oldContainer, this.container);

    // Register with the new Container (if any)
    if ((this.container != null) && (this.container instanceof Context)) {
        setReloadable( ((Context) this.container).getReloadable() );
        ((Context) this.container).addPropertyChangeListener(this);
    }

}
 
Example 5
Project: jerrydog   File: WebappLoader.java   View source code 6 votes vote down vote up
/**
 * Start the background thread that will periodically check for
 * session timeouts.
 *
 * @exception IllegalStateException if we should not be starting
 *  a background thread now
 */
private void threadStart() {

    // Has the background thread already been started?
    if (thread != null)
        return;

    // Validate our current state
    if (!reloadable)
        throw new IllegalStateException
            (sm.getString("webappLoader.notReloadable"));
    if (!(container instanceof Context))
        throw new IllegalStateException
            (sm.getString("webappLoader.notContext"));

    // Start the background thread
    if (debug >= 1)
        log(" Starting background thread");
    threadDone = false;
    threadName = "WebappLoader[" + container.getName() + "]";
    thread = new Thread(this, threadName);
    thread.setDaemon(true);
    thread.start();

}
 
Example 6
Project: tomcat7   File: ApplicationDispatcher.java   View source code 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 7
Project: lazycat   File: MapperListener.java   View source code 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, connector));
	}
}
 
Example 8
Project: tomcat7   File: TestCoyoteAdapter.java   View source code 6 votes vote down vote up
private void pathParamExtenionTest(String path, String expected)
        throws Exception {
    // Setup Tomcat instance
    Tomcat tomcat = getTomcatInstance();

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

    Tomcat.addServlet(ctx, "servlet", new PathParamServlet());
    ctx.addServletMapping("*.txt", "servlet");

    tomcat.start();

    ByteChunk res = getUrl("http://localhost:" + getPort() + path);
    Assert.assertEquals(expected, res.toString());
}
 
Example 9
Project: apache-tomcat-7.0.73-with-comment   File: TestStandardContext.java   View source code 6 votes vote down vote up
@Test
public void testTldListener() throws Exception {
    // Set up a container
    Tomcat tomcat = getTomcatInstance();

    File docBase = new File("test/webapp-3.0");
    Context ctx = tomcat.addContext("", docBase.getAbsolutePath());

    // Start the context
    tomcat.start();

    // Stop the context
    ctx.stop();

    String log = TesterTldListener.getLog();
    Assert.assertTrue(log, log.contains("PASS-01"));
    Assert.assertTrue(log, log.contains("PASS-02"));
    Assert.assertFalse(log, log.contains("FAIL"));
}
 
Example 10
Project: jerrydog   File: MBeanFactory.java   View source code 6 votes vote down vote up
/**
 * Remove an existing Context.
 *
 * @param name MBean Name of the comonent to remove
 *
 * @exception Exception if a component cannot be removed
 */
public void removeContext(String name) throws Exception {
    // Acquire a reference to the component to be removed
    ObjectName oname = new ObjectName(name);
    String serviceName = oname.getKeyProperty("service");
    String hostName = oname.getKeyProperty("host");
    String contextName = getPathStr(oname.getKeyProperty("path"));
    Server server = ServerFactory.getServer();
    Service service = server.findService(serviceName);
    Engine engine = (Engine) service.getContainer();
    Host host = (Host) engine.findChild(hostName);
    Context context = (Context) host.findChild(contextName);

    // Remove this component from its parent component
    host.removeChild(context);

}
 
Example 11
Project: apache-tomcat-7.0.73-with-comment   File: TestInputBuffer.java   View source code 6 votes vote down vote up
@Test
public void testUtf8Body() throws Exception {
    Tomcat tomcat = getTomcatInstance();
    // No file system docBase required
    Context root = tomcat.addContext("", null);
    Tomcat.addServlet(root, "Echo", new Utf8Echo());
    root.addServletMapping("/test", "Echo");

    tomcat.getConnector().setProperty("soTimeout", "300000");
    tomcat.start();

    for (Utf8TestCase testCase : TestUtf8.TEST_CASES) {
        String expected = null;
        if (testCase.invalidIndex == -1) {
            expected = testCase.outputReplaced;
        }
        doUtf8BodyTest(testCase.description, testCase.input, expected);
    }
}
 
Example 12
Project: tomcat7   File: TestAsyncContextImpl.java   View source code 6 votes vote down vote up
@Test
public void testTimeoutDispatchCustomErrorPage() throws Exception {
    Tomcat tomcat = getTomcatInstance();
    Context context = tomcat.addContext("", null);
    tomcat.addServlet("", "timeout", Bug58751AsyncServlet.class.getName())
            .setAsyncSupported(true);
    CustomErrorServlet customErrorServlet = new CustomErrorServlet();
    Tomcat.addServlet(context, "customErrorServlet", customErrorServlet);
    context.addServletMapping("/timeout", "timeout");
    context.addServletMapping("/error", "customErrorServlet");
    ErrorPage errorPage = new ErrorPage();
    errorPage.setLocation("/error");
    context.addErrorPage(errorPage);
    tomcat.start();

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

    Assert.assertEquals(503, rc);
    Assert.assertEquals(CustomErrorServlet.ERROR_MESSAGE, responseBody.toString());
}
 
Example 13
Project: lams   File: HTMLManagerServlet.java   View source code 6 votes vote down vote up
protected Session[] getSessionsForPath(String path) {
    if ((path == null) || (!path.startsWith("/") && path.equals(""))) {
        throw new IllegalArgumentException(sm.getString("managerServlet.invalidPath",
                                    RequestUtil.filter(path)));
    }
    String displayPath = path;
    if( path.equals("/") )
        path = "";
    Context context = (Context) host.findChild(path);
    if (null == context) {
        throw new IllegalArgumentException(sm.getString("managerServlet.noContext",
                                    RequestUtil.filter(displayPath)));
    }
    Session[] sessions = context.getManager().findSessions();
    return sessions;
}
 
Example 14
Project: apache-tomcat-7.0.73-with-comment   File: TestTomcat.java   View source code 6 votes vote down vote up
/**
 * Test for https://bz.apache.org/bugzilla/show_bug.cgi?id=47866
 */
@Test
public void testGetResource() throws Exception {
    Tomcat tomcat = getTomcatInstance();

    String contextPath = "/examples";

    File appDir = new File(getBuildDirectory(), "webapps" + contextPath);
    // app dir is relative to server home
    Context ctx =
        tomcat.addWebapp(null, "/examples", appDir.getAbsolutePath());

    Tomcat.addServlet(ctx, "testGetResource", new GetResource());
    ctx.addServletMapping("/testGetResource", "testGetResource");

    tomcat.start();

    ByteChunk res = new ByteChunk();

    int rc =getUrl("http://localhost:" + getPort() + contextPath +
            "/testGetResource", res, null);
    assertEquals(HttpServletResponse.SC_OK, rc);
    assertTrue(res.toString().contains("<?xml version=\"1.0\" "));
}
 
Example 15
Project: apache-tomcat-7.0.73-with-comment   File: StandardHostValve.java   View source code 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 16
Project: tomcat7   File: TestContextConfig.java   View source code 6 votes vote down vote up
@Test
public void testBug54448and54450() throws Exception {
    Tomcat tomcat = getTomcatInstance();

    File appDir = new File("test/webapp-3.0-fragments");
    Context context = tomcat.addWebapp(null, "/test",
            appDir.getAbsolutePath());

    Tomcat.addServlet(context, "TestServlet",
            "org.apache.catalina.startup.TesterServletWithAnnotations");
    context.addServletMapping("/testServlet", "TestServlet");

    tomcat.enableNaming();

    tomcat.start();

    assertPageContains("/test/testServlet",
            "envEntry1: 1 envEntry2: 2 envEntry3: 33 envEntry4: 4 envEntry5: 55 envEntry6: 66");
}
 
Example 17
Project: apache-tomcat-7.0.73-with-comment   File: TestContextConfig.java   View source code 6 votes vote down vote up
@Test
public void testBug54379() throws Exception {
    Tomcat tomcat = getTomcatInstance();

    File appDir = new File("test/webapp-3.0-fragments");
    Context context =
            tomcat.addWebapp(null, "/test", appDir.getAbsolutePath());

    Tomcat.addServlet(context, "TestServlet",
            "org.apache.catalina.startup.TesterServletWithLifeCycleMethods");
    context.addServletMapping("/testServlet", "TestServlet");

    tomcat.enableNaming();

    tomcat.start();

    assertPageContains("/test/testServlet", "postConstruct1()");
}
 
Example 18
Project: jerrydog   File: PersistentManagerBase.java   View source code 6 votes vote down vote up
/**
 * Process property change events from our associated Context.
 *
 * @param event The property change event that has occurred
 */
public void propertyChange(PropertyChangeEvent event) {

    // Validate the source of this event
    if (!(event.getSource() instanceof Context))
        return;
    Context context = (Context) event.getSource();

    // Process a relevant property change
    if (event.getPropertyName().equals("sessionTimeout")) {
        try {
            setMaxInactiveInterval
                ( ((Integer) event.getNewValue()).intValue()*60 );
        } catch (NumberFormatException e) {
            log(sm.getString("standardManager.sessionTimeout",
                             event.getNewValue().toString()));
        }
    }

}
 
Example 19
Project: tomcat7   File: ManagerBase.java   View source code 6 votes vote down vote up
@Override
public String getObjectNameKeyProperties() {
    
    StringBuilder name = new StringBuilder("type=Manager");
    
    if (container instanceof Context) {
        name.append(",context=");
        String contextName = container.getName();
        if (!contextName.startsWith("/")) {
            name.append('/');
        }
        name.append(contextName);
        
        Context context = (Context) container;
        name.append(",host=");
        name.append(context.getParent().getName());
    } else {
        // Unlikely / impossible? Handle it to be safe
        name.append(",container=");
        name.append(container.getName());
    }

    return name.toString();
}
 
Example 20
Project: tomcat7   File: TestJNDIRealm.java   View source code 6 votes vote down vote up
private JNDIRealm buildRealm(String password, String digest) throws javax.naming.NamingException,
        NoSuchFieldException, IllegalAccessException, LifecycleException {
    Context context = new TesterContext();
    JNDIRealm realm = new JNDIRealm();
    realm.setContainer(context);
    realm.setUserSearch("");
    realm.setDigest(digest);

    Field field = JNDIRealm.class.getDeclaredField("context");
    field.setAccessible(true);
    field.set(realm, mockDirContext(mockSearchResults(password)));

    realm.start();

    return realm;
}
 
Example 21
Project: tomcat7   File: TestWsWebSocketContainer.java   View source code 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 22
Project: tomcat7   File: MapperListener.java   View source code 6 votes vote down vote up
/**
 * Register host.
 */
private void registerHost(Host host) {

    String[] aliases = host.findAliases();
    mapper.addHost(host.getName(), aliases, host);

    for (Container container : host.findChildren()) {
        if (container.getState().isAvailable()) {
            registerContext((Context) container);
        }
    }
    if(log.isDebugEnabled()) {
        log.debug(sm.getString("mapperListener.registerHost",
                host.getName(), domain, connector));
    }
}
 
Example 23
Project: apache-tomcat-7.0.73-with-comment   File: TestStandardContext.java   View source code 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.addURLPattern("*");
    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.addServletMapping("/", "Bug46243");
}
 
Example 24
Project: tomcat7   File: TestSSOnonLoginAndDigestAuthenticator.java   View source code 6 votes vote down vote up
private void setUpDigest(Tomcat tomcat) throws Exception {

        // No file system docBase required
        Context ctxt = tomcat.addContext(CONTEXT_PATH_DIGEST, null);
        ctxt.setSessionTimeout(SHORT_TIMEOUT_SECS);

        // Add protected servlet
        Tomcat.addServlet(ctxt, "TesterServlet3", new TesterServlet());
        ctxt.addServletMapping(URI_PROTECTED, "TesterServlet3");
        SecurityCollection collection = new SecurityCollection();
        collection.addPattern(URI_PROTECTED);
        SecurityConstraint sc = new SecurityConstraint();
        sc.addAuthRole(ROLE);
        sc.addCollection(collection);
        ctxt.addConstraint(sc);

        // Configure the appropriate authenticator
        LoginConfig lc = new LoginConfig();
        lc.setAuthMethod("DIGEST");
        ctxt.setLoginConfig(lc);
        ctxt.getPipeline().addValve(new DigestAuthenticator());
    }
 
Example 25
Project: apache-tomcat-7.0.73-with-comment   File: WebappLoader.java   View source code 6 votes vote down vote up
@Override
protected String getObjectNameKeyProperties() {

    StringBuilder name = new StringBuilder("type=Loader");

    if (container instanceof Context) {
        name.append(",context=");
        Context context = (Context) container;

        String contextName = context.getName();
        if (!contextName.startsWith("/")) {
            name.append("/");
        }
        name.append(contextName);

        name.append(",host=");
        name.append(context.getParent().getName());
    } else {
        // Unlikely / impossible? Handle it to be safe
        name.append(",container=");
        name.append(container.getName());
    }

    return name.toString();
}
 
Example 26
Project: apache-tomcat-7.0.73-with-comment   File: CometConnectionManagerValve.java   View source code 5 votes vote down vote up
/**
 * Start this component and implement the requirements
 * of {@link org.apache.catalina.util.LifecycleBase#startInternal()}.
 *
 * @exception LifecycleException if this component detects a fatal error
 *  that prevents this component from being used
 */
@Override
protected synchronized void startInternal() throws LifecycleException {

    if (container instanceof Context) {
        container.addLifecycleListener(this);
    }

    setState(LifecycleState.STARTING);
}
 
Example 27
Project: lams   File: WebRuleSet.java   View source code 5 votes vote down vote up
public void begin(String namespace, String name, Attributes attributes)
    throws Exception {
    Context context = (Context) digester.peek(digester.getCount() - 1);
    String value = attributes.getValue("metadata-complete");
    if ("true".equals(value)) {
        context.setIgnoreAnnotations(true);
    }
    if (digester.getLogger().isDebugEnabled()) {
        digester.getLogger().debug
            (context.getClass().getName() + ".setIgnoreAnnotations( " +
                context.getIgnoreAnnotations() + ")");
    }
}
 
Example 28
Project: micrometer   File: TomcatMetricsConfiguration.java   View source code 5 votes vote down vote up
private Manager getManagerFromContainer(TomcatEmbeddedServletContainer servletContainer) {
    for (Container container : servletContainer.getTomcat().getHost().findChildren()) {
        if (container instanceof Context) {
            return ((Context) container).getManager();
        }
    }
    return null;
}
 
Example 29
Project: apache-tomcat-7.0.73-with-comment   File: MapperListener.java   View source code 5 votes vote down vote up
/**
 * Unregister context.
 */
private void unregisterContext(Context context) {

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

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

    if (context.getPaused()) {
        if (log.isDebugEnabled()) {
            log.debug(sm.getString("mapperListener.pauseContext",
                    contextPath, connector));
        }

        mapper.pauseContextVersion(context, hostName, contextPath,
                context.getWebappVersion());
    } else {
        if (log.isDebugEnabled()) {
            log.debug(sm.getString("mapperListener.unregisterContext",
                    contextPath, connector));
        }

        mapper.removeContextVersion(hostName, contextPath,
                context.getWebappVersion());
    }
}
 
Example 30
Project: tomcat7   File: TestWebSocket.java   View source code 5 votes vote down vote up
@Test
public void testNoConnection() throws Exception {
    Tomcat tomcat = getTomcatInstance();
    // No file system docBase required
    Context ctx = tomcat.addContext("", null);
    ctx.addApplicationListener(new ApplicationListener(
            TesterEchoServer.Config.class.getName(), false));

    Tomcat.addServlet(ctx, "default", new DefaultServlet());
    ctx.addServletMapping("/", "default");

    tomcat.start();

    WebSocketClient client= new WebSocketClient(getPort());

    // Send the WebSocket handshake
    client.writer.write("GET " + TesterEchoServer.Config.PATH_BASIC + " HTTP/1.1" + CRLF);
    client.writer.write("Host: foo" + CRLF);
    client.writer.write("Upgrade: websocket" + CRLF);
    client.writer.write("Sec-WebSocket-Version: 13" + CRLF);
    client.writer.write("Sec-WebSocket-Key: TODO" + CRLF);
    client.writer.write(CRLF);
    client.writer.flush();

    // Make sure we got an error response
    String responseLine = client.reader.readLine();
    assertTrue(responseLine.startsWith("HTTP/1.1 400"));

    // Finished with the socket
    client.close();
}
 
Example 31
Project: apache-tomcat-7.0.73-with-comment   File: TestTomcat.java   View source code 5 votes vote down vote up
/**
 * Test for enabling JNDI.
 */
@Test
public void testEnableNaming() throws Exception {
    Tomcat tomcat = getTomcatInstance();

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

    // You can customise the context by calling its API

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

    ContextEnvironment environment = new ContextEnvironment();
    environment.setType("java.lang.String");
    environment.setName(HelloWorldJndi.JNDI_ENV_NAME);
    environment.setValue("Tomcat User");
    ctx.getNamingResources().addEnvironment(environment);

    Tomcat.addServlet(ctx, "jndiServlet", new HelloWorldJndi());
    ctx.addServletMapping("/", "jndiServlet");

    tomcat.start();

    ByteChunk res = getUrl("http://localhost:" + getPort() + "/");
    assertEquals("Hello, Tomcat User", res.toString());
}
 
Example 32
Project: tomcat7   File: ReplicationValve.java   View source code 5 votes vote down vote up
/**
 * Log the interesting request parameters, invoke the next Valve in the
 * sequence, and log the interesting response parameters.
 *
 * @param request The servlet request to be processed
 * @param response The servlet response to be created
 *
 * @exception IOException if an input/output error occurs
 * @exception ServletException if a servlet error occurs
 */
@Override
public void invoke(Request request, Response response)
    throws IOException, ServletException
{
    long totalstart = 0;

    //this happens before the request
    if(doStatistics()) {
        totalstart = System.currentTimeMillis();
    }
    if (primaryIndicator) {
        createPrimaryIndicator(request) ;
    }
    Context context = request.getContext();
    boolean isCrossContext = context != null
            && context instanceof StandardContext
            && ((StandardContext) context).getCrossContext();
    try {
        if(isCrossContext) {
            if(log.isDebugEnabled())
                log.debug(sm.getString("ReplicationValve.crossContext.add"));
            //FIXME add Pool of Arraylists
            crossContextSessions.set(new ArrayList<DeltaSession>());
        }
        getNext().invoke(request, response);
        if(context != null && cluster != null
                && context.getManager() instanceof ClusterManager) {
            ClusterManager clusterManager = (ClusterManager) context.getManager();

            // valve cluster can access manager - other cluster handle replication 
            // at host level - hopefully!
            if(cluster.getManager(clusterManager.getName()) == null)
                return ;
            if(cluster.hasMembers()) {
                sendReplicationMessage(request, totalstart, isCrossContext, clusterManager, cluster);
            } else {
                resetReplicationRequest(request,isCrossContext);
            }        
        }
    } finally {
        // Array must be remove: Current master request send endAccess at recycle. 
        // Don't register this request session again!
        if(isCrossContext) {
            if(log.isDebugEnabled())
                log.debug(sm.getString("ReplicationValve.crossContext.remove"));
            // crossContextSessions.remove() only exist at Java 5
            // register ArrayList at a pool
            crossContextSessions.set(null);
        }
    }
}
 
Example 33
Project: apache-tomcat-7.0.73-with-comment   File: TestAsyncContextImpl.java   View source code 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.addServletMapping("/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);

    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 34
Project: apache-tomcat-7.0.73-with-comment   File: ThreadLocalLeakPreventionListener.java   View source code 5 votes vote down vote up
/**
 * Updates each ThreadPoolExecutor with the current time, which is the time
 * when a context is being stopped.
 * 
 * @param context
 *            the context being stopped, used to discover all the Connectors
 *            of its parent Service.
 */
private void stopIdleThreads(Context context) {
    if (serverStopping) return;

    if (!(context instanceof StandardContext) ||
        !((StandardContext) context).getRenewThreadsWhenStoppingContext()) {
        log.debug("Not renewing threads when the context is stopping. "
            + "It is not configured to do it.");
        return;
    }

    Engine engine = (Engine) context.getParent().getParent();
    Service service = engine.getService();
    Connector[] connectors = service.findConnectors();
    if (connectors != null) {
        for (Connector connector : connectors) {
            ProtocolHandler handler = connector.getProtocolHandler();
            Executor executor = null;
            if (handler != null) {
                executor = handler.getExecutor();
            }

            if (executor instanceof ThreadPoolExecutor) {
                ThreadPoolExecutor threadPoolExecutor =
                    (ThreadPoolExecutor) executor;
                threadPoolExecutor.contextStopping();
            } else if (executor instanceof StandardThreadExecutor) {
                StandardThreadExecutor stdThreadExecutor =
                    (StandardThreadExecutor) executor;
                stdThreadExecutor.contextStopping();
            }

        }
    }
}
 
Example 35
Project: apache-tomcat-7.0.73-with-comment   File: TestClose.java   View source code 5 votes vote down vote up
private Tomcat startServer(
        final Class<? extends WsContextListener> configClass)
        throws LifecycleException {

    Tomcat tomcat = getTomcatInstance();
    // No file system docBase required
    Context ctx = tomcat.addContext("", null);
    ctx.addApplicationListener(configClass.getName());
    Tomcat.addServlet(ctx, "default", new DefaultServlet());
    ctx.addServletMapping("/", "default");

    tomcat.start();
    return tomcat;
}
 
Example 36
Project: tomcat7   File: TestKeepAliveCount.java   View source code 5 votes vote down vote up
private synchronized void init() {
    if (init) return;

    Tomcat tomcat = getTomcatInstance();
    // No file system docBase required
    Context root = tomcat.addContext("", null);
    Tomcat.addServlet(root, "Simple", new SimpleServlet());
    root.addServletMapping("/test", "Simple");
    tomcat.getConnector().setProperty("maxKeepAliveRequests", "5");
    tomcat.getConnector().setProperty("soTimeout", "20000");
    tomcat.getConnector().setProperty("keepAliveTimeout", "50000");
    init = true;
}
 
Example 37
Project: tomcat7   File: TestEncodingDecoding.java   View source code 5 votes vote down vote up
@Test
public void testUnsupportedObject() throws Exception{
    Tomcat tomcat = getTomcatInstance();
    // No file system docBase required
    Context ctx = tomcat.addContext("", null);
    ctx.addApplicationListener(ProgramaticServerEndpointConfig.class.getName());
    Tomcat.addServlet(ctx, "default", new DefaultServlet());
    ctx.addServletMapping("/", "default");

    WebSocketContainer wsContainer = ContainerProvider.getWebSocketContainer();

    tomcat.start();

    Client client = new Client();
    URI uri = new URI("ws://localhost:" + getPort() + PATH_PROGRAMMATIC_EP);
    Session session = wsContainer.connectToServer(client, uri);

    // This should fail
    Object msg1 = new Object();
    try {
        session.getBasicRemote().sendObject(msg1);
        Assert.fail("No exception thrown ");
    } catch (EncodeException e) {
        // Expected
    } catch (Throwable t) {
        Assert.fail("Wrong exception type");
    } finally {
        session.close();
    }
}
 
Example 38
Project: tomcat7   File: ManagerServlet.java   View source code 5 votes vote down vote up
/**
 * List the resources of the given context.
 */
protected void printResources(PrintWriter writer, String prefix,
                              javax.naming.Context namingContext,
                              String type, Class<?> clazz,
                              StringManager smClient) {

    try {
        NamingEnumeration<Binding> items = namingContext.listBindings("");
        while (items.hasMore()) {
            Binding item = items.next();
            if (item.getObject() instanceof javax.naming.Context) {
                printResources
                    (writer, prefix + item.getName() + "/",
                     (javax.naming.Context) item.getObject(), type, clazz,
                     smClient);
            } else {
                if ((clazz != null) &&
                    (!(clazz.isInstance(item.getObject())))) {
                    continue;
                }
                writer.print(prefix + item.getName());
                writer.print(':');
                writer.print(item.getClassName());
                // Do we want a description if available?
                writer.println();
            }
        }
    } catch (Throwable t) {
        ExceptionUtils.handleThrowable(t);
        log("ManagerServlet.resources[" + type + "]", t);
        writer.println(smClient.getString("managerServlet.exception",
                t.toString()));
    }

}
 
Example 39
Project: dubbocloud   File: TomcatHttpServer.java   View source code 5 votes vote down vote up
public TomcatHttpServer(URL url, final HttpHandler handler) {
        super(url, handler);

        this.url = url;
        DispatcherServlet.addHttpHandler(url.getPort(), handler);
        String baseDir = new File(System.getProperty("java.io.tmpdir")).getAbsolutePath();
        tomcat = new Tomcat();
        tomcat.setBaseDir(baseDir);
        tomcat.setPort(url.getPort());
        tomcat.getConnector().setProperty(
                "maxThreads", String.valueOf(url.getParameter(Constants.THREADS_KEY, Constants.DEFAULT_THREADS)));
//        tomcat.getConnector().setProperty(
//                "minSpareThreads", String.valueOf(url.getParameter(Constants.THREADS_KEY, Constants.DEFAULT_THREADS)));

        tomcat.getConnector().setProperty(
                "maxConnections", String.valueOf(url.getParameter(Constants.ACCEPTS_KEY, -1)));

        tomcat.getConnector().setProperty("URIEncoding", "UTF-8");
        tomcat.getConnector().setProperty("connectionTimeout", "60000");

        tomcat.getConnector().setProperty("maxKeepAliveRequests", "-1");
        tomcat.getConnector().setProtocol("org.apache.coyote.http11.Http11NioProtocol");

        Context context = tomcat.addContext("/", baseDir);
        Tomcat.addServlet(context, "dispatcher", new DispatcherServlet());
        context.addServletMapping("/*", "dispatcher");
        ServletManager.getInstance().addServletContext(url.getPort(), context.getServletContext());

        try {
            tomcat.start();
        } catch (LifecycleException e) {
            throw new IllegalStateException("Failed to start tomcat server at " + url.getAddress(), e);
        }
    }
 
Example 40
Project: tomcat7   File: Embedded.java   View source code 5 votes vote down vote up
/**
 * Remove the specified Context from the set of defined Contexts for its
 * associated Host.  If this is the last Context for this Host, the Host
 * will also be removed.
 *
 * @param context The Context to be removed
 */
public synchronized void removeContext(Context context) {

    if( log.isDebugEnabled() )
        log.debug("Removing context[" + context.getName() + "]");

    // Is this Context actually among those that are defined?
    boolean found = false;
    for (int i = 0; i < engines.length; i++) {
        Container hosts[] = engines[i].findChildren();
        for (int j = 0; j < hosts.length; j++) {
            Container contexts[] = hosts[j].findChildren();
            for (int k = 0; k < contexts.length; k++) {
                if (context == (Context) contexts[k]) {
                    found = true;
                    break;
                }
            }
            if (found)
                break;
        }
        if (found)
            break;
    }
    if (!found)
        return;

    // Remove this Context from the associated Host
    if( log.isDebugEnabled() )
        log.debug(" Removing this Context");
    context.getParent().removeChild(context);

}