Search in sources :

Example 51 with StandardContext

use of org.apache.catalina.core.StandardContext in project tomcat by apache.

the class TestTomcatNoServer method testDefaultMimeTypeMappings.

@Test
public void testDefaultMimeTypeMappings() throws Exception {
    StandardContext ctx = new StandardContext();
    Tomcat.initWebappDefaults(ctx);
    InputSource globalWebXml = new InputSource(new File("conf/web.xml").getAbsoluteFile().toURI().toString());
    WebXml webXmlDefaultFragment = new WebXml();
    webXmlDefaultFragment.setOverridable(true);
    webXmlDefaultFragment.setDistributable(true);
    webXmlDefaultFragment.setAlwaysAddWelcomeFiles(false);
    Digester digester = DigesterFactory.newDigester(true, true, new WebRuleSet(), true);
    XmlErrorHandler handler = new XmlErrorHandler();
    digester.setErrorHandler(handler);
    digester.push(webXmlDefaultFragment);
    digester.parse(globalWebXml);
    Assert.assertEquals(0, handler.getErrors().size());
    Assert.assertEquals(0, handler.getWarnings().size());
    Map<String, String> webXmlMimeMappings = webXmlDefaultFragment.getMimeMappings();
    Set<String> embeddedExtensions = new HashSet<>(Arrays.asList(ctx.findMimeMappings()));
    // Find entries present in conf/web.xml that are missing in embedded
    Set<String> missingInEmbedded = new HashSet<>(webXmlMimeMappings.keySet());
    missingInEmbedded.removeAll(embeddedExtensions);
    if (missingInEmbedded.size() > 0) {
        for (String missingExtension : missingInEmbedded) {
            System.out.println("Missing in embedded: [" + missingExtension + "]-[" + webXmlMimeMappings.get(missingExtension) + "]");
        }
        Assert.fail("Embedded is missing [" + missingInEmbedded.size() + "] entries compared to conf/web.xml");
    }
    // Find entries present in embedded that are missing in conf/web.xml
    Set<String> missingInWebXml = new HashSet<>(embeddedExtensions);
    missingInWebXml.removeAll(webXmlMimeMappings.keySet());
    if (missingInWebXml.size() > 0) {
        for (String missingExtension : missingInWebXml) {
            System.out.println("Missing in embedded: [" + missingExtension + "]-[" + ctx.findMimeMapping(missingExtension) + "]");
        }
        Assert.fail("Embedded is missing [" + missingInWebXml.size() + "] entries compared to conf/web.xml");
    }
}
Also used : WebXml(org.apache.tomcat.util.descriptor.web.WebXml) InputSource(org.xml.sax.InputSource) StandardContext(org.apache.catalina.core.StandardContext) Digester(org.apache.tomcat.util.digester.Digester) XmlErrorHandler(org.apache.tomcat.util.descriptor.XmlErrorHandler) File(java.io.File) WebRuleSet(org.apache.tomcat.util.descriptor.web.WebRuleSet) HashSet(java.util.HashSet) Test(org.junit.Test)

Example 52 with StandardContext

use of org.apache.catalina.core.StandardContext in project tomcat by apache.

the class TestMaxConnections method init.

private synchronized void init() throws Exception {
    Tomcat tomcat = getTomcatInstance();
    StandardContext root = (StandardContext) tomcat.addContext("", SimpleHttpClient.TEMP_DIR);
    root.setUnloadDelay(soTimeout);
    Tomcat.addServlet(root, "Simple", new SimpleServlet());
    root.addServletMappingDecoded("/test", "Simple");
    Assert.assertTrue(tomcat.getConnector().setProperty("maxKeepAliveRequests", "1"));
    Assert.assertTrue(tomcat.getConnector().setProperty("maxThreads", "10"));
    Assert.assertTrue(tomcat.getConnector().setProperty("connectionTimeout", "20000"));
    Assert.assertTrue(tomcat.getConnector().setProperty("keepAliveTimeout", "50000"));
    Assert.assertTrue(tomcat.getConnector().setProperty("maxConnections", Integer.toString(MAX_CONNECTIONS)));
    Assert.assertTrue(tomcat.getConnector().setProperty("acceptCount", "1"));
    tomcat.start();
}
Also used : Tomcat(org.apache.catalina.startup.Tomcat) StandardContext(org.apache.catalina.core.StandardContext)

Example 53 with StandardContext

use of org.apache.catalina.core.StandardContext in project tomcat by apache.

the class ContainerMBean method addChild.

/**
 * Add a new child Container to those associated with this Container,
 * if supported. Won't start the child yet. Has to be started with a call to
 * Start method after necessary configurations are done.
 *
 * @param type ClassName of the child to be added
 * @param name Name of the child to be added
 *
 * @exception MBeanException if the child cannot be added
 */
public void addChild(String type, String name) throws MBeanException {
    Container contained = (Container) newInstance(type);
    contained.setName(name);
    if (contained instanceof StandardHost) {
        HostConfig config = new HostConfig();
        contained.addLifecycleListener(config);
    } else if (contained instanceof StandardContext) {
        ContextConfig config = new ContextConfig();
        contained.addLifecycleListener(config);
    }
    boolean oldValue = true;
    ContainerBase container = doGetManagedResource();
    try {
        oldValue = container.getStartChildren();
        container.setStartChildren(false);
        container.addChild(contained);
        contained.init();
    } catch (LifecycleException e) {
        throw new MBeanException(e);
    } finally {
        if (container != null) {
            container.setStartChildren(oldValue);
        }
    }
}
Also used : ContextConfig(org.apache.catalina.startup.ContextConfig) ContainerBase(org.apache.catalina.core.ContainerBase) Container(org.apache.catalina.Container) LifecycleException(org.apache.catalina.LifecycleException) StandardHost(org.apache.catalina.core.StandardHost) StandardContext(org.apache.catalina.core.StandardContext) HostConfig(org.apache.catalina.startup.HostConfig) MBeanException(javax.management.MBeanException)

Example 54 with StandardContext

use of org.apache.catalina.core.StandardContext in project tomcat by apache.

the class MBeanFactory method createStandardContext.

/**
 * Create a new StandardContext.
 *
 * @param parent MBean Name of the associated parent component
 * @param path The context path for this Context
 * @param docBase Document base directory (or WAR) for this Context
 * @param xmlValidation if XML descriptors should be validated
 * @param xmlNamespaceAware if the XML processor should namespace aware
 * @return the object name of the created context
 *
 * @exception Exception if an MBean cannot be created or registered
 */
public String createStandardContext(String parent, String path, String docBase, boolean xmlValidation, boolean xmlNamespaceAware) throws Exception {
    // Create a new StandardContext instance
    StandardContext context = new StandardContext();
    path = getPathStr(path);
    context.setPath(path);
    context.setDocBase(docBase);
    context.setXmlValidation(xmlValidation);
    context.setXmlNamespaceAware(xmlNamespaceAware);
    ContextConfig contextConfig = new ContextConfig();
    context.addLifecycleListener(contextConfig);
    // Add the new instance to its parent component
    ObjectName pname = new ObjectName(parent);
    ObjectName deployer = new ObjectName(pname.getDomain() + ":type=Deployer,host=" + pname.getKeyProperty("host"));
    if (mserver.isRegistered(deployer)) {
        String contextName = context.getName();
        Boolean result = (Boolean) mserver.invoke(deployer, "tryAddServiced", new Object[] { contextName }, new String[] { "java.lang.String" });
        if (result.booleanValue()) {
            try {
                String configPath = (String) mserver.getAttribute(deployer, "configBaseName");
                String baseName = context.getBaseName();
                File configFile = new File(new File(configPath), baseName + ".xml");
                if (configFile.isFile()) {
                    context.setConfigFile(configFile.toURI().toURL());
                }
                mserver.invoke(deployer, "manageApp", new Object[] { context }, new String[] { "org.apache.catalina.Context" });
            } finally {
                mserver.invoke(deployer, "removeServiced", new Object[] { contextName }, new String[] { "java.lang.String" });
            }
        } else {
            throw new IllegalStateException(sm.getString("mBeanFactory.contextCreate.addServicedFail", contextName));
        }
    } else {
        log.warn(sm.getString("mBeanFactory.noDeployer", pname.getKeyProperty("host")));
        Service service = getService(pname);
        Engine engine = service.getContainer();
        Host host = (Host) engine.findChild(pname.getKeyProperty("host"));
        host.addChild(context);
    }
    // Return the corresponding MBean name
    return context.getObjectName().toString();
}
Also used : ContextConfig(org.apache.catalina.startup.ContextConfig) StandardContext(org.apache.catalina.core.StandardContext) StandardService(org.apache.catalina.core.StandardService) Service(org.apache.catalina.Service) StandardHost(org.apache.catalina.core.StandardHost) Host(org.apache.catalina.Host) File(java.io.File) StandardEngine(org.apache.catalina.core.StandardEngine) Engine(org.apache.catalina.Engine) ObjectName(javax.management.ObjectName)

Example 55 with StandardContext

use of org.apache.catalina.core.StandardContext in project tomcat by apache.

the class StandardContextSF method storeChildren.

/**
 * Store the specified context element children.
 *
 * @param aWriter Current output writer
 * @param indent Indentation level
 * @param aContext Context to store
 * @param parentDesc The element description
 * @throws Exception Configuration storing error
 */
@Override
public void storeChildren(PrintWriter aWriter, int indent, Object aContext, StoreDescription parentDesc) throws Exception {
    if (aContext instanceof StandardContext) {
        StandardContext context = (StandardContext) aContext;
        // Store nested <Listener> elements
        LifecycleListener[] listeners = context.findLifecycleListeners();
        List<LifecycleListener> listenersArray = new ArrayList<>();
        for (LifecycleListener listener : listeners) {
            if (!(listener instanceof ThreadLocalLeakPreventionListener)) {
                listenersArray.add(listener);
            }
        }
        storeElementArray(aWriter, indent, listenersArray.toArray());
        // Store nested <Valve> elements
        Valve[] valves = context.getPipeline().getValves();
        storeElementArray(aWriter, indent, valves);
        // Store nested <Loader> elements
        Loader loader = context.getLoader();
        storeElement(aWriter, indent, loader);
        // Store nested <Manager> elements
        if (context.getCluster() == null || !context.getDistributable()) {
            Manager manager = context.getManager();
            storeElement(aWriter, indent, manager);
        }
        // Store nested <Realm> element
        Realm realm = context.getRealm();
        if (realm != null) {
            Realm parentRealm = null;
            // @TODO is this case possible?
            if (context.getParent() != null) {
                parentRealm = context.getParent().getRealm();
            }
            if (realm != parentRealm) {
                storeElement(aWriter, indent, realm);
            }
        }
        // Store nested resources
        WebResourceRoot resources = context.getResources();
        storeElement(aWriter, indent, resources);
        // Store nested <WrapperListener> elements
        String[] wLifecycles = context.findWrapperLifecycles();
        getStoreAppender().printTagArray(aWriter, "WrapperListener", indent + 2, wLifecycles);
        // Store nested <WrapperLifecycle> elements
        String[] wListeners = context.findWrapperListeners();
        getStoreAppender().printTagArray(aWriter, "WrapperLifecycle", indent + 2, wListeners);
        // Store nested <Parameter> elements
        ApplicationParameter[] appParams = context.findApplicationParameters();
        storeElementArray(aWriter, indent, appParams);
        // Store nested naming resources elements (EJB,Resource,...)
        NamingResourcesImpl nresources = context.getNamingResources();
        storeElement(aWriter, indent, nresources);
        // Store nested watched resources <WatchedResource>
        String[] wresources = context.findWatchedResources();
        wresources = filterWatchedResources(context, wresources);
        getStoreAppender().printTagArray(aWriter, "WatchedResource", indent + 2, wresources);
        // Store nested <JarScanner> elements
        JarScanner jarScanner = context.getJarScanner();
        storeElement(aWriter, indent, jarScanner);
        // Store nested <CookieProcessor> elements
        CookieProcessor cookieProcessor = context.getCookieProcessor();
        storeElement(aWriter, indent, cookieProcessor);
    }
}
Also used : ApplicationParameter(org.apache.tomcat.util.descriptor.web.ApplicationParameter) ArrayList(java.util.ArrayList) Loader(org.apache.catalina.Loader) LifecycleListener(org.apache.catalina.LifecycleListener) Manager(org.apache.catalina.Manager) JarScanner(org.apache.tomcat.JarScanner) ThreadLocalLeakPreventionListener(org.apache.catalina.core.ThreadLocalLeakPreventionListener) CookieProcessor(org.apache.tomcat.util.http.CookieProcessor) StandardContext(org.apache.catalina.core.StandardContext) Valve(org.apache.catalina.Valve) NamingResourcesImpl(org.apache.catalina.deploy.NamingResourcesImpl) Realm(org.apache.catalina.Realm) WebResourceRoot(org.apache.catalina.WebResourceRoot)

Aggregations

StandardContext (org.apache.catalina.core.StandardContext)181 File (java.io.File)72 Tomcat (org.apache.catalina.startup.Tomcat)64 Test (org.junit.Test)52 TomcatBaseTest (org.apache.catalina.startup.TomcatBaseTest)41 Context (org.apache.catalina.Context)32 ByteChunk (org.apache.tomcat.util.buf.ByteChunk)31 StandardHost (org.apache.catalina.core.StandardHost)25 IOException (java.io.IOException)22 Host (org.apache.catalina.Host)18 MalformedURLException (java.net.MalformedURLException)16 JarFile (java.util.jar.JarFile)16 ServletContext (javax.servlet.ServletContext)16 StandardRoot (org.apache.catalina.webresources.StandardRoot)16 URL (java.net.URL)13 InterceptSupport (com.creditease.monitor.interceptframework.InterceptSupport)12 InterceptContext (com.creditease.monitor.interceptframework.spi.InterceptContext)12 HashMap (java.util.HashMap)12 List (java.util.List)12 Container (org.apache.catalina.Container)12