Search in sources :

Example 6 with ContextResource

use of org.apache.tomcat.util.descriptor.web.ContextResource in project tomcat by apache.

the class ContextConfig method configureContext.

private void configureContext(WebXml webxml) {
    // As far as possible, process in alphabetical order so it is easy to
    // check everything is present
    // Some validation depends on correct public ID
    context.setPublicId(webxml.getPublicId());
    // Everything else in order
    context.setEffectiveMajorVersion(webxml.getMajorVersion());
    context.setEffectiveMinorVersion(webxml.getMinorVersion());
    for (Entry<String, String> entry : webxml.getContextParams().entrySet()) {
        context.addParameter(entry.getKey(), entry.getValue());
    }
    context.setDenyUncoveredHttpMethods(webxml.getDenyUncoveredHttpMethods());
    context.setDisplayName(webxml.getDisplayName());
    context.setDistributable(webxml.isDistributable());
    for (ContextLocalEjb ejbLocalRef : webxml.getEjbLocalRefs().values()) {
        context.getNamingResources().addLocalEjb(ejbLocalRef);
    }
    for (ContextEjb ejbRef : webxml.getEjbRefs().values()) {
        context.getNamingResources().addEjb(ejbRef);
    }
    for (ContextEnvironment environment : webxml.getEnvEntries().values()) {
        context.getNamingResources().addEnvironment(environment);
    }
    for (ErrorPage errorPage : webxml.getErrorPages().values()) {
        context.addErrorPage(errorPage);
    }
    for (FilterDef filter : webxml.getFilters().values()) {
        if (filter.getAsyncSupported() == null) {
            filter.setAsyncSupported("false");
        }
        context.addFilterDef(filter);
    }
    for (FilterMap filterMap : webxml.getFilterMappings()) {
        context.addFilterMap(filterMap);
    }
    context.setJspConfigDescriptor(webxml.getJspConfigDescriptor());
    for (String listener : webxml.getListeners()) {
        context.addApplicationListener(listener);
    }
    for (Entry<String, String> entry : webxml.getLocaleEncodingMappings().entrySet()) {
        context.addLocaleEncodingMappingParameter(entry.getKey(), entry.getValue());
    }
    // Prevents IAE
    if (webxml.getLoginConfig() != null) {
        context.setLoginConfig(webxml.getLoginConfig());
    }
    for (MessageDestinationRef mdr : webxml.getMessageDestinationRefs().values()) {
        context.getNamingResources().addMessageDestinationRef(mdr);
    }
    // messageDestinations were ignored in Tomcat 6, so ignore here
    context.setIgnoreAnnotations(webxml.isMetadataComplete());
    for (Entry<String, String> entry : webxml.getMimeMappings().entrySet()) {
        context.addMimeMapping(entry.getKey(), entry.getValue());
    }
    context.setRequestCharacterEncoding(webxml.getRequestCharacterEncoding());
    // Name is just used for ordering
    for (ContextResourceEnvRef resource : webxml.getResourceEnvRefs().values()) {
        context.getNamingResources().addResourceEnvRef(resource);
    }
    for (ContextResource resource : webxml.getResourceRefs().values()) {
        context.getNamingResources().addResource(resource);
    }
    context.setResponseCharacterEncoding(webxml.getResponseCharacterEncoding());
    boolean allAuthenticatedUsersIsAppRole = webxml.getSecurityRoles().contains(SecurityConstraint.ROLE_ALL_AUTHENTICATED_USERS);
    for (SecurityConstraint constraint : webxml.getSecurityConstraints()) {
        if (allAuthenticatedUsersIsAppRole) {
            constraint.treatAllAuthenticatedUsersAsApplicationRole();
        }
        context.addConstraint(constraint);
    }
    for (String role : webxml.getSecurityRoles()) {
        context.addSecurityRole(role);
    }
    for (ContextService service : webxml.getServiceRefs().values()) {
        context.getNamingResources().addService(service);
    }
    for (ServletDef servlet : webxml.getServlets().values()) {
        Wrapper wrapper = context.createWrapper();
        if (servlet.getLoadOnStartup() != null) {
            wrapper.setLoadOnStartup(servlet.getLoadOnStartup().intValue());
        }
        if (servlet.getEnabled() != null) {
            wrapper.setEnabled(servlet.getEnabled().booleanValue());
        }
        wrapper.setName(servlet.getServletName());
        Map<String, String> params = servlet.getParameterMap();
        for (Entry<String, String> entry : params.entrySet()) {
            wrapper.addInitParameter(entry.getKey(), entry.getValue());
        }
        wrapper.setRunAs(servlet.getRunAs());
        Set<SecurityRoleRef> roleRefs = servlet.getSecurityRoleRefs();
        for (SecurityRoleRef roleRef : roleRefs) {
            wrapper.addSecurityReference(roleRef.getName(), roleRef.getLink());
        }
        wrapper.setServletClass(servlet.getServletClass());
        MultipartDef multipartdef = servlet.getMultipartDef();
        if (multipartdef != null) {
            long maxFileSize = -1;
            long maxRequestSize = -1;
            int fileSizeThreshold = 0;
            if (null != multipartdef.getMaxFileSize()) {
                maxFileSize = Long.parseLong(multipartdef.getMaxFileSize());
            }
            if (null != multipartdef.getMaxRequestSize()) {
                maxRequestSize = Long.parseLong(multipartdef.getMaxRequestSize());
            }
            if (null != multipartdef.getFileSizeThreshold()) {
                fileSizeThreshold = Integer.parseInt(multipartdef.getFileSizeThreshold());
            }
            wrapper.setMultipartConfigElement(new MultipartConfigElement(multipartdef.getLocation(), maxFileSize, maxRequestSize, fileSizeThreshold));
        }
        if (servlet.getAsyncSupported() != null) {
            wrapper.setAsyncSupported(servlet.getAsyncSupported().booleanValue());
        }
        wrapper.setOverridable(servlet.isOverridable());
        context.addChild(wrapper);
    }
    for (Entry<String, String> entry : webxml.getServletMappings().entrySet()) {
        context.addServletMappingDecoded(entry.getKey(), entry.getValue());
    }
    SessionConfig sessionConfig = webxml.getSessionConfig();
    if (sessionConfig != null) {
        if (sessionConfig.getSessionTimeout() != null) {
            context.setSessionTimeout(sessionConfig.getSessionTimeout().intValue());
        }
        SessionCookieConfig scc = context.getServletContext().getSessionCookieConfig();
        scc.setName(sessionConfig.getCookieName());
        Map<String, String> attributes = sessionConfig.getCookieAttributes();
        for (Map.Entry<String, String> attribute : attributes.entrySet()) {
            scc.setAttribute(attribute.getKey(), attribute.getValue());
        }
        if (sessionConfig.getSessionTrackingModes().size() > 0) {
            context.getServletContext().setSessionTrackingModes(sessionConfig.getSessionTrackingModes());
        }
    }
    for (String welcomeFile : webxml.getWelcomeFiles()) {
        /*
             * The following will result in a welcome file of "" so don't add
             * that to the context
             * <welcome-file-list>
             *   <welcome-file/>
             * </welcome-file-list>
             */
        if (welcomeFile != null && welcomeFile.length() > 0) {
            context.addWelcomeFile(welcomeFile);
        }
    }
    // Do this last as it depends on servlets
    for (JspPropertyGroup jspPropertyGroup : webxml.getJspPropertyGroups()) {
        String jspServletName = context.findServletMapping("*.jsp");
        if (jspServletName == null) {
            jspServletName = "jsp";
        }
        if (context.findChild(jspServletName) != null) {
            for (String urlPattern : jspPropertyGroup.getUrlPatterns()) {
                context.addServletMappingDecoded(urlPattern, jspServletName, true);
            }
        } else {
            if (log.isDebugEnabled()) {
                for (String urlPattern : jspPropertyGroup.getUrlPatterns()) {
                    log.debug("Skipping " + urlPattern + " , no servlet " + jspServletName);
                }
            }
        }
    }
    for (Entry<String, String> entry : webxml.getPostConstructMethods().entrySet()) {
        context.addPostConstructMethod(entry.getKey(), entry.getValue());
    }
    for (Entry<String, String> entry : webxml.getPreDestroyMethods().entrySet()) {
        context.addPreDestroyMethod(entry.getKey(), entry.getValue());
    }
}
Also used : ContextService(org.apache.tomcat.util.descriptor.web.ContextService) ErrorPage(org.apache.tomcat.util.descriptor.web.ErrorPage) SessionConfig(org.apache.tomcat.util.descriptor.web.SessionConfig) SecurityRoleRef(org.apache.tomcat.util.descriptor.web.SecurityRoleRef) FilterMap(org.apache.tomcat.util.descriptor.web.FilterMap) SecurityConstraint(org.apache.tomcat.util.descriptor.web.SecurityConstraint) JspPropertyGroup(org.apache.tomcat.util.descriptor.web.JspPropertyGroup) MessageDestinationRef(org.apache.tomcat.util.descriptor.web.MessageDestinationRef) ContextLocalEjb(org.apache.tomcat.util.descriptor.web.ContextLocalEjb) MultipartDef(org.apache.tomcat.util.descriptor.web.MultipartDef) SessionCookieConfig(jakarta.servlet.SessionCookieConfig) ContextEnvironment(org.apache.tomcat.util.descriptor.web.ContextEnvironment) Wrapper(org.apache.catalina.Wrapper) FilterDef(org.apache.tomcat.util.descriptor.web.FilterDef) ServletDef(org.apache.tomcat.util.descriptor.web.ServletDef) ContextEjb(org.apache.tomcat.util.descriptor.web.ContextEjb) SecurityConstraint(org.apache.tomcat.util.descriptor.web.SecurityConstraint) ContextResource(org.apache.tomcat.util.descriptor.web.ContextResource) MultipartConfigElement(jakarta.servlet.MultipartConfigElement) ContextResourceEnvRef(org.apache.tomcat.util.descriptor.web.ContextResourceEnvRef) FilterMap(org.apache.tomcat.util.descriptor.web.FilterMap) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap)

Example 7 with ContextResource

use of org.apache.tomcat.util.descriptor.web.ContextResource in project tomcat by apache.

the class WebAnnotationSet method addResource.

protected static void addResource(Context context, Resource annotation, String defaultName, Class<?> defaultType) {
    String name = getName(annotation, defaultName);
    String type = getType(annotation, defaultType);
    if (type.equals("java.lang.String") || type.equals("java.lang.Character") || type.equals("java.lang.Integer") || type.equals("java.lang.Boolean") || type.equals("java.lang.Double") || type.equals("java.lang.Byte") || type.equals("java.lang.Short") || type.equals("java.lang.Long") || type.equals("java.lang.Float")) {
        // env-entry element
        ContextEnvironment resource = new ContextEnvironment();
        resource.setName(name);
        resource.setType(type);
        resource.setDescription(annotation.description());
        resource.setProperty(MAPPED_NAME_PROPERTY, annotation.mappedName());
        resource.setLookupName(annotation.lookup());
        context.getNamingResources().addEnvironment(resource);
    } else if (type.equals("javax.xml.rpc.Service")) {
        // service-ref element
        ContextService service = new ContextService();
        service.setName(name);
        service.setWsdlfile(annotation.mappedName());
        service.setType(type);
        service.setDescription(annotation.description());
        service.setLookupName(annotation.lookup());
        context.getNamingResources().addService(service);
    } else if (type.equals("javax.sql.DataSource") || type.equals("javax.jms.ConnectionFactory") || type.equals("javax.jms.QueueConnectionFactory") || type.equals("javax.jms.TopicConnectionFactory") || type.equals("jakarta.mail.Session") || type.equals("java.net.URL") || type.equals("javax.resource.cci.ConnectionFactory") || type.equals("org.omg.CORBA_2_3.ORB") || type.endsWith("ConnectionFactory")) {
        // resource-ref element
        ContextResource resource = new ContextResource();
        resource.setName(name);
        resource.setType(type);
        if (annotation.authenticationType() == Resource.AuthenticationType.CONTAINER) {
            resource.setAuth("Container");
        } else if (annotation.authenticationType() == Resource.AuthenticationType.APPLICATION) {
            resource.setAuth("Application");
        }
        resource.setScope(annotation.shareable() ? "Shareable" : "Unshareable");
        resource.setProperty(MAPPED_NAME_PROPERTY, annotation.mappedName());
        resource.setDescription(annotation.description());
        resource.setLookupName(annotation.lookup());
        context.getNamingResources().addResource(resource);
    } else if (type.equals("javax.jms.Queue") || type.equals("javax.jms.Topic")) {
        // message-destination-ref
        MessageDestinationRef resource = new MessageDestinationRef();
        resource.setName(name);
        resource.setType(type);
        resource.setUsage(annotation.mappedName());
        resource.setDescription(annotation.description());
        resource.setLookupName(annotation.lookup());
        context.getNamingResources().addMessageDestinationRef(resource);
    } else {
        /*
             * General case. Also used for:
             * - javax.resource.cci.InteractionSpec
             * - jakarta.transaction.UserTransaction
             */
        // resource-env-ref
        ContextResourceEnvRef resource = new ContextResourceEnvRef();
        resource.setName(name);
        resource.setType(type);
        resource.setProperty(MAPPED_NAME_PROPERTY, annotation.mappedName());
        resource.setDescription(annotation.description());
        resource.setLookupName(annotation.lookup());
        context.getNamingResources().addResourceEnvRef(resource);
    }
}
Also used : ContextEnvironment(org.apache.tomcat.util.descriptor.web.ContextEnvironment) MessageDestinationRef(org.apache.tomcat.util.descriptor.web.MessageDestinationRef) ContextService(org.apache.tomcat.util.descriptor.web.ContextService) ContextResourceEnvRef(org.apache.tomcat.util.descriptor.web.ContextResourceEnvRef) ContextResource(org.apache.tomcat.util.descriptor.web.ContextResource)

Example 8 with ContextResource

use of org.apache.tomcat.util.descriptor.web.ContextResource in project tomcat by apache.

the class NamingResourcesImpl method removeResource.

/**
 * Remove any resource reference with the specified name.
 *
 * @param name Name of the resource reference to remove
 */
@Override
public void removeResource(String name) {
    entries.remove(name);
    ContextResource resource = null;
    synchronized (resources) {
        resource = resources.remove(name);
    }
    if (resource != null) {
        support.firePropertyChange("resource", resource, null);
        // De-register with JMX
        if (resourceRequireExplicitRegistration) {
            try {
                MBeanUtils.destroyMBean(resource);
            } catch (Exception e) {
                log.warn(sm.getString("namingResources.mbeanDestroyFail", resource.getName()), e);
            }
        }
        resource.setNamingResources(null);
    }
}
Also used : NamingException(javax.naming.NamingException) LifecycleException(org.apache.catalina.LifecycleException) InvocationTargetException(java.lang.reflect.InvocationTargetException) ContextResource(org.apache.tomcat.util.descriptor.web.ContextResource)

Example 9 with ContextResource

use of org.apache.tomcat.util.descriptor.web.ContextResource in project tomcat by apache.

the class NamingResourcesImpl method destroyInternal.

@Override
protected void destroyInternal() throws LifecycleException {
    // Set this before we de-register currently known naming resources to
    // avoid timing issues. Duplication de-registration is not an issue.
    resourceRequireExplicitRegistration = false;
    // Destroy in reverse order to create, although it should not matter
    for (ContextResourceLink crl : resourceLinks.values()) {
        try {
            MBeanUtils.destroyMBean(crl);
        } catch (Exception e) {
            log.warn(sm.getString("namingResources.mbeanDestroyFail", crl.getName()), e);
        }
    }
    for (ContextEnvironment ce : envs.values()) {
        try {
            MBeanUtils.destroyMBean(ce);
        } catch (Exception e) {
            log.warn(sm.getString("namingResources.mbeanDestroyFail", ce.getName()), e);
        }
    }
    for (ContextResource cr : resources.values()) {
        try {
            MBeanUtils.destroyMBean(cr);
        } catch (Exception e) {
            log.warn(sm.getString("namingResources.mbeanDestroyFail", cr.getName()), e);
        }
    }
    super.destroyInternal();
}
Also used : ContextEnvironment(org.apache.tomcat.util.descriptor.web.ContextEnvironment) ContextResourceLink(org.apache.tomcat.util.descriptor.web.ContextResourceLink) NamingException(javax.naming.NamingException) LifecycleException(org.apache.catalina.LifecycleException) InvocationTargetException(java.lang.reflect.InvocationTargetException) ContextResource(org.apache.tomcat.util.descriptor.web.ContextResource)

Example 10 with ContextResource

use of org.apache.tomcat.util.descriptor.web.ContextResource in project tomcat by apache.

the class TestNamingContext method testListBindings.

@Test
public void testListBindings() throws Exception {
    Tomcat tomcat = getTomcatInstance();
    tomcat.enableNaming();
    // No file system docBase required
    org.apache.catalina.Context ctx = tomcat.addContext("", null);
    // Create the resource
    ContextResource cr = new ContextResource();
    cr.setName("list/foo");
    cr.setType("org.apache.naming.resources.TesterObject");
    cr.setProperty("factory", "org.apache.naming.resources.TesterFactory");
    ctx.getNamingResources().addResource(cr);
    // Map the test Servlet
    Bug23950Servlet bug23950Servlet = new Bug23950Servlet();
    Tomcat.addServlet(ctx, "bug23950Servlet", bug23950Servlet);
    ctx.addServletMappingDecoded("/", "bug23950Servlet");
    tomcat.start();
    ByteChunk bc = getUrl("http://localhost:" + getPort() + "/");
    Assert.assertEquals("org.apache.naming.resources.TesterObject", bc.toString());
}
Also used : Tomcat(org.apache.catalina.startup.Tomcat) ByteChunk(org.apache.tomcat.util.buf.ByteChunk) ContextResource(org.apache.tomcat.util.descriptor.web.ContextResource) TomcatBaseTest(org.apache.catalina.startup.TomcatBaseTest) Test(org.junit.Test)

Aggregations

ContextResource (org.apache.tomcat.util.descriptor.web.ContextResource)28 NamingResourcesImpl (org.apache.catalina.deploy.NamingResourcesImpl)10 ContextEnvironment (org.apache.tomcat.util.descriptor.web.ContextEnvironment)9 NamingException (javax.naming.NamingException)7 ContextResourceLink (org.apache.tomcat.util.descriptor.web.ContextResourceLink)7 ContextResourceEnvRef (org.apache.tomcat.util.descriptor.web.ContextResourceEnvRef)6 ContextEjb (org.apache.tomcat.util.descriptor.web.ContextEjb)5 ContextService (org.apache.tomcat.util.descriptor.web.ContextService)5 InvocationTargetException (java.lang.reflect.InvocationTargetException)3 ArrayList (java.util.ArrayList)3 LifecycleException (org.apache.catalina.LifecycleException)3 Tomcat (org.apache.catalina.startup.Tomcat)3 ByteChunk (org.apache.tomcat.util.buf.ByteChunk)3 ObjectName (javax.management.ObjectName)2 RuntimeOperationsException (javax.management.RuntimeOperationsException)2 Context (javax.naming.Context)2 Reference (javax.naming.Reference)2 StringRefAddr (javax.naming.StringRefAddr)2 EntityManagerFactory (javax.persistence.EntityManagerFactory)2 Server (org.apache.catalina.Server)2