javax.servlet.http.HttpSessionAttributeListener#org.apache.catalina.Context源码实例Demo

下面列出了javax.servlet.http.HttpSessionAttributeListener#org.apache.catalina.Context 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

@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();
    }
}
 
源代码2 项目: Tomcat7.0.67   文件: TestResponse.java
/**
 * 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());
}
 
源代码3 项目: Tomcat7.0.67   文件: TestWsWebSocketContainer.java
@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));
}
 
源代码4 项目: tomcatsrc   文件: StandardHostValve.java
/**
 * 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);

}
 
源代码5 项目: tomcatsrc   文件: ManagerServlet.java
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));
    }
}
 
源代码6 项目: glowroot   文件: InvokeJaxwsWebServiceInTomcat.java
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();
}
 
源代码7 项目: tomcatsrc   文件: Tomcat.java
@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;
    }
}
 
源代码8 项目: tomcatsrc   文件: TestRequest.java
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);
}
 
@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()));
}
 
源代码10 项目: tomee   文件: OpenEJBContextConfig.java
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;
}
 
源代码11 项目: Tomcat7.0.67   文件: SetNextNamingRule.java
/**
 * 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());

}
 
源代码12 项目: Tomcat8-Source-Read   文件: TestStandardContext.java
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");
}
 
@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());
}
 
源代码14 项目: Tomcat8-Source-Read   文件: MBeanFactory.java
/**
 * 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();

}
 
源代码15 项目: tomcatsrc   文件: UserConfig.java
/**
 * Deploy a web application for the specified user if they have such an
 * application in the defined directory within their home directory.
 *
 * @param user Username owning the application to be deployed
 * @param home Home directory of this user
 */
private void deploy(String user, String home) {

    // Does this user have a web application to be deployed?
    String contextPath = "/~" + user;
    if (host.findChild(contextPath) != null)
        return;
    File app = new File(home, directoryName);
    if (!app.exists() || !app.isDirectory())
        return;
    /*
    File dd = new File(app, "/WEB-INF/web.xml");
    if (!dd.exists() || !dd.isFile() || !dd.canRead())
        return;
    */
    host.getLogger().info(sm.getString("userConfig.deploy", user));

    // Deploy the web application for this user
    try {
        Class<?> clazz = Class.forName(contextClass);
        Context context =
          (Context) clazz.newInstance();
        context.setPath(contextPath);
        context.setDocBase(app.toString());
        clazz = Class.forName(configClass);
        LifecycleListener listener =
            (LifecycleListener) clazz.newInstance();
        context.addLifecycleListener(listener);
        host.addChild(context);
    } catch (Exception e) {
        host.getLogger().error(sm.getString("userConfig.error", user), e);
    }

}
 
源代码16 项目: Tomcat8-Source-Read   文件: TestStandardWrapper.java
private void doTestSecurityAnnotationsAddServlet(boolean useCreateServlet)
        throws Exception {

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

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

    Servlet s = new DenyAllServlet();
    ServletContainerInitializer sci = new SCI(s, useCreateServlet);
    ctx.addServletContainerInitializer(sci, null);

    tomcat.start();

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

    if (useCreateServlet) {
        Assert.assertTrue(bc.getLength() > 0);
        Assert.assertEquals(403, rc);
    } else {
        Assert.assertEquals("OK", bc.toString());
        Assert.assertEquals(200, rc);
    }
}
 
源代码17 项目: Tomcat7.0.67   文件: MBeanUtils.java
/**
 * Calculate the key properties string to be added to an object's
 * {@link ObjectName} to indicate that it is associated with that container.
 * 
 * @param container The container the object is associated with 
 * @return          A string suitable for appending to the ObjectName
 * @deprecated  To be removed since to creates a circular dependency. Will
 *              be replaced in Tomcat 8 by a new method on {@link
 *              Container}.
 */
@Deprecated
public static String getContainerKeyProperties(Container container) {
    
    Container c = container;
    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.append(",servlet=");
            keyProperties.append(c.getName());
        } else if (c instanceof Context) {
            keyProperties.append(",context=");
            ContextName cn = new ContextName(c.getName(), false);
            keyProperties.append(cn.getDisplayName());
        } else if (c instanceof Host) {
            keyProperties.append(",host=");
            keyProperties.append(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();
}
 
源代码18 项目: Tomcat8-Source-Read   文件: AuthenticatorBase.java
/**
 * Set the Container to which this Valve is attached.
 *
 * @param container
 *            The container to which we are attached
 */
@Override
public void setContainer(Container container) {

    if (container != null && !(container instanceof Context)) {
        throw new IllegalArgumentException(sm.getString("authenticator.notContext"));
    }

    super.setContainer(container);
    this.context = (Context) container;

}
 
源代码19 项目: Tomcat7.0.67   文件: CometConnectionManagerValve.java
/**
 * Stop this component and implement the requirements
 * of {@link org.apache.catalina.util.LifecycleBase#stopInternal()}.
 *
 * @exception LifecycleException if this component detects a fatal error
 *  that prevents this component from being used
 */
@Override
protected synchronized void stopInternal() throws LifecycleException {

    setState(LifecycleState.STOPPING);

    if (container instanceof Context) {
        container.removeLifecycleListener(this);
    }
}
 
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);
    }

}
 
源代码21 项目: tomcatsrc   文件: TestWebSocket.java
@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();
}
 
源代码22 项目: Tomcat8-Source-Read   文件: Tomcat.java
/**
 * Static version of {@link #addServlet(String, String, Servlet)}.
 * @param ctx           Context to add Servlet to
 * @param servletName   Servlet name (used in mappings)
 * @param servlet       The Servlet to add
 * @return The wrapper for the servlet
 */
public static Wrapper addServlet(Context ctx,
                                  String servletName,
                                  Servlet servlet) {
    // will do class for name and set init params
    Wrapper sw = new ExistingStandardWrapper(servlet);
    sw.setName(servletName);
    ctx.addChild(sw);

    return sw;
}
 
源代码23 项目: oxygen   文件: FatJarWebXmlListener.java
private void createWebResource(Context context, WebResourceRoot resources, String path) {
  log.info(String.format("create web resources for [%s]", path));
  URL resource = context.getParentClassLoader().getResource(path);
  if (resource != null) {
    String webXmlUrlString = resource.toString();
    try {
      URL root = new URL(webXmlUrlString.substring(0, webXmlUrlString.length() - path.length()));
      String webPath = Strings.SLASH + path;
      resources.createWebResourceSet(ResourceSetType.RESOURCE_JAR, webPath, root, webPath);
    } catch (MalformedURLException e) {
      // ignore
    }
  }
}
 
源代码24 项目: Tomcat8-Source-Read   文件: AsyncContextImpl.java
public boolean timeout() {
    AtomicBoolean result = new AtomicBoolean();
    request.getCoyoteRequest().action(ActionCode.ASYNC_TIMEOUT, result);
    // Avoids NPEs during shutdown. A call to recycle will null this field.
    Context context = this.context;

    if (result.get()) {
        if (log.isDebugEnabled()) {
            log.debug(sm.getString("asyncContextImpl.fireOnTimeout"));
        }
        ClassLoader oldCL = context.bind(false, null);
        try {
            List<AsyncListenerWrapper> listenersCopy = new ArrayList<>();
            listenersCopy.addAll(listeners);
            for (AsyncListenerWrapper listener : listenersCopy) {
                try {
                    listener.fireOnTimeout(event);
                } catch (Throwable t) {
                    ExceptionUtils.handleThrowable(t);
                    log.warn(sm.getString("asyncContextImpl.onTimeoutError",
                            listener.getClass().getName()), t);
                }
            }
            request.getCoyoteRequest().action(
                    ActionCode.ASYNC_IS_TIMINGOUT, result);
        } finally {
            context.unbind(false, oldCL);
        }
    }
    return !result.get();
}
 
源代码25 项目: tomcatsrc   文件: NamingResources.java
/**
 * Checks that the configuration of the type for the specified resource is
 * consistent with any injection targets and if the type is not specified,
 * tries to configure the type based on the injection targets
 *
 * @param resource  The resource to check
 *
 * @return  <code>true</code> if the type for the resource is now valid (if
 *          previously <code>null</code> this means it is now set) or
 *          <code>false</code> if the current resource type is inconsistent
 *          with the injection targets and/or cannot be determined
 */
private boolean checkResourceType(ResourceBase resource) {
    if (!(container instanceof Context)) {
        // Only Context's will have injection targets
        return true;
    }

    if (resource.getInjectionTargets() == null ||
            resource.getInjectionTargets().size() == 0) {
        // No injection targets so use the defined type for the resource
        return true;
    }

    Context context = (Context) container;

    String typeName = resource.getType();
    Class<?> typeClass = null;
    if (typeName != null) {
        typeClass = Introspection.loadClass(context, typeName);
        if (typeClass == null) {
            // Can't load the type - will trigger a failure later so don't
            // fail here
            return true;
        }
    }

    Class<?> compatibleClass =
            getCompatibleType(context, resource, typeClass);
    if (compatibleClass == null) {
        // Indicates that a compatible type could not be identified that
        // worked for all injection targets
        return false;
    }

    resource.setType(compatibleClass.getCanonicalName());
    return true;
}
 
源代码26 项目: Tomcat7.0.67   文件: TestCoyoteAdapter.java
private void pathParamTest(String path, String expected) throws Exception {
    // Setup Tomcat instance
    Tomcat tomcat = getTomcatInstance();

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

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

    tomcat.start();

    ByteChunk res = getUrl("http://localhost:" + getPort() + path);
    Assert.assertEquals(expected, res.toString());
}
 
源代码27 项目: Tomcat8-Source-Read   文件: TestTomcat.java
@Test
public void testSession() throws Exception {
    Tomcat tomcat = getTomcatInstance();

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

    Tomcat.addServlet(ctx, "myServlet", new HelloWorldSession());
    ctx.addServletMappingDecoded("/", "myServlet");

    tomcat.start();

    ByteChunk res = getUrl("http://localhost:" + getPort() + "/");
    Assert.assertEquals("Hello world", res.toString());
}
 
源代码28 项目: tomcatsrc   文件: TestRequest.java
@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);
}
 
源代码29 项目: tomee   文件: LowTypedRealm.java
@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()]);
}
 
/**
 * 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);
    }
}