Java Code Examples for org.apache.catalina.Context#getServletContext()

The following examples show how to use org.apache.catalina.Context#getServletContext() . 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: Request.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
/**
 * @return the real path of the specified virtual path.
 *
 * @param path Path to be translated
 *
 * @deprecated As of version 2.1 of the Java Servlet API, use
 *  <code>ServletContext.getRealPath()</code>.
 */
@Override
@Deprecated
public String getRealPath(String path) {

    Context context = getContext();
    if (context == null) {
        return null;
    }
    ServletContext servletContext = context.getServletContext();
    if (servletContext == null) {
        return null;
    }

    try {
        return servletContext.getRealPath(path);
    } catch (IllegalArgumentException e) {
        return null;
    }
}
 
Example 2
Source File: Request.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
/**
 * Notify interested listeners that attribute has been removed.
 *
 * @param name Attribute name
 * @param value Attribute value
 */
private void notifyAttributeRemoved(String name, Object value) {
    Context context = getContext();
    Object listeners[] = context.getApplicationEventListeners();
    if ((listeners == null) || (listeners.length == 0)) {
        return;
    }
    ServletRequestAttributeEvent event =
            new ServletRequestAttributeEvent(context.getServletContext(),
                    getRequest(), name, value);
    for (int i = 0; i < listeners.length; i++) {
        if (!(listeners[i] instanceof ServletRequestAttributeListener)) {
            continue;
        }
        ServletRequestAttributeListener listener =
                (ServletRequestAttributeListener) listeners[i];
        try {
            listener.attributeRemoved(event);
        } catch (Throwable t) {
            ExceptionUtils.handleThrowable(t);
            // Error valve will pick this exception up and display it to user
            attributes.put(RequestDispatcher.ERROR_EXCEPTION, t);
            context.getLogger().error(sm.getString("coyoteRequest.attributeEvent"), t);
        }
    }
}
 
Example 3
Source File: WebappServiceLoader.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
/**
 * Construct a loader to load services from a ServletContext.
 *
 * @param context the context to use
 */
public WebappServiceLoader(Context context) {
    this.context = context;
    this.servletContext = context.getServletContext();
    String containerSciFilter = context.getContainerSciFilter();
    if (containerSciFilter != null && containerSciFilter.length() > 0) {
        containerSciFilterPattern = Pattern.compile(containerSciFilter);
    } else {
        containerSciFilterPattern = null;
    }
}
 
Example 4
Source File: StandardSession.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
/**
 * Return the ServletContext to which this session belongs.
 */
@Override
public ServletContext getServletContext() {
    if (manager == null) {
        return null;
    }
    Context context = manager.getContext();
    return context.getServletContext();
}
 
Example 5
Source File: TestTldScanner.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@Test
public void testWithWebapp() throws Exception {
    Tomcat tomcat = getTomcatInstance();
    File appDir = new File("test/webapp-3.0");
    Context context = tomcat.addWebapp(null, "/test", appDir.getAbsolutePath());
    tomcat.start();

    TldScanner scanner =
            new TldScanner(context.getServletContext(), true, true, true);
    scanner.scan();
    Assert.assertEquals(5, scanner.getUriTldResourcePathMap().size());
    Assert.assertEquals(1, scanner.getListeners().size());
}
 
Example 6
Source File: WebappServiceLoader.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
/**
 * Construct a loader to load services from a ServletContext.
 *
 * @param context the context to use
 */
public WebappServiceLoader(Context context) {
    this.context = context;
    this.servletContext = context.getServletContext();
    String containerSciFilter = context.getContainerSciFilter();
    if (containerSciFilter != null && containerSciFilter.length() > 0) {
        containerSciFilterPattern = Pattern.compile(containerSciFilter);
    } else {
        containerSciFilterPattern = null;
    }
}
 
Example 7
Source File: StandardSession.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
/**
 * Return the ServletContext to which this session belongs.
 */
@Override
public ServletContext getServletContext() {

    if (manager == null)
        return (null);
    Context context = (Context) manager.getContainer();
    if (context == null)
        return (null);
    else
        return (context.getServletContext());

}
 
Example 8
Source File: TestTagPluginManager.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
@Test
public void testBug54240() throws Exception {
    Tomcat tomcat = getTomcatInstance();

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

    ServletContext context = ctx.getServletContext();

    TagPluginManager manager = new TagPluginManager(context);

    Node.Nodes nodes = new Node.Nodes();
    Node.CustomTag c = new Node.CustomTag("test:ATag", "test", "ATag",
            "http://tomcat.apache.org/jasper", null, null, null, null, null,
            new TagFileInfo("ATag", "http://tomcat.apache.org/jasper",
                    tagInfo));
    c.setTagHandlerClass(TesterTag.class);
    nodes.add(c);
    manager.apply(nodes, null, null);

    Node n = nodes.getNode(0);
    Assert.assertNotNull(n);
    Assert.assertTrue(n instanceof Node.CustomTag);

    Node.CustomTag t = (Node.CustomTag)n;
    Assert.assertNotNull(t.getAtSTag());

    Node.Nodes sTag = c.getAtSTag();
    Node scriptlet = sTag.getNode(0);
    Assert.assertNotNull(scriptlet);
    Assert.assertTrue(scriptlet instanceof Node.Scriptlet);
    Node.Scriptlet s = (Node.Scriptlet)scriptlet;
    Assert.assertEquals("//Just a comment", s.getText());
}
 
Example 9
Source File: WebappServiceLoader.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
/**
 * Construct a loader to load services from a ServletContext.
 *
 * @param context the context to use
 */
public WebappServiceLoader(Context context) {
    this.context = context;
    this.servletContext = context.getServletContext();
    String containerSciFilter = context.getContainerSciFilter();
    if (containerSciFilter != null && containerSciFilter.length() > 0) {
        containerSciFilterPattern = Pattern.compile(containerSciFilter);
    } else {
        containerSciFilterPattern = null;
    }
}
 
Example 10
Source File: StandardSession.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
/**
 * Return the ServletContext to which this session belongs.
 */
@Override
public ServletContext getServletContext() {
    if (manager == null) {
        return null;
    }
    Context context = (Context) manager.getContainer();
    return context.getServletContext();
}
 
Example 11
Source File: TestTagPluginManager.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
@Test
public void testBug54240() throws Exception {
    Tomcat tomcat = getTomcatInstance();

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

    ServletContext context = ctx.getServletContext();

    TagPluginManager manager = new TagPluginManager(context);

    Node.Nodes nodes = new Node.Nodes();
    Node.CustomTag c = new Node.CustomTag("test:ATag", "test", "ATag",
            "http://tomcat.apache.org/jasper", null, null, null, null, null,
            new TagFileInfo("ATag", "http://tomcat.apache.org/jasper",
                    tagInfo));
    c.setTagHandlerClass(TesterTag.class);
    nodes.add(c);
    manager.apply(nodes, null, null);

    Node n = nodes.getNode(0);
    Assert.assertNotNull(n);
    Assert.assertTrue(n instanceof Node.CustomTag);

    Node.CustomTag t = (Node.CustomTag)n;
    Assert.assertNotNull(t.getAtSTag());

    Node.Nodes sTag = c.getAtSTag();
    Node scriptlet = sTag.getNode(0);
    Assert.assertNotNull(scriptlet);
    Assert.assertTrue(scriptlet instanceof Node.Scriptlet);
    Node.Scriptlet s = (Node.Scriptlet)scriptlet;
    Assert.assertEquals("//Just a comment", s.getText());
}
 
Example 12
Source File: TestELInterpreterFactory.java    From Tomcat8-Source-Read with MIT License 4 votes vote down vote up
@Test
public void testBug54239() throws Exception {
    Tomcat tomcat = getTomcatInstance();

    File appDir = new File("test/webapp");
    Context ctx = tomcat.addWebapp(null, "/test", appDir.getAbsolutePath());
    tomcat.start();

    ServletContext context = ctx.getServletContext();

    ELInterpreter interpreter =
            ELInterpreterFactory.getELInterpreter(context);
    Assert.assertNotNull(interpreter);
    Assert.assertTrue(interpreter instanceof DefaultELInterpreter);

    context.removeAttribute(ELInterpreter.class.getName());

    context.setAttribute(ELInterpreter.class.getName(),
            SimpleELInterpreter.class.getName());
    interpreter = ELInterpreterFactory.getELInterpreter(context);
    Assert.assertNotNull(interpreter);
    Assert.assertTrue(interpreter instanceof SimpleELInterpreter);

    context.removeAttribute(ELInterpreter.class.getName());

    SimpleELInterpreter simpleInterpreter = new SimpleELInterpreter();
    context.setAttribute(ELInterpreter.class.getName(), simpleInterpreter);
    interpreter = ELInterpreterFactory.getELInterpreter(context);
    Assert.assertNotNull(interpreter);
    Assert.assertTrue(interpreter instanceof SimpleELInterpreter);
    Assert.assertTrue(interpreter == simpleInterpreter);

    context.removeAttribute(ELInterpreter.class.getName());

    ctx.stop();
    ctx.addApplicationListener(Bug54239Listener.class.getName());
    ctx.start();

    interpreter = ELInterpreterFactory.getELInterpreter(ctx.getServletContext());
    Assert.assertNotNull(interpreter);
    Assert.assertTrue(interpreter instanceof SimpleELInterpreter);
}
 
Example 13
Source File: TestELInterpreterFactory.java    From Tomcat7.0.67 with Apache License 2.0 4 votes vote down vote up
@Test
public void testBug54239() throws Exception {
    Tomcat tomcat = getTomcatInstance();

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

    ServletContext context = ctx.getServletContext();

    ELInterpreter interpreter =
            ELInterpreterFactory.getELInterpreter(context);
    Assert.assertNotNull(interpreter);
    Assert.assertTrue(interpreter instanceof DefaultELInterpreter);

    context.removeAttribute(ELInterpreter.class.getName());

    context.setAttribute(ELInterpreter.class.getName(),
            SimpleELInterpreter.class.getName());
    interpreter = ELInterpreterFactory.getELInterpreter(context);
    Assert.assertNotNull(interpreter);
    Assert.assertTrue(interpreter instanceof SimpleELInterpreter);

    context.removeAttribute(ELInterpreter.class.getName());

    SimpleELInterpreter simpleInterpreter = new SimpleELInterpreter();
    context.setAttribute(ELInterpreter.class.getName(), simpleInterpreter);
    interpreter = ELInterpreterFactory.getELInterpreter(context);
    Assert.assertNotNull(interpreter);
    Assert.assertTrue(interpreter instanceof SimpleELInterpreter);
    Assert.assertTrue(interpreter == simpleInterpreter);

    context.removeAttribute(ELInterpreter.class.getName());

    ctx.stop();
    ctx.addApplicationListener(Bug54239Listener.class.getName());
    ctx.start();

    interpreter = ELInterpreterFactory.getELInterpreter(ctx.getServletContext());
    Assert.assertNotNull(interpreter);
    Assert.assertTrue(interpreter instanceof SimpleELInterpreter);
}
 
Example 14
Source File: TestELInterpreterFactory.java    From tomcatsrc with Apache License 2.0 4 votes vote down vote up
@Test
public void testBug54239() throws Exception {
    Tomcat tomcat = getTomcatInstance();

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

    ServletContext context = ctx.getServletContext();

    ELInterpreter interpreter =
            ELInterpreterFactory.getELInterpreter(context);
    Assert.assertNotNull(interpreter);
    Assert.assertTrue(interpreter instanceof DefaultELInterpreter);

    context.removeAttribute(ELInterpreter.class.getName());

    context.setAttribute(ELInterpreter.class.getName(),
            SimpleELInterpreter.class.getName());
    interpreter = ELInterpreterFactory.getELInterpreter(context);
    Assert.assertNotNull(interpreter);
    Assert.assertTrue(interpreter instanceof SimpleELInterpreter);

    context.removeAttribute(ELInterpreter.class.getName());

    SimpleELInterpreter simpleInterpreter = new SimpleELInterpreter();
    context.setAttribute(ELInterpreter.class.getName(), simpleInterpreter);
    interpreter = ELInterpreterFactory.getELInterpreter(context);
    Assert.assertNotNull(interpreter);
    Assert.assertTrue(interpreter instanceof SimpleELInterpreter);
    Assert.assertTrue(interpreter == simpleInterpreter);

    context.removeAttribute(ELInterpreter.class.getName());

    ctx.stop();
    ctx.addApplicationListener(Bug54239Listener.class.getName());
    ctx.start();

    interpreter = ELInterpreterFactory.getELInterpreter(ctx.getServletContext());
    Assert.assertNotNull(interpreter);
    Assert.assertTrue(interpreter instanceof SimpleELInterpreter);
}
 
Example 15
Source File: InfinispanSessionCacheIdMapperUpdater.java    From keycloak with Apache License 2.0 4 votes vote down vote up
public static SessionIdMapperUpdater addTokenStoreUpdaters(Context context, SessionIdMapper mapper, SessionIdMapperUpdater previousIdMapperUpdater) {
    ServletContext servletContext = context.getServletContext();
    String containerName = servletContext == null ? null : servletContext.getInitParameter(AdapterConstants.REPLICATION_CONFIG_CONTAINER_PARAM_NAME);
    String cacheName = servletContext == null ? null : servletContext.getInitParameter(AdapterConstants.REPLICATION_CONFIG_SSO_CACHE_PARAM_NAME);

    // the following is based on https://github.com/jbossas/jboss-as/blob/7.2.0.Final/clustering/web-infinispan/src/main/java/org/jboss/as/clustering/web/infinispan/DistributedCacheManagerFactory.java#L116-L122
    String host = context.getParent() == null ? "" : context.getParent().getName();
    String contextPath = context.getPath();
    if ("/".equals(contextPath)) {
        contextPath = "/ROOT";
    }
    String deploymentSessionCacheName = host + contextPath;

    if (containerName == null || cacheName == null || deploymentSessionCacheName == null) {
        LOG.warnv("Cannot determine parameters of SSO cache for deployment {0}.", host + contextPath);

        return previousIdMapperUpdater;
    }

    String cacheContainerLookup = DEFAULT_CACHE_CONTAINER_JNDI_NAME + "/" + containerName;

    try {
        EmbeddedCacheManager cacheManager = (EmbeddedCacheManager) new InitialContext().lookup(cacheContainerLookup);

        Configuration ssoCacheConfiguration = cacheManager.getCacheConfiguration(cacheName);
        if (ssoCacheConfiguration == null) {
            Configuration cacheConfiguration = cacheManager.getCacheConfiguration(deploymentSessionCacheName);
            if (cacheConfiguration == null) {
                LOG.debugv("Using default configuration for SSO cache {0}.{1}.", containerName, cacheName);
                ssoCacheConfiguration = cacheManager.getDefaultCacheConfiguration();
            } else {
                LOG.debugv("Using distributed HTTP session cache configuration for SSO cache {0}.{1}, configuration taken from cache {2}",
                  containerName, cacheName, deploymentSessionCacheName);
                ssoCacheConfiguration = cacheConfiguration;
                cacheManager.defineConfiguration(cacheName, ssoCacheConfiguration);
            }
        } else {
            LOG.debugv("Using custom configuration of SSO cache {0}.{1}.", containerName, cacheName);
        }

        CacheMode ssoCacheMode = ssoCacheConfiguration.clustering().cacheMode();
        if (ssoCacheMode != CacheMode.REPL_ASYNC && ssoCacheMode != CacheMode.REPL_SYNC) {
            LOG.warnv("SSO cache mode is {0}, it is recommended to use replicated mode instead.", ssoCacheConfiguration.clustering().cacheModeString());
        }

        Cache<String, String[]> ssoCache = cacheManager.getCache(cacheName, true);
        final SsoSessionCacheListener listener = new SsoSessionCacheListener(ssoCache, mapper);
        ssoCache.addListener(listener);

        // Not possible to add listener for cross-DC support because of too old Infinispan in AS 7
        warnIfRemoteStoreIsUsed(ssoCache);

        LOG.debugv("Added distributed SSO session cache, lookup={0}, cache name={1}", cacheContainerLookup, cacheName);

        SsoCacheSessionIdMapperUpdater updater = new SsoCacheSessionIdMapperUpdater(ssoCache, previousIdMapperUpdater);

        return updater;
    } catch (NamingException ex) {
        LOG.warnv("Failed to obtain distributed session cache container, lookup={0}", cacheContainerLookup);
        return previousIdMapperUpdater;
    }
}
 
Example 16
Source File: Runner.java    From myrrix-recommender with Apache License 2.0 4 votes vote down vote up
private Context makeContext(Tomcat tomcat, File noSuchBaseDir, int port) throws IOException {

    File contextPath = new File(noSuchBaseDir, "context");
    if (!contextPath.mkdirs()) {
      throw new IOException("Could not create " + contextPath);
    }

    String contextPathURIBase = config.getContextPath();
    Context context = 
        tomcat.addContext(contextPathURIBase == null ? "" : contextPathURIBase, contextPath.getAbsolutePath());
    context.addApplicationListener(new ApplicationListener(InitListener.class.getName(), false));
    context.setWebappVersion("3.0");
    context.addWelcomeFile("index.jspx");
    addErrorPages(context);

    ServletContext servletContext = context.getServletContext();
    servletContext.setAttribute(InitListener.INSTANCE_ID_KEY, config.getInstanceID());
    servletContext.setAttribute(InitListener.BUCKET_KEY, config.getBucket());
    servletContext.setAttribute(InitListener.RESCORER_PROVIDER_CLASS_KEY, config.getRescorerProviderClassName());
    servletContext.setAttribute(InitListener.CLIENT_THREAD_CLASS_KEY, config.getClientThreadClassName());    
    servletContext.setAttribute(InitListener.LOCAL_INPUT_DIR_KEY, config.getLocalInputDir());
    servletContext.setAttribute(InitListener.PORT_KEY, port);
    servletContext.setAttribute(InitListener.READ_ONLY_KEY, config.isReadOnly());
    servletContext.setAttribute(InitListener.ALL_PARTITIONS_SPEC_KEY, config.getAllPartitionsSpecification());
    servletContext.setAttribute(InitListener.PARTITION_KEY, config.getPartition());

    boolean needHTTPS = config.getKeystoreFile() != null;
    boolean needAuthentication = config.getUserName() != null;

    if (needHTTPS || needAuthentication) {

      SecurityCollection securityCollection = new SecurityCollection("Protected Resources");
      if (config.isConsoleOnlyPassword()) {
        securityCollection.addPattern("/index.jspx");
      } else {
        securityCollection.addPattern("/*");
      }
      SecurityConstraint securityConstraint = new SecurityConstraint();
      securityConstraint.addCollection(securityCollection);

      if (needHTTPS) {
        securityConstraint.setUserConstraint("CONFIDENTIAL");
      }

      if (needAuthentication) {

        LoginConfig loginConfig = new LoginConfig();
        loginConfig.setAuthMethod("DIGEST");
        loginConfig.setRealmName(InMemoryRealm.NAME);
        context.setLoginConfig(loginConfig);

        securityConstraint.addAuthRole(InMemoryRealm.AUTH_ROLE);

        context.addSecurityRole(InMemoryRealm.AUTH_ROLE);
        DigestAuthenticator authenticator = new DigestAuthenticator();
        authenticator.setNonceValidity(10 * 1000L); // Shorten from 5 minutes to 10 seconds
        authenticator.setNonceCacheSize(20000); // Increase from 1000 to 20000
        context.getPipeline().addValve(authenticator);
      }

      context.addConstraint(securityConstraint);
    }

    context.setCookies(false);

    return context;
  }