org.apache.catalina.core.StandardContext Java Examples

The following examples show how to use org.apache.catalina.core.StandardContext. 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: TomcatTest.java    From deltaspike with Apache License 2.0 6 votes vote down vote up
@Override
protected int createServer() throws Exception
{
    String baseDir = "target/webapp-runner";
    tomcat = new Tomcat();
    int port = super.getPort();
    tomcat.setPort(port);
    File base = new File(baseDir);
    if (!base.exists())
    {
        base.mkdirs();
    }
    tomcat.setBaseDir(baseDir);
    Context ctx = tomcat.addContext("/",base.getAbsolutePath());
    StandardContext standardContext = (StandardContext)ctx;
    standardContext.addApplicationListener(CdiServletContextListener.class.getName());

    Wrapper wrapper = Tomcat.addServlet(ctx,"RequestServlet",RequestServlet.class.getName());
    wrapper.addMapping("/*");
    tomcat.start();
    return port;
}
 
Example #2
Source File: AnnotationProcessor.java    From carbon-device-mgt with Apache License 2.0 6 votes vote down vote up
public AnnotationProcessor(final StandardContext context) {
    servletContext = context.getServletContext();
    classLoader = servletContext.getClassLoader();
    try {
        pathClazz = (Class<Path>) classLoader.loadClass(Path.class.getName());
        consumesClass = (Class<Consumes>) classLoader.loadClass(Consumes.class.getName());
        producesClass = (Class<Produces>) classLoader.loadClass(Produces.class.getName());
        apiClazz= (Class<SwaggerDefinition>)classLoader.loadClass((SwaggerDefinition.class.getName()));
        infoClass = (Class<io.swagger.annotations.Info>)classLoader
                .loadClass((io.swagger.annotations.Info.class.getName()));
        tagClass = (Class<io.swagger.annotations.Tag>)classLoader
                .loadClass((io.swagger.annotations.Tag.class.getName()));
        extensionClass = (Class<io.swagger.annotations.Extension>)classLoader
                .loadClass((io.swagger.annotations.Extension.class.getName()));
        extensionPropertyClass = (Class<io.swagger.annotations.ExtensionProperty>)classLoader
                .loadClass(io.swagger.annotations.ExtensionProperty.class.getName());
        scopeClass = (Class<org.wso2.carbon.apimgt.annotations.api.Scope>) classLoader
                .loadClass(org.wso2.carbon.apimgt.annotations.api.Scope.class.getName());
        scopesClass = (Class<org.wso2.carbon.apimgt.annotations.api.Scopes>) classLoader
                .loadClass(org.wso2.carbon.apimgt.annotations.api.Scopes.class.getName());
        apiOperation = (Class<io.swagger.annotations.ApiOperation>)classLoader
                .loadClass((io.swagger.annotations.ApiOperation.class.getName()));
    } catch (ClassNotFoundException e) {
        log.error("An error has occurred while loading classes ", e);
    }
}
 
Example #3
Source File: TestELInJsp.java    From tomcatsrc with Apache License 2.0 6 votes vote down vote up
@Test
public void testBug56029() throws Exception {
    Tomcat tomcat = getTomcatInstance();

    File appDir = new File("test/webapp-3.0");
    // app dir is relative to server home
    StandardContext ctxt = (StandardContext) tomcat.addWebapp(
            null, "/test", appDir.getAbsolutePath());

    // This test needs the JSTL libraries
    File lib = new File("webapps/examples/WEB-INF/lib");
    ctxt.setAliases("/WEB-INF/lib=" + lib.getCanonicalPath());

    tomcat.start();

    ByteChunk res = getUrl("http://localhost:" + getPort() +
            "/test/bug5nnnn/bug56029.jspx");

    String result = res.toString();

    Assert.assertTrue(result.contains("[1]:[1]"));
}
 
Example #4
Source File: InMemoryRealmTest.java    From oryx with Apache License 2.0 6 votes vote down vote up
@Test
public void testAuthenticate() throws Exception {
  InMemoryRealm realm = new InMemoryRealm();
  StandardContext ctx = new StandardContext();
  ctx.setName("OryxTest");
  realm.setContainer(ctx);
  realm.start();

  realm.addUser("foo", "bar");
  Principal authPrincipal = realm.authenticate("foo", "bar");
  assertNotNull(authPrincipal);
  assertEquals("foo", authPrincipal.getName());
  assertNull(realm.authenticate("foo", "baz"));
  assertNull(realm.authenticate("bar", "foo"));
  assertEquals("bar", realm.getPassword("foo"));
  assertEquals("foo", realm.getPrincipal("foo").getName());
}
 
Example #5
Source File: TestContextConfig.java    From Tomcat7.0.67 with Apache License 2.0 6 votes vote down vote up
private void doTestOverrideDefaultServletWithSCI(String servletName)
        throws Exception{

    Tomcat tomcat = getTomcatInstance();

    File appDir = new File("test/webapp-3.0");
    StandardContext ctxt = (StandardContext) tomcat.addContext(null,
            "/test", appDir.getAbsolutePath());
    ctxt.setDefaultWebXml(new File("conf/web.xml").getAbsolutePath());
    ctxt.addLifecycleListener(new ContextConfig());

    ctxt.addServletContainerInitializer(
            new CustomDefaultServletSCI(servletName), null);

    tomcat.start();

    assertPageContains("/test", "OK - Custom default Servlet");
}
 
Example #6
Source File: TomcatWebAppBuilder.java    From tomee with Apache License 2.0 6 votes vote down vote up
@Override
public void configureStart(final LifecycleEvent event, final StandardContext standardContext) {
    final ContextTransaction contextTransaction = new ContextTransaction();
    contextTransaction.setProperty(org.apache.naming.factory.Constants.FACTORY, UserTransactionFactory.class.getName());
    standardContext.getNamingResources().setTransaction(contextTransaction);

    if (event != null) {
        // ensure NamingContext is available for eager usage (@Observes @Initialized(ApplicationScoped) for instance)
        standardContext.getNamingContextListener().lifecycleEvent(event);
    }

    TomcatHelper.configureJarScanner(standardContext);

    startInternal(standardContext);

    // clear a bit log for default case
    addMyFacesDefaultParameters(standardContext.getLoader().getClassLoader(), standardContext.getServletContext());

    // breaks cdi
    standardContext.setTldValidation(Boolean.parseBoolean(SystemInstance.get().getProperty("tomee.tld.validation", "false")));
    // breaks jstl
    standardContext.setXmlValidation(Boolean.parseBoolean(SystemInstance.get().getProperty("tomee.xml.validation", "false")));
}
 
Example #7
Source File: WatchedResourceSF.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
@Override
public void store(PrintWriter aWriter, int indent, Object aElement)
        throws Exception {
    if (aElement instanceof StandardContext) {
        StoreDescription elementDesc = getRegistry().findDescription(
                aElement.getClass().getName() + ".[WatchedResource]");
        String[] resources = ((StandardContext) aElement)
                .findWatchedResources();
        if (elementDesc != null) {
            if (log.isDebugEnabled())
                log.debug("store " + elementDesc.getTag() + "( " + aElement
                        + " )");
            getStoreAppender().printTagArray(aWriter, "WatchedResource",
                    indent, resources);
        }
    } else
        log.warn("Descriptor for element" + aElement.getClass()
                + ".[WatchedResource] not configured!");
}
 
Example #8
Source File: StoreContextAppender.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
/**
 * Print Context Values. <ul><li> Special handling to default workDir.
 * </li><li> Don't save path at external context.xml </li><li> Don't
 * generate docBase for host.appBase webapps <LI></ul>
 *
 * @see org.apache.catalina.storeconfig.StoreAppender#isPrintValue(java.lang.Object,
 *      java.lang.Object, java.lang.String,
 *      org.apache.catalina.storeconfig.StoreDescription)
 */
@Override
public boolean isPrintValue(Object bean, Object bean2, String attrName,
        StoreDescription desc) {
    boolean isPrint = super.isPrintValue(bean, bean2, attrName, desc);
    if (isPrint) {
        StandardContext context = ((StandardContext) bean);
        if ("workDir".equals(attrName)) {
            String defaultWorkDir = getDefaultWorkDir(context);
            isPrint = !defaultWorkDir.equals(context.getWorkDir());
        } else if ("path".equals(attrName)) {
            isPrint = desc.isStoreSeparate()
                        && desc.isExternalAllowed()
                        && context.getConfigFile() == null;
        } else if ("docBase".equals(attrName)) {
            Container host = context.getParent();
            if (host instanceof StandardHost) {
                File appBase = getAppBase(((StandardHost) host));
                File docBase = getDocBase(context,appBase);
                isPrint = !appBase.equals(docBase.getParentFile());
            }
        }
    }
    return isPrint;
}
 
Example #9
Source File: TomcatWebAppBuilder.java    From tomee with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void destroy(final StandardContext standardContext) {
    final Loader standardContextLoader = standardContext.getLoader();
    if (LazyStopLoader.class.isInstance(standardContextLoader)) {
        final Loader delegate = LazyStopLoader.class.cast(standardContextLoader).getDelegateLoader();
        if (TomEEWebappLoader.class.isInstance(delegate)) {
            final TomEEWebappLoader webappLoader = TomEEWebappLoader.class.cast(delegate);
            final ClassLoader loader = webappLoader.internalLoader();
            webappLoader.clearLoader();
            if (TomEEWebappClassLoader.class.isInstance(loader)) {
                TomEEWebappClassLoader.class.cast(loader).internalDestroy();
            }
        }
    }

    final WebResourceRoot root = standardContext.getResources();
    if (LazyStopStandardRoot.class.isInstance(root)) {
        try {
            LazyStopStandardRoot.class.cast(root).internalDestroy();
        } catch (final LifecycleException e) {
            throw new IllegalStateException(e);
        }
    }
}
 
Example #10
Source File: TestTomcat.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
@Test
public void testBrokenWarTwo() throws Exception {
    Tomcat tomcat = getTomcatInstance();

    StandardContext ctxA = (StandardContext) tomcat.addContext("/a", null);
    ctxA.addValve(new BrokenAuthenticator());
    StandardContext ctxB = (StandardContext) tomcat.addContext("/b", null);
    ctxB.addValve(new BrokenAuthenticator());

    try {
        tomcat.start();
        Assert.fail();
    } catch (Throwable t) {
        Assert.assertTrue(getRootCause(t) instanceof MultiThrowable);
    }
}
 
Example #11
Source File: TomEEMyFacesContainerInitializer.java    From tomee with Apache License 2.0 6 votes vote down vote up
private boolean isFacesServletPresent(final ServletContext ctx) {
    if (ctx instanceof ApplicationContextFacade) {
        try {
            final ApplicationContext appCtx = (ApplicationContext) get(ApplicationContextFacade.class, ctx);
            final Context tomcatCtx = (Context) get(ApplicationContext.class, appCtx);
            if (tomcatCtx instanceof StandardContext) {
                final Container[] servlets = tomcatCtx.findChildren();
                if (servlets != null) {
                    for (final Container s : servlets) {
                        if (s instanceof Wrapper) {
                            if ("javax.faces.webapp.FacesServlet".equals(((Wrapper) s).getServletClass())
                                    || "Faces Servlet".equals(s.getName())) {
                                return true;
                            }
                        }
                    }
                }
            }
        } catch (final Exception e) {
            // no-op
        }
    }
    return false;
}
 
Example #12
Source File: BasicAuthAuthenticatorTest.java    From carbon-device-mgt with Apache License 2.0 6 votes vote down vote up
@Test(description = "This method tests the behaviour of the authenticate method in BasicAuthenticator with valid "
        + "credentials", dependsOnMethods = "testCanHandleWithRequireParameters")
public void testAuthenticateWithValidCredentials() throws EncoderException, IllegalAccessException {
    String encodedString = new String(Base64.getEncoder().encode((ADMIN_USER + ":" + ADMIN_USER).getBytes()));
    request = new Request();
    context = new StandardContext();
    context.addParameter("basicAuth", "true");
    request.setContext(context);
    mimeHeaders = new MimeHeaders();
    bytes = mimeHeaders.addValue(BaseWebAppAuthenticatorFrameworkTest.AUTHORIZATION_HEADER);
    bytes.setString(BASIC_HEADER + encodedString);
    coyoteRequest = new org.apache.coyote.Request();
    headersField.set(coyoteRequest, mimeHeaders);
    request.setCoyoteRequest(coyoteRequest);
    AuthenticationInfo authenticationInfo = basicAuthAuthenticator.authenticate(request, null);
    Assert.assertEquals(authenticationInfo.getStatus(), WebappAuthenticator.Status.CONTINUE,
            "For a valid user authentication failed.");
    Assert.assertEquals(authenticationInfo.getUsername(), ADMIN_USER,
            "Authenticated username for from BasicAuthenticator is not matching with the original user.");
    Assert.assertEquals(authenticationInfo.getTenantDomain(), MultitenantConstants.SUPER_TENANT_DOMAIN_NAME,
            "Authenticated user's tenant domain from BasicAuthenticator is not matching with the "
                    + "original user's tenant domain");
    Assert.assertEquals(authenticationInfo.getTenantId(), MultitenantConstants.SUPER_TENANT_ID,
            "Authenticated user's tenant ID from BasicAuthenticator is not matching with the "
                    + "original user's tenant ID");
}
 
Example #13
Source File: TestHttpServlet.java    From Tomcat7.0.67 with Apache License 2.0 6 votes vote down vote up
@Test
public void testBug53454() throws Exception {
    Tomcat tomcat = getTomcatInstance();

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

    // Map the test Servlet
    LargeBodyServlet largeBodyServlet = new LargeBodyServlet();
    Tomcat.addServlet(ctx, "largeBodyServlet", largeBodyServlet);
    ctx.addServletMapping("/", "largeBodyServlet");

    tomcat.start();

    Map<String,List<String>> resHeaders=
            new HashMap<String, List<String>>();
    int rc = headUrl("http://localhost:" + getPort() + "/", new ByteChunk(),
           resHeaders);

    Assert.assertEquals(HttpServletResponse.SC_OK, rc);
    Assert.assertEquals(LargeBodyServlet.RESPONSE_LENGTH,
            resHeaders.get("Content-Length").get(0));
}
 
Example #14
Source File: TestWarDirContext.java    From tomcatsrc with Apache License 2.0 6 votes vote down vote up
/**
 * Additional test following on from SPR-7350 above to check files that
 * contain JNDI reserved characters can be served when caching is disabled.
 */
@Test
public void testReservedJNDIFileNamesNoCache() throws Exception {
    Tomcat tomcat = getTomcatInstance();

    File appDir = new File("test/webapp-3.0-fragments");
    // app dir is relative to server home
    StandardContext ctxt = (StandardContext) tomcat.addWebapp(
            null, "/test", appDir.getAbsolutePath());
    ctxt.setCachingAllowed(false);

    tomcat.start();

    // Should be found in resources.jar
    ByteChunk bc = getUrl("http://localhost:" + getPort() +
            "/test/'singlequote.jsp");
    assertEquals("<p>'singlequote.jsp in resources.jar</p>",
            bc.toString());

    // Should be found in file system
    bc = getUrl("http://localhost:" + getPort() +
            "/test/'singlequote2.jsp");
    assertEquals("<p>'singlequote2.jsp in file system</p>",
            bc.toString());
}
 
Example #15
Source File: TestWarDirContext.java    From Tomcat7.0.67 with Apache License 2.0 6 votes vote down vote up
/**
 * Additional test following on from SPR-7350 above to check files that
 * contain JNDI reserved characters can be served when caching is enabled.
 */
@Test
public void testReservedJNDIFileNamesWithCache() throws Exception {
    Tomcat tomcat = getTomcatInstance();

    File appDir = new File("test/webapp-3.0-fragments");
    // app dir is relative to server home
    StandardContext ctxt = (StandardContext) tomcat.addWebapp(
            null, "/test", appDir.getAbsolutePath());
    ctxt.setCachingAllowed(true);

    tomcat.start();

    // Should be found in resources.jar
    ByteChunk bc = getUrl("http://localhost:" + getPort() +
            "/test/'singlequote.jsp");
    assertEquals("<p>'singlequote.jsp in resources.jar</p>",
            bc.toString());

    // Should be found in file system
    bc = getUrl("http://localhost:" + getPort() +
            "/test/'singlequote2.jsp");
    assertEquals("<p>'singlequote2.jsp in file system</p>",
            bc.toString());
}
 
Example #16
Source File: TomcatWebAppBuilder.java    From tomee with Apache License 2.0 6 votes vote down vote up
/**
 * Creates an openejb {@link AppModule} instance
 * from given tomcat context.
 *
 * @param standardContext tomcat context instance
 * @return a openejb application module
 */
private AppModule loadApplication(final StandardContext standardContext) {
    // don't use getId since the app id shouldnt get the host (jndi)
    // final TomcatDeploymentLoader tomcatDeploymentLoader = new TomcatDeploymentLoader(standardContext, getId(standardContext));

    String id = standardContext.getName();
    if (id.startsWith("/")) {
        id = id.substring(1);
    }

    final TomcatDeploymentLoader tomcatDeploymentLoader = new TomcatDeploymentLoader(standardContext, id);
    final AppModule appModule;
    try {
        appModule = tomcatDeploymentLoader.load(Contexts.warPath(standardContext), configuredClasspath(standardContext));
    } catch (final OpenEJBException e) {
        throw new TomEERuntimeException(e);
    }

    // create the web module
    loadWebModule(appModule, standardContext);

    return appModule;
}
 
Example #17
Source File: Tomcat.java    From Tomcat8-Source-Read with MIT License 6 votes vote down vote up
/**
 * Create the configured {@link Context} for the given <code>host</code>.
 * The default constructor of the class that was configured with
 * {@link StandardHost#setContextClass(String)} will be used
 *
 * @param host
 *            host for which the {@link Context} should be created, or
 *            <code>null</code> if default host should be used
 * @param url
 *            path of the webapp which should get the {@link Context}
 * @return newly created {@link Context}
 */
private Context createContext(Host host, String url) {
    String contextClass = StandardContext.class.getName();
    if (host == null) {
        host = this.getHost();
    }
    if (host instanceof StandardHost) {
        contextClass = ((StandardHost) host).getContextClass();
    }
    try {
        return (Context) Class.forName(contextClass).getConstructor()
                .newInstance();
    } catch (InstantiationException | IllegalAccessException
            | IllegalArgumentException | InvocationTargetException
            | NoSuchMethodException | SecurityException
            | ClassNotFoundException e) {
        throw new IllegalArgumentException(
                "Can't instantiate context-class " + contextClass
                        + " for host " + host + " and url "
                        + url, e);
    }
}
 
Example #18
Source File: DubboApplicationContextInitializerTest.java    From dubbo-2.6.5 with Apache License 2.0 6 votes vote down vote up
@Test
public void testSpringContextLoaderListenerInWebXml() throws Exception {
    Tomcat tomcat = new Tomcat();
    tomcat.setBaseDir("target/test-classes");
    tomcat.setPort(12345);
    StandardContext context = new StandardContext();
    context.setName("test");
    context.setDocBase("test");
    context.setPath("/test");
    context.addLifecycleListener(new ContextConfig());
    tomcat.getHost().addChild(context);
    tomcat.start();
    // there should be 1 application listener
    Assert.assertEquals(1, context.getApplicationLifecycleListeners().length);
    // the first one should be Spring's built in ContextLoaderListener.
    Assert.assertTrue(context.getApplicationLifecycleListeners()[0] instanceof ContextLoaderListener);
    tomcat.stop();
    tomcat.destroy();
}
 
Example #19
Source File: ContextConfig.java    From Tomcat7.0.67 with Apache License 2.0 6 votes vote down vote up
/**
 * Process a "destroy" event for this Context.
 */
protected synchronized void destroy() {
    // Called from StandardContext.destroy()
    if (log.isDebugEnabled())
        log.debug(sm.getString("contextConfig.destroy"));

    // Skip clearing the work directory if Tomcat is being shutdown
    Server s = getServer();
    if (s != null && !s.getState().isAvailable()) {
        return;
    }

    // Changed to getWorkPath per Bugzilla 35819.
    if (context instanceof StandardContext) {
        String workDir = ((StandardContext) context).getWorkPath();
        if (workDir != null) {
            ExpandWar.delete(new File(workDir));
        }
    }
}
 
Example #20
Source File: DubboApplicationContextInitializerTest.java    From dubbo-2.6.5 with Apache License 2.0 6 votes vote down vote up
@Test
public void testNoListenerInWebXml() throws Exception {
    Tomcat tomcat = new Tomcat();
    tomcat.setBaseDir("target/test-classes");
    tomcat.setPort(12345);
    StandardContext context = new StandardContext();
    context.setName("test2");
    context.setDocBase("test2");
    context.setPath("/test2");
    context.addLifecycleListener(new ContextConfig());
    tomcat.getHost().addChild(context);
    tomcat.start();
    // there should be 1 application listener
    Assert.assertEquals(1, context.getApplicationLifecycleListeners().length);
    // the first one should be Spring's built in ContextLoaderListener.
    Assert.assertTrue(context.getApplicationLifecycleListeners()[0] instanceof ContextLoaderListener);
    tomcat.stop();
    tomcat.destroy();
}
 
Example #21
Source File: OpenEJBContextConfig.java    From tomee with Apache License 2.0 6 votes vote down vote up
@Override
protected WebXml createWebXml() {
    String prefix = "";
    if (context instanceof StandardContext) {
        final StandardContext standardContext = (StandardContext) context;
        prefix = standardContext.getEncodedPath();
        if (prefix.startsWith("/")) {
            prefix = prefix.substring(1);
        }
    }
    final OpenEJBWebXml webXml = new OpenEJBWebXml(prefix);

    if (DEFERRED_SYNTAX != null) {
        for (final String s : DEFERRED_SYNTAX.split(",")) {
            if (!s.isEmpty()) {
                final JspPropertyGroup propertyGroup = new JspPropertyGroup();
                propertyGroup.addUrlPattern(s);
                propertyGroup.setDeferredSyntax("true");
                webXml.addJspPropertyGroup(propertyGroup);
            }
        }
    }

    return webXml;
}
 
Example #22
Source File: ContextConfig.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
/**
 * Identify the default web.xml to be used and obtain an input source for
 * it.
 */
protected InputSource getGlobalWebXmlSource() {
    // Is a default web.xml specified for the Context?
    if (defaultWebXml == null && context instanceof StandardContext) {
        defaultWebXml = ((StandardContext) context).getDefaultWebXml();
    }
    // Set the default if we don't have any overrides
    if (defaultWebXml == null) getDefaultWebXml();

    // Is it explicitly suppressed, e.g. in embedded environment?
    if (Constants.NoDefaultWebXml.equals(defaultWebXml)) {
        return null;
    }
    return getWebXmlSource(defaultWebXml, getBaseDir());
}
 
Example #23
Source File: ArkTomcatServletWebServerFactory.java    From sofa-ark with Apache License 2.0 5 votes vote down vote up
@Override
protected void prepareContext(Host host, ServletContextInitializer[] initializers) {
    if (host.getState() == LifecycleState.NEW) {
        super.prepareContext(host, initializers);
    } else {
        File documentRoot = getValidDocumentRoot();
        StandardContext context = new StandardContext();
        if (documentRoot != null) {
            context.setResources(new StandardRoot(context));
        }
        context.setName(getContextPath());
        context.setDisplayName(getDisplayName());
        context.setPath(getContextPath());
        File docBase = (documentRoot != null) ? documentRoot : createTempDir("tomcat-docbase");
        context.setDocBase(docBase.getAbsolutePath());
        context.addLifecycleListener(new Tomcat.FixContextListener());
        context.setParentClassLoader(Thread.currentThread().getContextClassLoader());
        resetDefaultLocaleMapping(context);
        addLocaleMappings(context);
        context.setUseRelativeRedirects(false);
        configureTldSkipPatterns(context);
        WebappLoader loader = new WebappLoader(context.getParentClassLoader());
        loader
            .setLoaderClass("com.alipay.sofa.ark.web.embed.tomcat.ArkTomcatEmbeddedWebappClassLoader");
        loader.setDelegate(true);
        context.setLoader(loader);
        if (isRegisterDefaultServlet()) {
            addDefaultServlet(context);
        }
        if (shouldRegisterJspServlet()) {
            addJspServlet(context);
            addJasperInitializer(context);
        }
        context.addLifecycleListener(new StaticResourceConfigurer(context));
        ServletContextInitializer[] initializersToUse = mergeInitializers(initializers);
        context.setParent(host);
        configureContext(context, initializersToUse);
        host.addChild(context);
    }
}
 
Example #24
Source File: ArkTomcatServletWebServerFactory.java    From sofa-ark with Apache License 2.0 5 votes vote down vote up
/**
 * Override Tomcat's default locale mappings to align with other servers. See
 * {@code org.apache.catalina.util.CharsetMapperDefault.properties}.
 * @param context the context to reset
 */
private void resetDefaultLocaleMapping(StandardContext context) {
    context.addLocaleEncodingMappingParameter(Locale.ENGLISH.toString(),
        DEFAULT_CHARSET.displayName());
    context.addLocaleEncodingMappingParameter(Locale.FRENCH.toString(),
        DEFAULT_CHARSET.displayName());
}
 
Example #25
Source File: TestNamingContext.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
@Test
public void testBug52830() throws Exception {
    Tomcat tomcat = getTomcatInstance();
    tomcat.enableNaming();

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

    // Create the resource
    ContextEnvironment env = new ContextEnvironment();
    env.setName("boolean");
    env.setType(Boolean.class.getName());
    env.setValue("true");
    ctx.getNamingResources().addEnvironment(env);

    // Map the test Servlet
    Bug52830Servlet bug52830Servlet = new Bug52830Servlet();
    Tomcat.addServlet(ctx, "bug52830Servlet", bug52830Servlet);
    ctx.addServletMapping("/", "bug52830Servlet");

    tomcat.start();

    ByteChunk bc = new ByteChunk();
    int rc = getUrl("http://localhost:" + getPort() + "/", bc, null);
    assertEquals(200, rc);
    assertTrue(bc.toString().contains("truetrue"));
}
 
Example #26
Source File: ArkTomcatServletWebServerFactory.java    From sofa-ark with Apache License 2.0 5 votes vote down vote up
private void addJasperInitializer(StandardContext context) {
    try {
        ServletContainerInitializer initializer = (ServletContainerInitializer) ClassUtils
            .forName("org.apache.jasper.servlet.JasperInitializer", null).newInstance();
        context.addServletContainerInitializer(initializer, null);
    } catch (Exception ex) {
        // Probably not Tomcat 8
    }
}
 
Example #27
Source File: Contexts.java    From tomee with Apache License 2.0 5 votes vote down vote up
public static String getHostname(final StandardContext ctx) {
    String hostName = null;
    final Container parentHost = ctx.getParent();
    if (parentHost != null) {
        hostName = parentHost.getName();
    }
    if ((hostName == null) || (hostName.length() < 1)) {
        hostName = "_";
    }
    return hostName;
}
 
Example #28
Source File: SpringBootTomcatPlusIT.java    From uavstack with Apache License 2.0 5 votes vote down vote up
/**
 * onAppStop
 * 
 * @param args
 */
@Override
public void onAppStop(Object... args) {

    StandardContext sc = (StandardContext) args[0];
    InterceptSupport iSupport = InterceptSupport.instance();
    InterceptContext context = iSupport.createInterceptContext(Event.WEBCONTAINER_STOPPED);

    if (null == context || null == sc) {
        return;
    }

    /**
     * NOTE: spring boot will reset tomcat webappclassloader to null when shutdown, we may use the currentThread's
     * classloader as the classloader
     */
    context.put(InterceptConstants.WEBAPPLOADER, Thread.currentThread().getContextClassLoader());
    context.put(InterceptConstants.WEBWORKDIR, sc.getWorkPath());

    String contextPath = (String) ReflectionHelper.getField(StandardContext.class, sc, "encodedPath", true);
    context.put(InterceptConstants.CONTEXTPATH, contextPath);

    context.put(InterceptConstants.APPNAME, ReflectionHelper.getField(StandardContext.class, sc, "displayName", true));
    context.put(InterceptConstants.SERVLET_CONTEXT,
            ReflectionHelper.getField(StandardContext.class, sc, "context", true));

    iSupport.doIntercept(context);
}
 
Example #29
Source File: TestMapperWebapps.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
@Test
public void testWelcomeFileNotStrict() throws Exception {

    Tomcat tomcat = getTomcatInstance();

    File appDir = new File("test/webapp-3.0");

    StandardContext ctxt = (StandardContext) tomcat.addWebapp(null, "/test",
            appDir.getAbsolutePath());
    ctxt.setReplaceWelcomeFiles(true);
    ctxt.addWelcomeFile("index.jsp");
    // Mapping for *.do is defined in web.xml
    ctxt.addWelcomeFile("index.do");

    tomcat.start();
    ByteChunk bc = new ByteChunk();
    int rc = getUrl("http://localhost:" + getPort() +
            "/test/welcome-files", bc, new HashMap<String,List<String>>());
    Assert.assertEquals(HttpServletResponse.SC_OK, rc);
    Assert.assertTrue(bc.toString().contains("JSP"));

    rc = getUrl("http://localhost:" + getPort() +
            "/test/welcome-files/sub", bc,
            new HashMap<String,List<String>>());
    Assert.assertEquals(HttpServletResponse.SC_OK, rc);
    Assert.assertTrue(bc.toString().contains("Servlet"));
}
 
Example #30
Source File: ContextConfig.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
/**
 * Process the application classes annotations, if it exists.
 */
protected void applicationAnnotationsConfig() {

    long t1=System.currentTimeMillis();

    WebAnnotationSet.loadApplicationAnnotations(context);

    long t2=System.currentTimeMillis();
    if (context instanceof StandardContext) {
        ((StandardContext) context).setStartupTime(t2-t1+
                ((StandardContext) context).getStartupTime());
    }
}