Search in sources :

Example 6 with JBossServletMetaData

use of org.jboss.metadata.web.jboss.JBossServletMetaData in project wildfly by wildfly.

the class JaxrsIntegrationProcessor method deploy.

@Override
public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException {
    final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();
    if (!JaxrsDeploymentMarker.isJaxrsDeployment(deploymentUnit)) {
        return;
    }
    if (!DeploymentTypeMarker.isType(DeploymentType.WAR, deploymentUnit)) {
        return;
    }
    final DeploymentUnit parent = deploymentUnit.getParent() == null ? deploymentUnit : deploymentUnit.getParent();
    final WarMetaData warMetaData = deploymentUnit.getAttachment(WarMetaData.ATTACHMENT_KEY);
    final JBossWebMetaData webdata = warMetaData.getMergedJBossWebMetaData();
    final ResteasyDeploymentData resteasy = deploymentUnit.getAttachment(JaxrsAttachments.RESTEASY_DEPLOYMENT_DATA);
    if (resteasy == null)
        return;
    deploymentUnit.getDeploymentSubsystemModel(JaxrsExtension.SUBSYSTEM_NAME);
    //remove the resteasy.scan parameter
    //because it is not needed
    final List<ParamValueMetaData> params = webdata.getContextParams();
    boolean entityExpandEnabled = false;
    if (params != null) {
        Iterator<ParamValueMetaData> it = params.iterator();
        while (it.hasNext()) {
            final ParamValueMetaData param = it.next();
            if (param.getParamName().equals(RESTEASY_SCAN)) {
                it.remove();
            } else if (param.getParamName().equals(RESTEASY_SCAN_RESOURCES)) {
                it.remove();
            } else if (param.getParamName().equals(RESTEASY_SCAN_PROVIDERS)) {
                it.remove();
            } else if (param.getParamName().equals(ResteasyContextParameters.RESTEASY_EXPAND_ENTITY_REFERENCES)) {
                entityExpandEnabled = true;
            }
        }
    }
    //don't expand entity references by default
    if (!entityExpandEnabled) {
        setContextParameter(webdata, ResteasyContextParameters.RESTEASY_EXPAND_ENTITY_REFERENCES, "false");
    }
    final Map<ModuleIdentifier, ResteasyDeploymentData> attachmentMap = parent.getAttachment(JaxrsAttachments.ADDITIONAL_RESTEASY_DEPLOYMENT_DATA);
    final List<ResteasyDeploymentData> additionalData = new ArrayList<ResteasyDeploymentData>();
    final ModuleSpecification moduleSpec = deploymentUnit.getAttachment(Attachments.MODULE_SPECIFICATION);
    if (moduleSpec != null && attachmentMap != null) {
        final Set<ModuleIdentifier> identifiers = new HashSet<ModuleIdentifier>();
        for (ModuleDependency dep : moduleSpec.getAllDependencies()) {
            //make sure we don't double up
            if (!identifiers.contains(dep.getIdentifier())) {
                identifiers.add(dep.getIdentifier());
                if (attachmentMap.containsKey(dep.getIdentifier())) {
                    additionalData.add(attachmentMap.get(dep.getIdentifier()));
                }
            }
        }
        resteasy.merge(additionalData);
    }
    if (!resteasy.getScannedResourceClasses().isEmpty()) {
        StringBuffer buf = null;
        for (String resource : resteasy.getScannedResourceClasses()) {
            if (buf == null) {
                buf = new StringBuffer();
                buf.append(resource);
            } else {
                buf.append(",").append(resource);
            }
        }
        String resources = buf.toString();
        JAXRS_LOGGER.debugf("Adding JAX-RS resource classes: %s", resources);
        setContextParameter(webdata, ResteasyContextParameters.RESTEASY_SCANNED_RESOURCES, resources);
    }
    if (!resteasy.getScannedProviderClasses().isEmpty()) {
        StringBuffer buf = null;
        for (String provider : resteasy.getScannedProviderClasses()) {
            if (buf == null) {
                buf = new StringBuffer();
                buf.append(provider);
            } else {
                buf.append(",").append(provider);
            }
        }
        String providers = buf.toString();
        JAXRS_LOGGER.debugf("Adding JAX-RS provider classes: %s", providers);
        setContextParameter(webdata, ResteasyContextParameters.RESTEASY_SCANNED_PROVIDERS, providers);
    }
    if (!resteasy.getScannedJndiComponentResources().isEmpty()) {
        StringBuffer buf = null;
        for (String resource : resteasy.getScannedJndiComponentResources()) {
            if (buf == null) {
                buf = new StringBuffer();
                buf.append(resource);
            } else {
                buf.append(",").append(resource);
            }
        }
        String providers = buf.toString();
        JAXRS_LOGGER.debugf("Adding JAX-RS jndi component resource classes: %s", providers);
        setContextParameter(webdata, ResteasyContextParameters.RESTEASY_SCANNED_JNDI_RESOURCES, providers);
    }
    if (!resteasy.isUnwrappedExceptionsParameterSet()) {
        setContextParameter(webdata, ResteasyContextParameters.RESTEASY_UNWRAPPED_EXCEPTIONS, "javax.ejb.EJBException");
    }
    if (resteasy.hasBootClasses() || resteasy.isDispatcherCreated())
        return;
    // ignore any non-annotated Application class that doesn't have a servlet mapping
    Set<Class<? extends Application>> applicationClassSet = new HashSet<>();
    for (Class<? extends Application> clazz : resteasy.getScannedApplicationClasses()) {
        if (clazz.isAnnotationPresent(ApplicationPath.class) || servletMappingsExist(webdata, clazz.getName())) {
            applicationClassSet.add(clazz);
        }
    }
    // add default servlet
    if (applicationClassSet.size() == 0) {
        JBossServletMetaData servlet = new JBossServletMetaData();
        servlet.setName(JAX_RS_SERVLET_NAME);
        servlet.setServletClass(HttpServlet30Dispatcher.class.getName());
        servlet.setAsyncSupported(true);
        addServlet(webdata, servlet);
        setServletMappingPrefix(webdata, JAX_RS_SERVLET_NAME, servlet);
    } else {
        for (Class<? extends Application> applicationClass : applicationClassSet) {
            String servletName = null;
            servletName = applicationClass.getName();
            JBossServletMetaData servlet = new JBossServletMetaData();
            // must load on startup for services like JSAPI to work
            servlet.setLoadOnStartup("" + 0);
            servlet.setName(servletName);
            servlet.setServletClass(HttpServlet30Dispatcher.class.getName());
            servlet.setAsyncSupported(true);
            setServletInitParam(servlet, SERVLET_INIT_PARAM, applicationClass.getName());
            addServlet(webdata, servlet);
            if (!servletMappingsExist(webdata, servletName)) {
                try {
                    //no mappings, add our own
                    List<String> patterns = new ArrayList<String>();
                    //for some reason the spec requires this to be decoded
                    String pathValue = URLDecoder.decode(applicationClass.getAnnotation(ApplicationPath.class).value().trim(), "UTF-8");
                    if (!pathValue.startsWith("/")) {
                        pathValue = "/" + pathValue;
                    }
                    String prefix = pathValue;
                    if (pathValue.endsWith("/")) {
                        pathValue += "*";
                    } else {
                        pathValue += "/*";
                    }
                    patterns.add(pathValue);
                    setServletInitParam(servlet, "resteasy.servlet.mapping.prefix", prefix);
                    ServletMappingMetaData mapping = new ServletMappingMetaData();
                    mapping.setServletName(servletName);
                    mapping.setUrlPatterns(patterns);
                    if (webdata.getServletMappings() == null) {
                        webdata.setServletMappings(new ArrayList<ServletMappingMetaData>());
                    }
                    webdata.getServletMappings().add(mapping);
                } catch (UnsupportedEncodingException e) {
                    throw new RuntimeException(e);
                }
            } else {
                setServletMappingPrefix(webdata, servletName, servlet);
            }
        }
    }
    if (webdata.getServletMappings() == null || webdata.getServletMappings().isEmpty()) {
        JAXRS_LOGGER.noServletDeclaration(deploymentUnit.getName());
    }
}
Also used : JBossWebMetaData(org.jboss.metadata.web.jboss.JBossWebMetaData) ModuleDependency(org.jboss.as.server.deployment.module.ModuleDependency) JBossServletMetaData(org.jboss.metadata.web.jboss.JBossServletMetaData) WarMetaData(org.jboss.as.web.common.WarMetaData) ArrayList(java.util.ArrayList) ApplicationPath(javax.ws.rs.ApplicationPath) ModuleIdentifier(org.jboss.modules.ModuleIdentifier) HashSet(java.util.HashSet) ParamValueMetaData(org.jboss.metadata.javaee.spec.ParamValueMetaData) UnsupportedEncodingException(java.io.UnsupportedEncodingException) ServletMappingMetaData(org.jboss.metadata.web.spec.ServletMappingMetaData) HttpServlet30Dispatcher(org.jboss.resteasy.plugins.server.servlet.HttpServlet30Dispatcher) ModuleSpecification(org.jboss.as.server.deployment.module.ModuleSpecification) DeploymentUnit(org.jboss.as.server.deployment.DeploymentUnit) Application(javax.ws.rs.core.Application)

Example 7 with JBossServletMetaData

use of org.jboss.metadata.web.jboss.JBossServletMetaData in project wildfly by wildfly.

the class UndertowDeploymentProcessor method processManagement.

//todo move to UndertowDeploymentService and use all registered servlets from Deployment instead of just one found by metadata
void processManagement(final DeploymentUnit unit, JBossWebMetaData metaData) {
    final DeploymentResourceSupport deploymentResourceSupport = unit.getAttachment(Attachments.DEPLOYMENT_RESOURCE_SUPPORT);
    for (final JBossServletMetaData servlet : metaData.getServlets()) {
        try {
            final String name = servlet.getName();
            final ModelNode node = deploymentResourceSupport.getDeploymentSubModel(UndertowExtension.SUBSYSTEM_NAME, PathElement.pathElement("servlet", name));
            node.get("servlet-class").set(servlet.getServletClass());
            node.get("servlet-name").set(servlet.getServletName());
        } catch (Exception e) {
            // Should a failure in creating the mgmt view also make to the deployment to fail?
            continue;
        }
    }
}
Also used : DeploymentResourceSupport(org.jboss.as.server.deployment.DeploymentResourceSupport) JBossServletMetaData(org.jboss.metadata.web.jboss.JBossServletMetaData) ModelNode(org.jboss.dmr.ModelNode) DeploymentUnitProcessingException(org.jboss.as.server.deployment.DeploymentUnitProcessingException) MalformedURLException(java.net.MalformedURLException)

Example 8 with JBossServletMetaData

use of org.jboss.metadata.web.jboss.JBossServletMetaData in project wildfly by wildfly.

the class UndertowDeploymentProcessor method processDeployment.

private void processDeployment(final WarMetaData warMetaData, final DeploymentUnit deploymentUnit, final ServiceTarget serviceTarget, final String deploymentName, final String hostName, final String serverInstanceName) throws DeploymentUnitProcessingException {
    ResourceRoot deploymentResourceRoot = deploymentUnit.getAttachment(Attachments.DEPLOYMENT_ROOT);
    final VirtualFile deploymentRoot = deploymentResourceRoot.getRoot();
    final Module module = deploymentUnit.getAttachment(Attachments.MODULE);
    if (module == null) {
        throw new DeploymentUnitProcessingException(UndertowLogger.ROOT_LOGGER.failedToResolveModule(deploymentUnit));
    }
    final JBossWebMetaData metaData = warMetaData.getMergedJBossWebMetaData();
    final List<SetupAction> setupActions = deploymentUnit.getAttachmentList(org.jboss.as.ee.component.Attachments.WEB_SETUP_ACTIONS);
    ScisMetaData scisMetaData = deploymentUnit.getAttachment(ScisMetaData.ATTACHMENT_KEY);
    final Set<ServiceName> dependentComponents = new HashSet<>();
    // see AS7-2077
    // basically we want to ignore components that have failed for whatever reason
    // if they are important they will be picked up when the web deployment actually starts
    final List<ServiceName> components = deploymentUnit.getAttachmentList(WebComponentDescription.WEB_COMPONENTS);
    final Set<ServiceName> failed = deploymentUnit.getAttachment(org.jboss.as.ee.component.Attachments.FAILED_COMPONENTS);
    for (final ServiceName component : components) {
        if (!failed.contains(component)) {
            dependentComponents.add(component);
        }
    }
    String servletContainerName = metaData.getServletContainerName();
    if (servletContainerName == null) {
        servletContainerName = defaultContainer;
    }
    boolean componentRegistryExists = true;
    ComponentRegistry componentRegistry = deploymentUnit.getAttachment(org.jboss.as.ee.component.Attachments.COMPONENT_REGISTRY);
    if (componentRegistry == null) {
        componentRegistryExists = false;
        //we do this to avoid lots of other null checks
        //this will only happen if the EE subsystem is not installed
        componentRegistry = new ComponentRegistry(null);
    }
    final WebInjectionContainer injectionContainer = new WebInjectionContainer(module.getClassLoader(), componentRegistry);
    String jaccContextId = metaData.getJaccContextID();
    if (jaccContextId == null) {
        jaccContextId = deploymentUnit.getName();
    }
    if (deploymentUnit.getParent() != null) {
        jaccContextId = deploymentUnit.getParent().getName() + "!" + jaccContextId;
    }
    final String pathName = pathNameOfDeployment(deploymentUnit, metaData);
    boolean securityEnabled = deploymentUnit.hasAttachment(SecurityAttachments.SECURITY_ENABLED);
    String metaDataSecurityDomain = metaData.getSecurityDomain();
    if (metaDataSecurityDomain == null) {
        metaDataSecurityDomain = getJBossAppSecurityDomain(deploymentUnit);
    }
    if (metaDataSecurityDomain != null) {
        metaDataSecurityDomain = metaDataSecurityDomain.trim();
    }
    final String securityDomain;
    if (securityEnabled) {
        securityDomain = metaDataSecurityDomain == null ? defaultSecurityDomain : SecurityUtil.unprefixSecurityDomain(metaDataSecurityDomain);
    } else {
        securityDomain = null;
    }
    final Set<ServiceName> additionalDependencies = new HashSet<>();
    for (final SetupAction setupAction : setupActions) {
        Set<ServiceName> dependencies = setupAction.dependencies();
        if (dependencies != null) {
            additionalDependencies.addAll(dependencies);
        }
    }
    SharedSessionManagerConfig sharedSessionManagerConfig = deploymentUnit.getParent() != null ? deploymentUnit.getParent().getAttachment(UndertowAttachments.SHARED_SESSION_MANAGER_CONFIG) : null;
    if (!deploymentResourceRoot.isUsePhysicalCodeSource()) {
        try {
            deploymentUnit.addToAttachmentList(ServletContextAttribute.ATTACHMENT_KEY, new ServletContextAttribute(Constants.CODE_SOURCE_ATTRIBUTE_NAME, deploymentRoot.toURL()));
        } catch (MalformedURLException e) {
            throw new DeploymentUnitProcessingException(e);
        }
    }
    deploymentUnit.addToAttachmentList(ServletContextAttribute.ATTACHMENT_KEY, new ServletContextAttribute(Constants.PERMISSION_COLLECTION_ATTRIBUTE_NAME, deploymentUnit.getAttachment(Attachments.MODULE_PERMISSIONS)));
    additionalDependencies.addAll(warMetaData.getAdditionalDependencies());
    final ServiceName hostServiceName = UndertowService.virtualHostName(serverInstanceName, hostName);
    final ServiceName deploymentServiceName = UndertowService.deploymentServiceName(serverInstanceName, hostName, pathName);
    TldsMetaData tldsMetaData = deploymentUnit.getAttachment(TldsMetaData.ATTACHMENT_KEY);
    UndertowDeploymentInfoService undertowDeploymentInfoService = UndertowDeploymentInfoService.builder().setAttributes(deploymentUnit.getAttachmentList(ServletContextAttribute.ATTACHMENT_KEY)).setContextPath(pathName).setDeploymentName(//todo: is this deployment name concept really applicable?
    deploymentName).setDeploymentRoot(deploymentRoot).setMergedMetaData(warMetaData.getMergedJBossWebMetaData()).setModule(module).setScisMetaData(scisMetaData).setJaccContextId(jaccContextId).setSecurityDomain(securityDomain).setSharedTlds(tldsMetaData == null ? Collections.<TldMetaData>emptyList() : tldsMetaData.getSharedTlds(deploymentUnit)).setTldsMetaData(tldsMetaData).setSetupActions(setupActions).setSharedSessionManagerConfig(sharedSessionManagerConfig).setOverlays(warMetaData.getOverlays()).setExpressionFactoryWrappers(deploymentUnit.getAttachmentList(ExpressionFactoryWrapper.ATTACHMENT_KEY)).setPredicatedHandlers(deploymentUnit.getAttachment(UndertowHandlersDeploymentProcessor.PREDICATED_HANDLERS)).setInitialHandlerChainWrappers(deploymentUnit.getAttachmentList(UndertowAttachments.UNDERTOW_INITIAL_HANDLER_CHAIN_WRAPPERS)).setInnerHandlerChainWrappers(deploymentUnit.getAttachmentList(UndertowAttachments.UNDERTOW_INNER_HANDLER_CHAIN_WRAPPERS)).setOuterHandlerChainWrappers(deploymentUnit.getAttachmentList(UndertowAttachments.UNDERTOW_OUTER_HANDLER_CHAIN_WRAPPERS)).setThreadSetupActions(deploymentUnit.getAttachmentList(UndertowAttachments.UNDERTOW_THREAD_SETUP_ACTIONS)).setServletExtensions(deploymentUnit.getAttachmentList(UndertowAttachments.UNDERTOW_SERVLET_EXTENSIONS)).setExplodedDeployment(ExplodedDeploymentMarker.isExplodedDeployment(deploymentUnit)).setWebSocketDeploymentInfo(deploymentUnit.getAttachment(UndertowAttachments.WEB_SOCKET_DEPLOYMENT_INFO)).setTempDir(warMetaData.getTempDir()).setExternalResources(deploymentUnit.getAttachmentList(UndertowAttachments.EXTERNAL_RESOURCES)).setAllowSuspendedRequests(deploymentUnit.getAttachmentList(UndertowAttachments.ALLOW_REQUEST_WHEN_SUSPENDED)).createUndertowDeploymentInfoService();
    final ServiceName deploymentInfoServiceName = deploymentServiceName.append(UndertowDeploymentInfoService.SERVICE_NAME);
    ServiceBuilder<DeploymentInfo> infoBuilder = serviceTarget.addService(deploymentInfoServiceName, undertowDeploymentInfoService).addDependency(UndertowService.SERVLET_CONTAINER.append(servletContainerName), ServletContainerService.class, undertowDeploymentInfoService.getContainer()).addDependency(UndertowService.UNDERTOW, UndertowService.class, undertowDeploymentInfoService.getUndertowService()).addDependency(hostServiceName, Host.class, undertowDeploymentInfoService.getHost()).addDependency(ServerEnvironmentService.SERVICE_NAME, ServerEnvironment.class, undertowDeploymentInfoService.getServerEnvironmentInjectedValue()).addDependency(SuspendController.SERVICE_NAME, SuspendController.class, undertowDeploymentInfoService.getSuspendControllerInjectedValue()).addDependencies(additionalDependencies);
    if (securityDomain != null) {
        if (knownSecurityDomain.test(securityDomain)) {
            infoBuilder.addDependency(deploymentUnit.getAttachment(Attachments.CAPABILITY_SERVICE_SUPPORT).getCapabilityServiceName(ApplicationSecurityDomainDefinition.APPLICATION_SECURITY_DOMAIN_CAPABILITY, securityDomain), BiFunction.class, undertowDeploymentInfoService.getSecurityFunctionInjector());
        } else {
            infoBuilder.addDependency(SecurityDomainService.SERVICE_NAME.append(securityDomain), SecurityDomainContext.class, undertowDeploymentInfoService.getSecurityDomainContextValue());
        }
    }
    if (RequestControllerActivationMarker.isRequestControllerEnabled(deploymentUnit)) {
        String topLevelName;
        if (deploymentUnit.getParent() == null) {
            topLevelName = deploymentUnit.getName();
        } else {
            topLevelName = deploymentUnit.getParent().getName();
        }
        infoBuilder.addDependency(ControlPointService.serviceName(topLevelName, UndertowExtension.SUBSYSTEM_NAME), ControlPoint.class, undertowDeploymentInfoService.getControlPointInjectedValue());
    }
    final Set<String> seenExecutors = new HashSet<String>();
    if (metaData.getExecutorName() != null) {
        final InjectedValue<Executor> executor = new InjectedValue<Executor>();
        infoBuilder.addDependency(IOServices.WORKER.append(metaData.getExecutorName()), Executor.class, executor);
        undertowDeploymentInfoService.addInjectedExecutor(metaData.getExecutorName(), executor);
        seenExecutors.add(metaData.getExecutorName());
    }
    if (metaData.getServlets() != null) {
        for (JBossServletMetaData servlet : metaData.getServlets()) {
            if (servlet.getExecutorName() != null && !seenExecutors.contains(servlet.getExecutorName())) {
                final InjectedValue<Executor> executor = new InjectedValue<Executor>();
                infoBuilder.addDependency(IOServices.WORKER.append(servlet.getExecutorName()), Executor.class, executor);
                undertowDeploymentInfoService.addInjectedExecutor(servlet.getExecutorName(), executor);
                seenExecutors.add(servlet.getExecutorName());
            }
        }
    }
    if (componentRegistryExists) {
        infoBuilder.addDependency(ComponentRegistry.serviceName(deploymentUnit), ComponentRegistry.class, undertowDeploymentInfoService.getComponentRegistryInjectedValue());
    } else {
        undertowDeploymentInfoService.getComponentRegistryInjectedValue().setValue(new ImmediateValue<>(componentRegistry));
    }
    if (sharedSessionManagerConfig != null) {
        infoBuilder.addDependency(deploymentUnit.getParent().getServiceName().append(SharedSessionManagerConfig.SHARED_SESSION_MANAGER_SERVICE_NAME), SessionManagerFactory.class, undertowDeploymentInfoService.getSessionManagerFactoryInjector());
        infoBuilder.addDependency(deploymentUnit.getParent().getServiceName().append(SharedSessionManagerConfig.SHARED_SESSION_IDENTIFIER_CODEC_SERVICE_NAME), SessionIdentifierCodec.class, undertowDeploymentInfoService.getSessionIdentifierCodecInjector());
    } else {
        CapabilityServiceSupport support = deploymentUnit.getAttachment(Attachments.CAPABILITY_SERVICE_SUPPORT);
        ServiceName sessionManagerFactoryServiceName = installSessionManagerFactory(support, serviceTarget, deploymentServiceName, deploymentName, module, metaData, deploymentUnit.getAttachment(UndertowAttachments.SERVLET_CONTAINER_SERVICE));
        infoBuilder.addDependency(sessionManagerFactoryServiceName, SessionManagerFactory.class, undertowDeploymentInfoService.getSessionManagerFactoryInjector());
        ServiceName sessionIdentifierCodecServiceName = installSessionIdentifierCodec(serviceTarget, deploymentServiceName, deploymentName, metaData);
        infoBuilder.addDependency(sessionIdentifierCodecServiceName, SessionIdentifierCodec.class, undertowDeploymentInfoService.getSessionIdentifierCodecInjector());
    }
    infoBuilder.install();
    final boolean isWebappBundle = deploymentUnit.hasAttachment(Attachments.OSGI_MANIFEST);
    final UndertowDeploymentService service = new UndertowDeploymentService(injectionContainer, !isWebappBundle);
    final ServiceBuilder<UndertowDeploymentService> builder = serviceTarget.addService(deploymentServiceName, service).addDependencies(dependentComponents).addDependency(UndertowService.SERVLET_CONTAINER.append(defaultContainer), ServletContainerService.class, service.getContainer()).addDependency(hostServiceName, Host.class, service.getHost()).addDependencies(deploymentUnit.getAttachmentList(Attachments.WEB_DEPENDENCIES)).addDependency(deploymentInfoServiceName, DeploymentInfo.class, service.getDeploymentInfoInjectedValue());
    // inject the server executor which can be used by the WebDeploymentService for blocking tasks in start/stop
    // of that service
    Services.addServerExecutorDependency(builder, service.getServerExecutorInjector(), false);
    deploymentUnit.addToAttachmentList(Attachments.DEPLOYMENT_COMPLETE_SERVICES, deploymentServiceName);
    // adding JACC service
    if (securityEnabled) {
        AbstractSecurityDeployer<WarMetaData> deployer = new WarJACCDeployer();
        JaccService<WarMetaData> jaccService = deployer.deploy(deploymentUnit, jaccContextId);
        if (jaccService != null) {
            final ServiceName jaccServiceName = deploymentUnit.getServiceName().append(JaccService.SERVICE_NAME);
            ServiceBuilder<?> jaccBuilder = serviceTarget.addService(jaccServiceName, jaccService);
            if (deploymentUnit.getParent() != null) {
                // add dependency to parent policy
                final DeploymentUnit parentDU = deploymentUnit.getParent();
                jaccBuilder.addDependency(parentDU.getServiceName().append(JaccService.SERVICE_NAME), PolicyConfiguration.class, jaccService.getParentPolicyInjector());
            }
            // add dependency to web deployment service
            jaccBuilder.addDependency(deploymentServiceName);
            jaccBuilder.setInitialMode(Mode.PASSIVE).install();
        }
    }
    // OSGi web applications are activated in {@link WebContextActivationProcessor} according to bundle lifecycle changes
    if (isWebappBundle) {
        UndertowDeploymentService.ContextActivatorImpl activator = new UndertowDeploymentService.ContextActivatorImpl(builder.install());
        deploymentUnit.putAttachment(ContextActivator.ATTACHMENT_KEY, activator);
        deploymentUnit.addToAttachmentList(Attachments.BUNDLE_ACTIVE_DEPENDENCIES, deploymentServiceName);
    } else {
        builder.install();
    }
    // Process the web related mgmt information
    final DeploymentResourceSupport deploymentResourceSupport = deploymentUnit.getAttachment(Attachments.DEPLOYMENT_RESOURCE_SUPPORT);
    final ModelNode node = deploymentResourceSupport.getDeploymentSubsystemModel(UndertowExtension.SUBSYSTEM_NAME);
    node.get(DeploymentDefinition.CONTEXT_ROOT.getName()).set("".equals(pathName) ? "/" : pathName);
    node.get(DeploymentDefinition.VIRTUAL_HOST.getName()).set(hostName);
    node.get(DeploymentDefinition.SERVER.getName()).set(serverInstanceName);
    processManagement(deploymentUnit, metaData);
}
Also used : VirtualFile(org.jboss.vfs.VirtualFile) DeploymentUnitProcessingException(org.jboss.as.server.deployment.DeploymentUnitProcessingException) JBossWebMetaData(org.jboss.metadata.web.jboss.JBossWebMetaData) InjectedValue(org.jboss.msc.value.InjectedValue) MalformedURLException(java.net.MalformedURLException) JBossServletMetaData(org.jboss.metadata.web.jboss.JBossServletMetaData) WarMetaData(org.jboss.as.web.common.WarMetaData) ServletContextAttribute(org.jboss.as.web.common.ServletContextAttribute) CapabilityServiceSupport(org.jboss.as.controller.capability.CapabilityServiceSupport) ResourceRoot(org.jboss.as.server.deployment.module.ResourceRoot) SharedSessionManagerConfig(org.wildfly.extension.undertow.session.SharedSessionManagerConfig) DeploymentResourceSupport(org.jboss.as.server.deployment.DeploymentResourceSupport) Executor(java.util.concurrent.Executor) SuspendController(org.jboss.as.server.suspend.SuspendController) DeploymentInfo(io.undertow.servlet.api.DeploymentInfo) HashSet(java.util.HashSet) ServletContainerService(org.wildfly.extension.undertow.ServletContainerService) SetupAction(org.jboss.as.server.deployment.SetupAction) Host(org.wildfly.extension.undertow.Host) ServiceName(org.jboss.msc.service.ServiceName) ComponentRegistry(org.jboss.as.ee.component.ComponentRegistry) WebInjectionContainer(org.jboss.as.web.common.WebInjectionContainer) WarJACCDeployer(org.wildfly.extension.undertow.security.jacc.WarJACCDeployer) Module(org.jboss.modules.Module) ModelNode(org.jboss.dmr.ModelNode) DeploymentUnit(org.jboss.as.server.deployment.DeploymentUnit)

Example 9 with JBossServletMetaData

use of org.jboss.metadata.web.jboss.JBossServletMetaData in project wildfly by wildfly.

the class UndertowNativeWebSocketDeploymentProcessor method deploy.

@Override
public void deploy(final DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException {
    final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();
    WarMetaData metaData = deploymentUnit.getAttachment(WarMetaData.ATTACHMENT_KEY);
    if (metaData == null) {
        return;
    }
    JBossWebMetaData mergedMetaData = metaData.getMergedJBossWebMetaData();
    if (!mergedMetaData.isEnableWebSockets()) {
        return;
    }
    if (mergedMetaData.getServlets() != null) {
        for (final JBossServletMetaData servlet : mergedMetaData.getServlets()) {
            if (servlet.getServletClass() != null) {
                try {
                    Class<?> clazz = ClassLoadingUtils.loadClass(servlet.getServletClass(), deploymentUnit);
                    if (WebSocketConnectionCallback.class.isAssignableFrom(clazz)) {
                        servlet.setServletClass(WebSocketServlet.class.getName());
                        if (servlet.getInitParam() == null) {
                            servlet.setInitParam(new ArrayList<ParamValueMetaData>());
                        }
                        final ParamValueMetaData param = new ParamValueMetaData();
                        param.setParamName(WebSocketServlet.SESSION_HANDLER);
                        param.setParamValue(clazz.getName());
                        servlet.getInitParam().add(param);
                    }
                } catch (ClassNotFoundException e) {
                    throw new DeploymentUnitProcessingException(e);
                }
            }
        }
    }
}
Also used : ParamValueMetaData(org.jboss.metadata.javaee.spec.ParamValueMetaData) DeploymentUnitProcessingException(org.jboss.as.server.deployment.DeploymentUnitProcessingException) JBossWebMetaData(org.jboss.metadata.web.jboss.JBossWebMetaData) JBossServletMetaData(org.jboss.metadata.web.jboss.JBossServletMetaData) WarMetaData(org.jboss.as.web.common.WarMetaData) WebSocketServlet(io.undertow.servlet.websockets.WebSocketServlet) DeploymentUnit(org.jboss.as.server.deployment.DeploymentUnit)

Example 10 with JBossServletMetaData

use of org.jboss.metadata.web.jboss.JBossServletMetaData in project wildfly by wildfly.

the class WarJACCService method qualifyURLPatterns.

/**
     * JACC url pattern Qualified URL Pattern Names.
     *
     * The rules for qualifying a URL pattern are dependent on the rules for determining if one URL pattern matches another as
     * defined in Section 3.1.3.3, Servlet URL-Pattern Matching Rules, and are described as follows: - If the pattern is a path
     * prefix pattern, it must be qualified by every path-prefix pattern in the deployment descriptor matched by and different
     * from the pattern being qualified. The pattern must also be qualified by every exact pattern appearing in the deployment
     * descriptor that is matched by the pattern being qualified. - If the pattern is an extension pattern, it must be qualified
     * by every path-prefix pattern appearing in the deployment descriptor and every exact pattern in the deployment descriptor
     * that is matched by the pattern being qualified. - If the pattern is the default pattern, "/", it must be qualified by
     * every other pattern except the default pattern appearing in the deployment descriptor. - If the pattern is an exact
     * pattern, its qualified form must not contain any qualifying patterns.
     *
     * URL patterns are qualified by appending to their String representation, a colon separated representation of the list of
     * patterns that qualify the pattern. Duplicates must not be included in the list of qualifying patterns, and any qualifying
     * pattern matched by another qualifying pattern may5 be dropped from the list.
     *
     * Any pattern, qualified by a pattern that matches it, is overridden and made irrelevant (in the translation) by the
     * qualifying pattern. Specifically, all extension patterns and the default pattern are made irrelevant by the presence of
     * the path prefix pattern "/*" in a deployment descriptor. Patterns qualified by the "/*" pattern violate the
     * URLPatternSpec constraints of WebResourcePermission and WebUserDataPermission names and must be rejected by the
     * corresponding permission constructors.
     *
     * @param metaData - the web deployment metadata
     * @return HashMap<String, PatternInfo>
     */
static HashMap<String, PatternInfo> qualifyURLPatterns(JBossWebMetaData metaData) {
    ArrayList<PatternInfo> prefixList = new ArrayList<PatternInfo>();
    ArrayList<PatternInfo> extensionList = new ArrayList<PatternInfo>();
    ArrayList<PatternInfo> exactList = new ArrayList<PatternInfo>();
    HashMap<String, PatternInfo> patternMap = new HashMap<String, PatternInfo>();
    PatternInfo defaultInfo = null;
    List<SecurityConstraintMetaData> constraints = metaData.getSecurityConstraints();
    if (constraints != null) {
        for (SecurityConstraintMetaData constraint : constraints) {
            WebResourceCollectionsMetaData resourceCollectionsMetaData = constraint.getResourceCollections();
            if (resourceCollectionsMetaData != null) {
                for (WebResourceCollectionMetaData resourceCollectionMetaData : resourceCollectionsMetaData) {
                    List<String> urlPatterns = resourceCollectionMetaData.getUrlPatterns();
                    for (String url : urlPatterns) {
                        int type = getPatternType(url);
                        PatternInfo info = patternMap.get(url);
                        if (info == null) {
                            info = new PatternInfo(url, type);
                            patternMap.put(url, info);
                            switch(type) {
                                case PREFIX:
                                    prefixList.add(info);
                                    break;
                                case EXTENSION:
                                    extensionList.add(info);
                                    break;
                                case EXACT:
                                    exactList.add(info);
                                    break;
                                case DEFAULT:
                                    defaultInfo = info;
                                    break;
                            }
                        }
                    }
                }
            }
        }
    }
    JBossServletsMetaData servlets = metaData.getServlets();
    List<ServletMappingMetaData> mappings = metaData.getServletMappings();
    if (!metaData.isMetadataComplete() && servlets != null && mappings != null) {
        Map<String, List<String>> servletMappingMap = new HashMap<>();
        for (ServletMappingMetaData mapping : mappings) {
            List<String> list = servletMappingMap.get(mapping.getServletName());
            if (list == null) {
                servletMappingMap.put(mapping.getServletName(), list = new ArrayList<>());
            }
            list.addAll(mapping.getUrlPatterns());
        }
        for (JBossServletMetaData servlet : servlets) {
            ServletSecurityMetaData security = servlet.getServletSecurity();
            if (security != null) {
                List<String> servletMappings = servletMappingMap.get(servlet.getServletName());
                if (servletMappings != null) {
                    for (String url : servletMappings) {
                        int type = getPatternType(url);
                        PatternInfo info = patternMap.get(url);
                        if (info == null) {
                            info = new PatternInfo(url, type);
                            patternMap.put(url, info);
                            switch(type) {
                                case PREFIX:
                                    prefixList.add(info);
                                    break;
                                case EXTENSION:
                                    extensionList.add(info);
                                    break;
                                case EXACT:
                                    exactList.add(info);
                                    break;
                                case DEFAULT:
                                    defaultInfo = info;
                                    break;
                            }
                        }
                    }
                }
            }
        }
    }
    // Qualify all prefix patterns
    for (int i = 0; i < prefixList.size(); i++) {
        PatternInfo info = prefixList.get(i);
        // Qualify by every other prefix pattern matching this pattern
        for (int j = 0; j < prefixList.size(); j++) {
            if (i == j)
                continue;
            PatternInfo other = prefixList.get(j);
            if (info.matches(other))
                info.addQualifier(other);
        }
        // Qualify by every exact pattern that is matched by this pattern
        for (PatternInfo other : exactList) {
            if (info.matches(other))
                info.addQualifier(other);
        }
    }
    // Qualify all extension patterns
    for (PatternInfo info : extensionList) {
        // Qualify by every path prefix pattern
        for (PatternInfo other : prefixList) {
            // Any extension
            info.addQualifier(other);
        }
        // Qualify by every matching exact pattern
        for (PatternInfo other : exactList) {
            if (info.isExtensionFor(other))
                info.addQualifier(other);
        }
    }
    // Qualify the default pattern
    if (defaultInfo == null) {
        defaultInfo = new PatternInfo("/", DEFAULT);
        patternMap.put("/", defaultInfo);
    }
    for (PatternInfo info : patternMap.values()) {
        if (info == defaultInfo)
            continue;
        defaultInfo.addQualifier(info);
    }
    return patternMap;
}
Also used : JBossServletsMetaData(org.jboss.metadata.web.jboss.JBossServletsMetaData) HashMap(java.util.HashMap) JBossServletMetaData(org.jboss.metadata.web.jboss.JBossServletMetaData) ArrayList(java.util.ArrayList) ServletSecurityMetaData(org.jboss.metadata.web.spec.ServletSecurityMetaData) SecurityConstraintMetaData(org.jboss.metadata.web.spec.SecurityConstraintMetaData) WebResourceCollectionsMetaData(org.jboss.metadata.web.spec.WebResourceCollectionsMetaData) ServletMappingMetaData(org.jboss.metadata.web.spec.ServletMappingMetaData) ArrayList(java.util.ArrayList) List(java.util.List) WebResourceCollectionMetaData(org.jboss.metadata.web.spec.WebResourceCollectionMetaData)

Aggregations

JBossServletMetaData (org.jboss.metadata.web.jboss.JBossServletMetaData)11 ArrayList (java.util.ArrayList)5 DeploymentUnit (org.jboss.as.server.deployment.DeploymentUnit)5 WarMetaData (org.jboss.as.web.common.WarMetaData)5 ParamValueMetaData (org.jboss.metadata.javaee.spec.ParamValueMetaData)5 JBossWebMetaData (org.jboss.metadata.web.jboss.JBossWebMetaData)5 ServletMappingMetaData (org.jboss.metadata.web.spec.ServletMappingMetaData)5 HashSet (java.util.HashSet)4 HashMap (java.util.HashMap)3 List (java.util.List)3 DeploymentUnitProcessingException (org.jboss.as.server.deployment.DeploymentUnitProcessingException)3 SecurityConstraintMetaData (org.jboss.metadata.web.spec.SecurityConstraintMetaData)3 WebResourceCollectionMetaData (org.jboss.metadata.web.spec.WebResourceCollectionMetaData)3 DeploymentInfo (io.undertow.servlet.api.DeploymentInfo)2 MalformedURLException (java.net.MalformedURLException)2 Map (java.util.Map)2 Set (java.util.Set)2 DeploymentResourceSupport (org.jboss.as.server.deployment.DeploymentResourceSupport)2 ModelNode (org.jboss.dmr.ModelNode)2 SecurityRoleRefMetaData (org.jboss.metadata.javaee.spec.SecurityRoleRefMetaData)2