private static String getDeploymentSecurityDomainName(final Endpoint ep) {
   JBossWebMetaData metadata =
       ep.getService().getDeployment().getAttachment(JBossWebMetaData.class);
   String metaDataSecurityDomain = metadata != null ? metadata.getSecurityDomain() : null;
   return metaDataSecurityDomain == null
       ? SecurityConstants.DEFAULT_APPLICATION_POLICY
       : SecurityUtil.unprefixSecurityDomain(metaDataSecurityDomain.trim());
 }
  /**
   * This method is invoked from within subclass performDeploy() method implementations when they
   * invoke WebDescriptorParser.parseWebAppDescriptors().
   *
   * @param loader the ClassLoader for the web application. May not be null.
   * @param metaData the WebMetaData from the WebApplication object passed to the performDeploy
   *     method.
   */
  protected void processEnc(ClassLoader loader, WebApplication webApp) throws Exception {
    if (loader == null)
      throw new IllegalArgumentException("Classloader passed to process ENC refs is null");
    log.debug("AbstractWebContainer.parseWebAppDescriptors, Begin");
    InitialContext iniCtx = new InitialContext();
    Context envCtx = null;
    Thread currentThread = Thread.currentThread();
    ClassLoader currentLoader = currentThread.getContextClassLoader();
    JBossWebMetaData metaData = webApp.getMetaData();
    try {
      // Create a java:comp/env environment unique for the web application
      log.debug("Creating ENC using ClassLoader: " + loader);
      ClassLoader parent = loader.getParent();
      while (parent != null) {
        log.debug(".." + parent);
        parent = parent.getParent();
      }
      // TODO: The enc should be an input?
      currentThread.setContextClassLoader(loader);
      // webApp.setENCLoader(loader);
      envCtx = (Context) iniCtx.lookup("java:comp");

      // TODO: inject the ORB
      ORB orb = null;
      try {
        ObjectName ORB_NAME = new ObjectName("jboss:service=CorbaORB");
        orb = (ORB) server.getAttribute(ORB_NAME, "ORB");
        // Bind the orb
        if (orb != null) {
          NonSerializableFactory.rebind(envCtx, "ORB", orb);
          log.debug("Bound java:comp/ORB");
        }
      } catch (Throwable t) {
        log.debug("Unable to retrieve orb" + t.toString());
      }

      // TODO: injection, Add a link to the global transaction manager
      envCtx.bind("UserTransaction", new LinkRef("UserTransaction"));
      log.debug("Linked java:comp/UserTransaction to JNDI name: UserTransaction");
      envCtx = envCtx.createSubcontext("env");
      processEncReferences(webApp, envCtx);
    } finally {
      currentThread.setContextClassLoader(currentLoader);
    }

    String securityDomain = metaData.getSecurityDomain();
    log.debug("linkSecurityDomain");
    linkSecurityDomain(securityDomain, envCtx);
    log.debug("AbstractWebContainer.parseWebAppDescriptors, End");
  }
  private void processDeployment(
      final WarMetaData warMetaData,
      final DeploymentUnit deploymentUnit,
      final ServiceTarget serviceTarget,
      String hostName)
      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);
    metaData.resolveRunAs();

    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);
      }
    }

    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;
    }

    String deploymentName;
    if (deploymentUnit.getParent() == null) {
      deploymentName = deploymentUnit.getName();
    } else {
      deploymentName = deploymentUnit.getParent().getName() + "." + deploymentUnit.getName();
    }

    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
              ? SecurityConstants.DEFAULT_APPLICATION_POLICY
              : SecurityUtil.unprefixSecurityDomain(metaDataSecurityDomain);
    } else {
      securityDomain = null;
    }

    String serverInstanceName =
        metaData.getServerInstanceName() == null ? defaultServer : metaData.getServerInstanceName();
    final ServiceName deploymentServiceName =
        UndertowService.deploymentServiceName(serverInstanceName, hostName, pathName);

    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);
    TldsMetaData tldsMetaData = deploymentUnit.getAttachment(TldsMetaData.ATTACHMENT_KEY);
    UndertowDeploymentInfoService undertowDeploymentInfoService =
        UndertowDeploymentInfoService.builder()
            .setAttributes(deploymentUnit.getAttachmentList(ServletContextAttribute.ATTACHMENT_KEY))
            .setTopLevelDeploymentName(
                deploymentUnit.getParent() == null
                    ? deploymentUnit.getName()
                    : deploymentUnit.getParent().getName())
            .setContextPath(pathName)
            .setDeploymentName(
                deploymentName) // todo: is this deployment name concept really applicable?
            .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))
            .createUndertowDeploymentInfoService();

    final ServiceName deploymentInfoServiceName =
        deploymentServiceName.append(UndertowDeploymentInfoService.SERVICE_NAME);
    ServiceBuilder<DeploymentInfo> infoBuilder =
        serviceTarget
            .addService(deploymentInfoServiceName, undertowDeploymentInfoService)
            .addDependency(
                UndertowService.SERVLET_CONTAINER.append(defaultContainer),
                ServletContainerService.class,
                undertowDeploymentInfoService.getContainer())
            .addDependency(
                UndertowService.UNDERTOW,
                UndertowService.class,
                undertowDeploymentInfoService.getUndertowService())
            .addDependencies(deploymentUnit.getAttachmentList(Attachments.WEB_DEPENDENCIES))
            .addDependency(hostServiceName, Host.class, undertowDeploymentInfoService.getHost())
            .addDependency(
                SuspendController.SERVICE_NAME,
                SuspendController.class,
                undertowDeploymentInfoService.getSuspendControllerInjectedValue())
            .addDependencies(additionalDependencies);
    if (securityDomain != null) {
      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 {
      ServiceName sessionManagerFactoryServiceName =
          installSessionManagerFactory(
              serviceTarget, deploymentServiceName, deploymentName, module, metaData);
      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);
  }
  private DeploymentInfo createServletConfig(
      final JBossWebMetaData mergedMetaData,
      final DeploymentUnit deploymentUnit,
      final Module module,
      final DeploymentClassIndex classReflectionIndex,
      final WebInjectionContainer injectionContainer,
      final ComponentRegistry componentRegistry,
      final ScisMetaData scisMetaData,
      final VirtualFile deploymentRoot)
      throws DeploymentUnitProcessingException {
    try {
      mergedMetaData.resolveAnnotations();
      final DeploymentInfo d = new DeploymentInfo();
      d.setContextPath(mergedMetaData.getContextRoot());
      if (mergedMetaData.getDescriptionGroup() != null) {
        d.setDisplayName(mergedMetaData.getDescriptionGroup().getDisplayName());
      }
      d.setDeploymentName(deploymentUnit.getName());
      d.setResourceLoader(new DeploymentResourceLoader(deploymentRoot));
      d.setClassLoader(module.getClassLoader());
      final String servletVersion = mergedMetaData.getServletVersion();
      if (servletVersion != null) {
        d.setMajorVersion(Integer.parseInt(servletVersion.charAt(0) + ""));
        d.setMinorVersion(Integer.parseInt(servletVersion.charAt(2) + ""));
      } else {
        d.setMajorVersion(3);
        d.setMinorVersion(1);
      }

      // for 2.2 apps we do not require a leading / in path mappings
      boolean is22OrOlder;
      if (d.getMajorVersion() == 1) {
        is22OrOlder = true;
      } else if (d.getMajorVersion() == 2) {
        is22OrOlder = d.getMinorVersion() < 3;
      } else {
        is22OrOlder = false;
      }

      HashMap<String, TagLibraryInfo> tldInfo =
          createTldsInfo(deploymentUnit, classReflectionIndex, componentRegistry, d);
      HashMap<String, JspPropertyGroup> propertyGroups = createJspConfig(mergedMetaData);

      JspServletBuilder.setupDeployment(
          d, propertyGroups, tldInfo, new UndertowJSPInstanceManager(injectionContainer));
      d.setJspConfigDescriptor(
          new JspConfigDescriptorImpl(tldInfo.values(), propertyGroups.values()));
      d.setDefaultServletConfig(new DefaultServletConfig(true, Collections.<String>emptySet()));

      // default JSP servlet
      final ServletInfo jspServlet =
          new ServletInfo("Default JSP Servlet", JspServlet.class)
              .addMapping("*.jsp")
              .addMapping("*.jspx")
              .addInitParam("development", "false"); // todo: make configurable
      d.addServlet(jspServlet);

      final Set<String> jspPropertyGroupMappings = propertyGroups.keySet();
      for (final String mapping : jspPropertyGroupMappings) {
        jspServlet.addMapping(mapping);
      }

      d.setClassIntrospecter(new ComponentClassIntrospector(componentRegistry));

      final Map<String, List<ServletMappingMetaData>> servletMappings = new HashMap<>();

      if (mergedMetaData.getServletMappings() != null) {
        for (final ServletMappingMetaData mapping : mergedMetaData.getServletMappings()) {
          List<ServletMappingMetaData> list = servletMappings.get(mapping.getServletName());
          if (list == null) {
            servletMappings.put(mapping.getServletName(), list = new ArrayList<>());
          }
          list.add(mapping);
        }
      }
      final Set<String> seenMappings = new HashSet<>(jspPropertyGroupMappings);
      if (mergedMetaData.getServlets() != null) {
        for (final JBossServletMetaData servlet : mergedMetaData.getServlets()) {
          final ServletInfo s;

          if (servlet.getJspFile() != null) {
            // TODO: real JSP support
            s = new ServletInfo(servlet.getName(), JspServlet.class);
            s.addHandlerChainWrapper(new JspFileWrapper(servlet.getJspFile()));
          } else {
            Class<? extends Servlet> servletClass =
                (Class<? extends Servlet>)
                    classReflectionIndex.classIndex(servlet.getServletClass()).getModuleClass();
            ComponentRegistry.ComponentManagedReferenceFactory creator =
                componentRegistry.getComponentsByClass().get(servletClass);
            if (creator != null) {
              InstanceFactory<Servlet> factory = createInstanceFactory(creator);
              s = new ServletInfo(servlet.getName(), servletClass, factory);
            } else {
              s = new ServletInfo(servlet.getName(), servletClass);
            }
          }
          s.setAsyncSupported(servlet.isAsyncSupported())
              .setJspFile(servlet.getJspFile())
              .setEnabled(servlet.isEnabled());
          if (servlet.getRunAs() != null) {
            s.setRunAs(servlet.getRunAs().getRoleName());
          }
          if (servlet
              .getLoadOnStartupSet()) { // todo why not cleanup api and just use int everywhere
            s.setLoadOnStartup(servlet.getLoadOnStartupInt());
          }

          List<ServletMappingMetaData> mappings = servletMappings.get(servlet.getName());
          if (mappings != null) {
            for (ServletMappingMetaData mapping : mappings) {
              for (String pattern : mapping.getUrlPatterns()) {
                if (is22OrOlder && !pattern.startsWith("*") && !pattern.startsWith("/")) {
                  pattern = "/" + pattern;
                }
                if (!seenMappings.contains(pattern)) {
                  s.addMapping(pattern);
                  seenMappings.add(pattern);
                }
              }
            }
          }
          if (servlet.getInitParam() != null) {
            for (ParamValueMetaData initParam : servlet.getInitParam()) {
              if (!s.getInitParams().containsKey(initParam.getParamName())) {
                s.addInitParam(initParam.getParamName(), initParam.getParamValue());
              }
            }
          }
          if (servlet.getServletSecurity() != null) {
            ServletSecurityInfo securityInfo = new ServletSecurityInfo();
            s.setServletSecurityInfo(securityInfo);
            securityInfo
                .setEmptyRoleSemantic(
                    servlet.getServletSecurity().getEmptyRoleSemantic()
                            == EmptyRoleSemanticType.PERMIT
                        ? PERMIT
                        : DENY)
                .setTransportGuaranteeType(
                    transportGuaranteeType(servlet.getServletSecurity().getTransportGuarantee()))
                .addRolesAllowed(servlet.getServletSecurity().getRolesAllowed());
            if (servlet.getServletSecurity().getHttpMethodConstraints() != null) {
              for (HttpMethodConstraintMetaData method :
                  servlet.getServletSecurity().getHttpMethodConstraints()) {
                securityInfo.addHttpMethodSecurityInfo(
                    new HttpMethodSecurityInfo()
                        .setEmptyRoleSemantic(
                            method.getEmptyRoleSemantic() == EmptyRoleSemanticType.PERMIT
                                ? PERMIT
                                : DENY)
                        .setTransportGuaranteeType(
                            transportGuaranteeType(method.getTransportGuarantee()))
                        .addRolesAllowed(method.getRolesAllowed())
                        .setMethod(method.getMethod()));
              }
            }
          }
          if (servlet.getSecurityRoleRefs() != null) {
            for (final SecurityRoleRefMetaData ref : servlet.getSecurityRoleRefs()) {
              s.addSecurityRoleRef(ref.getRoleName(), ref.getRoleLink());
            }
          }

          d.addServlet(s);
        }
      }

      if (mergedMetaData.getFilters() != null) {
        for (final FilterMetaData filter : mergedMetaData.getFilters()) {
          Class<? extends Filter> filterClass =
              (Class<? extends Filter>)
                  classReflectionIndex.classIndex(filter.getFilterClass()).getModuleClass();
          ComponentRegistry.ComponentManagedReferenceFactory creator =
              componentRegistry.getComponentsByClass().get(filterClass);
          FilterInfo f;
          if (creator != null) {
            InstanceFactory<Filter> instanceFactory = createInstanceFactory(creator);
            f = new FilterInfo(filter.getName(), filterClass, instanceFactory);
          } else {
            f = new FilterInfo(filter.getName(), filterClass);
          }
          f.setAsyncSupported(filter.isAsyncSupported());
          d.addFilter(f);

          if (filter.getInitParam() != null) {
            for (ParamValueMetaData initParam : filter.getInitParam()) {
              f.addInitParam(initParam.getParamName(), initParam.getParamValue());
            }
          }
        }
      }
      if (mergedMetaData.getFilterMappings() != null) {
        for (final FilterMappingMetaData mapping : mergedMetaData.getFilterMappings()) {
          if (mapping.getUrlPatterns() != null) {
            for (String url : mapping.getUrlPatterns()) {
              if (is22OrOlder && !url.startsWith("*") && !url.startsWith("/")) {
                url = "/" + url;
              }
              if (mapping.getDispatchers() != null && !mapping.getDispatchers().isEmpty()) {
                for (DispatcherType dispatcher : mapping.getDispatchers()) {

                  d.addFilterUrlMapping(
                      mapping.getFilterName(),
                      url,
                      javax.servlet.DispatcherType.valueOf(dispatcher.name()));
                }
              } else {
                d.addFilterUrlMapping(
                    mapping.getFilterName(), url, javax.servlet.DispatcherType.REQUEST);
              }
            }
          }
          if (mapping.getServletNames() != null) {
            for (String servletName : mapping.getServletNames()) {
              if (mapping.getDispatchers() != null && !mapping.getDispatchers().isEmpty()) {
                for (DispatcherType dispatcher : mapping.getDispatchers()) {
                  d.addFilterServletNameMapping(
                      mapping.getFilterName(),
                      servletName,
                      javax.servlet.DispatcherType.valueOf(dispatcher.name()));
                }
              } else {
                d.addFilterServletNameMapping(
                    mapping.getFilterName(), servletName, javax.servlet.DispatcherType.REQUEST);
              }
            }
          }
        }
      }

      if (scisMetaData != null && scisMetaData.getHandlesTypes() != null) {
        for (final Map.Entry<ServletContainerInitializer, Set<Class<?>>> sci :
            scisMetaData.getHandlesTypes().entrySet()) {
          final ImmediateInstanceFactory<ServletContainerInitializer> instanceFactory =
              new ImmediateInstanceFactory<>(sci.getKey());
          d.addServletContainerInitalizer(
              new ServletContainerInitializerInfo(
                  sci.getKey().getClass(), instanceFactory, sci.getValue()));
        }
      }

      if (mergedMetaData.getListeners() != null) {
        for (ListenerMetaData listener : mergedMetaData.getListeners()) {
          addListener(classReflectionIndex, componentRegistry, d, listener);
        }
      }
      if (mergedMetaData.getContextParams() != null) {
        for (ParamValueMetaData param : mergedMetaData.getContextParams()) {
          d.addInitParameter(param.getParamName(), param.getParamValue());
        }
      }

      if (mergedMetaData.getWelcomeFileList() != null
          && mergedMetaData.getWelcomeFileList().getWelcomeFiles() != null) {
        d.addWelcomePages(mergedMetaData.getWelcomeFileList().getWelcomeFiles());
      } else {
        d.addWelcomePages("index.html", "index.htm", "index.jsp");
      }

      if (mergedMetaData.getErrorPages() != null) {
        for (final ErrorPageMetaData page : mergedMetaData.getErrorPages()) {
          final ErrorPage errorPage;
          if (page.getExceptionType() == null || page.getExceptionType().isEmpty()) {
            errorPage = new ErrorPage(page.getLocation(), Integer.parseInt(page.getErrorCode()));
          } else {
            errorPage =
                new ErrorPage(
                    page.getLocation(),
                    (Class<? extends Throwable>)
                        classReflectionIndex.classIndex(page.getExceptionType()).getModuleClass());
          }
          d.addErrorPages(errorPage);
        }
      }

      if (mergedMetaData.getMimeMappings() != null) {
        for (final MimeMappingMetaData mapping : mergedMetaData.getMimeMappings()) {
          d.addMimeMapping(new MimeMapping(mapping.getExtension(), mapping.getMimeType()));
        }
      }

      if (mergedMetaData.getSecurityConstraints() != null) {
        for (SecurityConstraintMetaData constraint : mergedMetaData.getSecurityConstraints()) {
          SecurityConstraint securityConstraint =
              new SecurityConstraint()
                  .setTransportGuaranteeType(
                      transportGuaranteeType(constraint.getTransportGuarantee()))
                  .addRolesAllowed(constraint.getRoleNames());

          if (constraint.getAuthConstraint() == null) {
            // no auth constraint means we permit the empty roles
            securityConstraint.setEmptyRoleSemantic(PERMIT);
          }

          if (constraint.getResourceCollections() != null) {
            for (final WebResourceCollectionMetaData resourceCollection :
                constraint.getResourceCollections()) {
              securityConstraint.addWebResourceCollection(
                  new WebResourceCollection()
                      .addHttpMethods(resourceCollection.getHttpMethods())
                      .addHttpMethodOmissions(resourceCollection.getHttpMethodOmissions())
                      .addUrlPatterns(resourceCollection.getUrlPatterns()));
            }
          }
          d.addSecurityConstraint(securityConstraint);
        }
      }
      final LoginConfigMetaData loginConfig = mergedMetaData.getLoginConfig();
      if (loginConfig != null) {
        String authMethod = authMethod(loginConfig.getAuthMethod());
        if (loginConfig.getFormLoginConfig() != null) {
          d.setLoginConfig(
              new LoginConfig(
                  authMethod,
                  loginConfig.getRealmName(),
                  loginConfig.getFormLoginConfig().getLoginPage(),
                  loginConfig.getFormLoginConfig().getErrorPage()));
        } else {
          d.setLoginConfig(new LoginConfig(authMethod, loginConfig.getRealmName()));
        }
      }

      d.addSecurityRoles(mergedMetaData.getSecurityRoleNames());

      if (mergedMetaData.getSecurityDomain() != null) {

        String contextId = deploymentUnit.getName();
        if (deploymentUnit.getParent() != null) {
          contextId = deploymentUnit.getParent().getName() + "!" + contextId;
        }
        d.addOuterHandlerChainWrapper(
            SecurityContextCreationHandler.wrapper(mergedMetaData.getSecurityDomain()));
        d.addDispatchedHandlerChainWrapper(
            SecurityContextAssociationHandler.wrapper(
                mergedMetaData.getPrincipalVersusRolesMap(), contextId));
      }

      // Setup an deployer configured ServletContext attributes
      final List<ServletContextAttribute> attributes =
          deploymentUnit.getAttachmentList(ServletContextAttribute.ATTACHMENT_KEY);
      for (ServletContextAttribute attribute : attributes) {
        d.addServletContextAttribute(attribute.getName(), attribute.getValue());
      }

      if (mergedMetaData.getLocalEncodings() != null
          && mergedMetaData.getLocalEncodings().getMappings() != null) {
        for (LocaleEncodingMetaData locale : mergedMetaData.getLocalEncodings().getMappings()) {
          d.addLocaleCharsetMapping(locale.getLocale(), locale.getEncoding());
        }
      }

      return d;
    } catch (ClassNotFoundException e) {
      throw new DeploymentUnitProcessingException(e);
    }
  }
  private void processDeployment(
      final WarMetaData warMetaData,
      final DeploymentUnit deploymentUnit,
      final ServiceTarget serviceTarget,
      String hostName)
      throws DeploymentUnitProcessingException {
    final VirtualFile deploymentRoot =
        deploymentUnit.getAttachment(Attachments.DEPLOYMENT_ROOT).getRoot();
    final Module module = deploymentUnit.getAttachment(Attachments.MODULE);
    if (module == null) {
      throw new DeploymentUnitProcessingException(MESSAGES.failedToResolveModule(deploymentUnit));
    }
    final DeploymentClassIndex deploymentClassIndex =
        deploymentUnit.getAttachment(Attachments.CLASS_INDEX);
    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) {
      boolean skip = false;
      if (!failed.contains(component)) {
        dependentComponents.add(component);
      }
    }

    ComponentRegistry componentRegistry =
        deploymentUnit.getAttachment(org.jboss.as.ee.component.Attachments.COMPONENT_REGISTRY);
    if (componentRegistry == null) {
      // 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);

    DeploymentInfo deploymentInfo =
        createServletConfig(
            metaData,
            deploymentUnit,
            module,
            deploymentClassIndex,
            injectionContainer,
            componentRegistry,
            scisMetaData,
            deploymentRoot);

    final String pathName = pathNameOfDeployment(deploymentUnit, metaData);
    deploymentInfo.setContextPath(pathName);

    String metaDataSecurityDomain = metaData.getSecurityDomain();
    if (metaDataSecurityDomain == null) {
      metaDataSecurityDomain = getJBossAppSecurityDomain(deploymentUnit);
    }
    if (metaDataSecurityDomain != null) {
      metaDataSecurityDomain = metaDataSecurityDomain.trim();
    }

    String securityDomain =
        metaDataSecurityDomain == null
            ? SecurityConstants.DEFAULT_APPLICATION_POLICY
            : SecurityUtil.unprefixSecurityDomain(metaDataSecurityDomain);

    final ServiceName deploymentServiceName =
        UndertowService.deploymentServiceName(hostName, deploymentInfo.getContextPath());
    final ServiceName hostServiceName = UndertowService.virtualHostName(defaultServer, hostName);
    final UndertowDeploymentService service =
        new UndertowDeploymentService(
            deploymentInfo, injectionContainer, module, warMetaData.getMergedJBossWebMetaData());
    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())
            .addDependency(
                SecurityDomainService.SERVICE_NAME.append(securityDomain),
                SecurityDomainContext.class,
                service.getSecurityDomainContextValue())
            .addDependency(
                UndertowService.UNDERTOW, UndertowService.class, service.getUndertowService());

    deploymentUnit.addToAttachmentList(
        Attachments.DEPLOYMENT_COMPLETE_SERVICES, deploymentServiceName);

    // add any dependencies required by the setup action
    for (final SetupAction action : setupActions) {
      builder.addDependencies(action.dependencies());
      deploymentInfo.addThreadSetupAction(
          new ThreadSetupAction() {

            @Override
            public Handle setup(final HttpServerExchange exchange) {
              action.setup(Collections.<String, Object>emptyMap());
              return new Handle() {
                @Override
                public void tearDown() {
                  action.teardown(Collections.<String, Object>emptyMap());
                }
              };
            }
          });
    }

    if (metaData.getDistributable() != null) {
      DistributedCacheManagerFactoryService factoryService =
          new DistributedCacheManagerFactoryService();
      DistributedCacheManagerFactory factory = factoryService.getValue();
      if (factory != null) {
        ServiceName factoryServiceName = deploymentServiceName.append("session");
        builder.addDependency(
            ServiceBuilder.DependencyType.OPTIONAL,
            factoryServiceName,
            DistributedCacheManagerFactory.class,
            service.getDistributedCacheManagerFactoryInjectedValue());

        ServiceBuilder<DistributedCacheManagerFactory> factoryBuilder =
            serviceTarget.addService(factoryServiceName, factoryService);
        boolean enabled =
            factory.addDeploymentDependencies(
                deploymentServiceName,
                deploymentUnit.getServiceRegistry(),
                serviceTarget,
                factoryBuilder,
                metaData);
        factoryBuilder.setInitialMode(enabled ? Mode.ON_DEMAND : Mode.NEVER).install();
      }
    }

    // OSGi web applications are activated in {@link WebContextActivationProcessor} according to
    // bundle lifecycle changes
    if (deploymentUnit.hasAttachment(Attachments.OSGI_MANIFEST)) {
      builder.setInitialMode(Mode.NEVER);
      UndertowDeploymentService.ContextActivatorImpl activator =
          new UndertowDeploymentService.ContextActivatorImpl(builder.install());
      deploymentUnit.putAttachment(ContextActivator.ATTACHMENT_KEY, activator);
    } else {
      builder.setInitialMode(Mode.ACTIVE);
      builder.install();
    }

    // Process the web related mgmt information
    final ModelNode node =
        deploymentUnit.getDeploymentSubsystemModel(UndertowExtension.SUBSYSTEM_NAME);
    node.get(DeploymentDefinition.CONTEXT_ROOT.getName()).set("".equals(pathName) ? "/" : pathName);
    node.get(DeploymentDefinition.VIRTUAL_HOST.getName()).set(hostName);
    processManagement(deploymentUnit, metaData);
  }
  protected void processDeployment(
      final String hostName, final WarMetaData warMetaData, final DeploymentUnitContext context)
      throws DeploymentUnitProcessingException {
    final VirtualFile deploymentRoot = VirtualFileAttachment.getVirtualFileAttachment(context);
    final Module module = context.getAttachment(ModuleDeploymentProcessor.MODULE_ATTACHMENT_KEY);
    if (module == null) {
      throw new DeploymentUnitProcessingException(
          "failed to resolve module for deployment " + deploymentRoot);
    }
    final ClassLoader classLoader = module.getClassLoader();
    final JBossWebMetaData metaData = warMetaData.getMergedJBossWebMetaData();

    // Create the context
    final StandardContext webContext = new StandardContext();
    final ContextConfig config = new JBossContextConfig(context);
    // Set the deployment root
    try {
      webContext.setDocBase(deploymentRoot.getPhysicalFile().getAbsolutePath());
    } catch (IOException e) {
      throw new DeploymentUnitProcessingException(e);
    }
    webContext.addLifecycleListener(config);

    // Set the path name
    final String deploymentName = context.getName();
    String pathName = null;
    if (metaData.getContextRoot() == null) {
      pathName = deploymentRoot.getName();
      if (pathName.equals("ROOT.war")) {
        pathName = "";
      } else {
        pathName = "/" + pathName.substring(0, pathName.length() - 4);
      }
    } else {
      pathName = metaData.getContextRoot();
      if ("/".equals(pathName)) {
        pathName = "";
      }
    }
    webContext.setPath(pathName);
    webContext.setIgnoreAnnotations(true);

    // Add a dummy realm for now
    Realm realm = new MemoryRealm();
    webContext.setRealm(realm);

    //
    final Loader loader = new WebCtxLoader(classLoader);
    final InstanceManager manager = new WebInjectionContainer(classLoader);
    webContext.setInstanceManager(manager);
    webContext.setLoader(loader);

    // Set the session cookies flag according to metadata
    switch (metaData.getSessionCookies()) {
      case JBossWebMetaData.SESSION_COOKIES_ENABLED:
        webContext.setCookies(true);
        break;
      case JBossWebMetaData.SESSION_COOKIES_DISABLED:
        webContext.setCookies(false);
        break;
    }

    String metaDataSecurityDomain = metaData.getSecurityDomain();
    if (metaDataSecurityDomain != null) {
      metaDataSecurityDomain = metaDataSecurityDomain.trim();
    }

    // Add the context service
    final BatchBuilder builder = context.getBatchBuilder();
    builder
        .addService(
            WebSubsystemElement.JBOSS_WEB.append(deploymentName),
            new WebDeploymentService(webContext))
        .addDependency(
            WebSubsystemElement.JBOSS_WEB_HOST.append(hostName),
            Host.class,
            new WebContextInjector(webContext))
        .setInitialMode(Mode.ACTIVE);
  }
  protected void processDeployment(
      final String hostName,
      final WarMetaData warMetaData,
      final DeploymentUnit deploymentUnit,
      final ServiceTarget serviceTarget)
      throws DeploymentUnitProcessingException {
    final VirtualFile deploymentRoot =
        deploymentUnit.getAttachment(Attachments.DEPLOYMENT_ROOT).getRoot();
    final Module module = deploymentUnit.getAttachment(Attachments.MODULE);
    if (module == null) {
      throw new DeploymentUnitProcessingException(MESSAGES.failedToResolveModule(deploymentRoot));
    }
    final ClassLoader classLoader = module.getClassLoader();
    final JBossWebMetaData metaData = warMetaData.getMergedJBossWebMetaData();
    final List<SetupAction> setupActions =
        deploymentUnit.getAttachmentList(org.jboss.as.ee.component.Attachments.WEB_SETUP_ACTIONS);

    // Create the context
    final StandardContext webContext = new StandardContext();
    final JBossContextConfig config = new JBossContextConfig(deploymentUnit);

    // Add SecurityAssociationValve right at the beginning
    webContext.addValve(new SecurityContextAssociationValve(deploymentUnit));

    // Set the deployment root
    try {
      webContext.setDocBase(deploymentRoot.getPhysicalFile().getAbsolutePath());
    } catch (IOException e) {
      throw new DeploymentUnitProcessingException(e);
    }
    webContext.addLifecycleListener(config);

    final String pathName = pathNameOfDeployment(deploymentUnit, metaData);
    webContext.setPath(pathName);
    webContext.setIgnoreAnnotations(true);
    webContext.setCrossContext(!metaData.isDisableCrossContext());

    final WebInjectionContainer injectionContainer =
        new WebInjectionContainer(module.getClassLoader());

    // 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 Map<String, ComponentInstantiator> components =
        deploymentUnit.getAttachment(WebAttachments.WEB_COMPONENT_INSTANTIATORS);
    if (components != null) {
      final Set<ServiceName> failed =
          deploymentUnit.getAttachment(org.jboss.as.ee.component.Attachments.FAILED_COMPONENTS);
      for (Map.Entry<String, ComponentInstantiator> entry : components.entrySet()) {
        boolean skip = false;
        for (final ServiceName serviceName : entry.getValue().getServiceNames()) {
          if (failed.contains(serviceName)) {
            skip = true;
            break;
          }
        }
        if (!skip) {
          injectionContainer.addInstantiator(entry.getKey(), entry.getValue());
        }
      }
    }

    final Loader loader = new WebCtxLoader(classLoader);
    webContext.setLoader(loader);

    // Valves
    List<ValveMetaData> valves = metaData.getValves();
    if (valves == null) {
      metaData.setValves(valves = new ArrayList<ValveMetaData>());
    }
    for (ValveMetaData valve : valves) {
      Valve valveInstance =
          (Valve) getInstance(module, valve.getModule(), valve.getValveClass(), valve.getParams());
      webContext.getPipeline().addValve(valveInstance);
    }

    // Container listeners
    List<ContainerListenerMetaData> listeners = metaData.getContainerListeners();
    if (listeners != null) {
      for (ContainerListenerMetaData listener : listeners) {
        switch (listener.getListenerType()) {
          case CONTAINER:
            ContainerListener containerListener =
                (ContainerListener)
                    getInstance(
                        module,
                        listener.getModule(),
                        listener.getListenerClass(),
                        listener.getParams());
            webContext.addContainerListener(containerListener);
            break;
          case LIFECYCLE:
            LifecycleListener lifecycleListener =
                (LifecycleListener)
                    getInstance(
                        module,
                        listener.getModule(),
                        listener.getListenerClass(),
                        listener.getParams());
            if (webContext instanceof Lifecycle) {
              ((Lifecycle) webContext).addLifecycleListener(lifecycleListener);
            }
            break;
          case SERVLET_INSTANCE:
            webContext.addInstanceListener(listener.getListenerClass());
            break;
          case SERVLET_CONTAINER:
            webContext.addWrapperListener(listener.getListenerClass());
            break;
          case SERVLET_LIFECYCLE:
            webContext.addWrapperLifecycle(listener.getListenerClass());
            break;
        }
      }
    }

    // Set the session cookies flag according to metadata
    switch (metaData.getSessionCookies()) {
      case JBossWebMetaData.SESSION_COOKIES_ENABLED:
        webContext.setCookies(true);
        break;
      case JBossWebMetaData.SESSION_COOKIES_DISABLED:
        webContext.setCookies(false);
        break;
    }

    String metaDataSecurityDomain = metaData.getSecurityDomain();
    if (metaDataSecurityDomain != null) {
      metaDataSecurityDomain = metaDataSecurityDomain.trim();
    }

    String securityDomain =
        metaDataSecurityDomain == null
            ? SecurityConstants.DEFAULT_APPLICATION_POLICY
            : SecurityUtil.unprefixSecurityDomain(metaDataSecurityDomain);

    // Setup an deployer configured ServletContext attributes
    final List<ServletContextAttribute> attributes =
        deploymentUnit.getAttachment(ServletContextAttribute.ATTACHMENT_KEY);

    try {
      final ServiceName deploymentServiceName =
          WebSubsystemServices.deploymentServiceName(hostName, pathName);
      final ServiceName realmServiceName = deploymentServiceName.append("realm");

      final JBossWebRealmService realmService = new JBossWebRealmService(deploymentUnit);
      ServiceBuilder<?> builder = serviceTarget.addService(realmServiceName, realmService);
      builder
          .addDependency(
              DependencyType.REQUIRED,
              SecurityDomainService.SERVICE_NAME.append(securityDomain),
              SecurityDomainContext.class,
              realmService.getSecurityDomainContextInjector())
          .setInitialMode(Mode.ACTIVE)
          .install();

      final WebDeploymentService webDeploymentService =
          new WebDeploymentService(webContext, injectionContainer, setupActions, attributes);
      builder =
          serviceTarget
              .addService(deploymentServiceName, webDeploymentService)
              .addDependency(
                  WebSubsystemServices.JBOSS_WEB_HOST.append(hostName),
                  VirtualHost.class,
                  new WebContextInjector(webContext))
              .addDependencies(injectionContainer.getServiceNames())
              .addDependency(realmServiceName, Realm.class, webDeploymentService.getRealm())
              .addDependencies(deploymentUnit.getAttachmentList(Attachments.WEB_DEPENDENCIES))
              .addDependency(JndiNamingDependencyProcessor.serviceName(deploymentUnit));

      // add any dependencies required by the setup action
      for (final SetupAction action : setupActions) {
        builder.addDependencies(action.dependencies());
      }

      if (metaData.getDistributable() != null) {
        DistributedCacheManagerFactoryService factoryService =
            new DistributedCacheManagerFactoryService();
        DistributedCacheManagerFactory factory = factoryService.getValue();
        if (factory != null) {
          ServiceName factoryServiceName = deploymentServiceName.append("session");
          builder.addDependency(
              DependencyType.OPTIONAL,
              factoryServiceName,
              DistributedCacheManagerFactory.class,
              config.getDistributedCacheManagerFactoryInjector());

          ServiceBuilder<DistributedCacheManagerFactory> factoryBuilder =
              serviceTarget.addService(factoryServiceName, factoryService);
          boolean enabled = factory.addDependencies(serviceTarget, factoryBuilder, metaData);
          factoryBuilder
              .setInitialMode(
                  enabled ? ServiceController.Mode.ON_DEMAND : ServiceController.Mode.NEVER)
              .install();
        }
      }

      builder.install();

      // adding JACC service
      AbstractSecurityDeployer<?> deployer = new WarSecurityDeployer();
      JaccService<?> service = deployer.deploy(deploymentUnit);
      if (service != null) {
        ((WarJaccService) service).setContext(webContext);
        final ServiceName jaccServiceName =
            JaccService.SERVICE_NAME.append(deploymentUnit.getName());
        builder = serviceTarget.addService(jaccServiceName, service);
        if (deploymentUnit.getParent() != null) {
          // add dependency to parent policy
          final DeploymentUnit parentDU = deploymentUnit.getParent();
          builder.addDependency(
              JaccService.SERVICE_NAME.append(parentDU.getName()),
              PolicyConfiguration.class,
              service.getParentPolicyInjector());
        }
        // add dependency to web deployment service
        builder.addDependency(deploymentServiceName);
        builder.setInitialMode(Mode.ACTIVE).install();
      }
    } catch (ServiceRegistryException e) {
      throw new DeploymentUnitProcessingException(MESSAGES.failedToAddWebDeployment(), e);
    }

    // Process the web related mgmt information
    final ModelNode node = deploymentUnit.getDeploymentSubsystemModel("web");
    node.get("context-root").set("".equals(pathName) ? "/" : pathName);
    node.get("virtual-host").set(hostName);
    processManagement(deploymentUnit, metaData);
  }