@Override
 protected void processDeployment(
     final DeploymentPhaseContext phaseContext,
     final DeploymentUnit deploymentUnit,
     final ResourceRoot root)
     throws DeploymentUnitProcessingException {
   final List<DeploymentUnit> subDeployments = getSubDeployments(deploymentUnit);
   final String loggingProfile = findLoggingProfile(root);
   if (loggingProfile != null) {
     // Get the profile logging context
     final LoggingProfileContextSelector loggingProfileContext =
         LoggingProfileContextSelector.getInstance();
     if (loggingProfileContext.exists(loggingProfile)) {
       // Get the module
       final Module module = deploymentUnit.getAttachment(Attachments.MODULE);
       final LogContext logContext = loggingProfileContext.get(loggingProfile);
       LoggingLogger.ROOT_LOGGER.tracef(
           "Registering log context '%s' on '%s' for profile '%s'",
           logContext, root, loggingProfile);
       registerLogContext(deploymentUnit, module, logContext);
       // Process sub-deployments
       for (DeploymentUnit subDeployment : subDeployments) {
         // A sub-deployment must have a module to process
         if (subDeployment.hasAttachment(Attachments.MODULE)) {
           // Set the result to true if a logging profile was found
           if (subDeployment.hasAttachment(Attachments.DEPLOYMENT_ROOT)) {
             processDeployment(
                 phaseContext,
                 subDeployment,
                 subDeployment.getAttachment(Attachments.DEPLOYMENT_ROOT));
           }
           if (!hasRegisteredLogContext(subDeployment)) {
             final Module subDeploymentModule = subDeployment.getAttachment(Attachments.MODULE);
             LoggingLogger.ROOT_LOGGER.tracef(
                 "Registering log context '%s' on '%s' for profile '%s'",
                 logContext,
                 subDeployment.getAttachment(Attachments.DEPLOYMENT_ROOT),
                 loggingProfile);
             registerLogContext(subDeployment, subDeploymentModule, logContext);
           }
         }
       }
     } else {
       LoggingLogger.ROOT_LOGGER.loggingProfileNotFound(loggingProfile, root);
     }
   } else {
     // No logging profile found, but the sub-deployments should be checked for logging profiles
     for (DeploymentUnit subDeployment : subDeployments) {
       // A sub-deployment must have a root resource and a module to process
       if (subDeployment.hasAttachment(Attachments.MODULE)
           && subDeployment.hasAttachment(Attachments.DEPLOYMENT_ROOT)) {
         processDeployment(
             phaseContext,
             subDeployment,
             subDeployment.getAttachment(Attachments.DEPLOYMENT_ROOT));
       }
     }
   }
 }
 @Override
 public void undeploy(DeploymentUnit unit) {
   if (unit.hasAttachment(ClojureMetaData.ATTACHMENT_KEY)) {
     try {
       FileUtils.deleteDirectory(tmpMountDir(unit));
     } catch (IOException e) {
       e.printStackTrace();
     }
   }
 }
  /**
   * @see
   *     org.jboss.webservices.integration.deployers.deployment.DeploymentModelBuilder#newDeploymentModel(DeploymentUnit)
   * @param unit deployment unit
   */
  public final void newDeploymentModel(final DeploymentUnit unit) {
    final ArchiveDeployment dep;
    if (unit.hasAttachment(DEPLOYMENT_KEY)) {
      dep = (ArchiveDeployment) unit.getAttachment(DEPLOYMENT_KEY);
    } else {
      dep = newDeployment(unit);
      propagateAttachments(unit, dep);
    }

    this.build(dep, unit);
  }
  @Override
  public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException {
    DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();

    if (deploymentUnit.hasAttachment(ClojureMetaData.ATTACHMENT_KEY)) {
      return;
    }

    Timer t = new Timer("parsing deployment descriptor");
    String deploymentName = deploymentUnit.getName();

    try {
      VirtualFile descriptor = getDescriptorFile(deploymentUnit);
      if (descriptor == null) {
        return;
      }

      ClojureMetaData appMetaData =
          new ClojureMetaData(deploymentName, ClojureMetaData.parse(descriptor.getPhysicalFile()));

      appMetaData.attachTo(deploymentUnit);

      File root = appMetaData.getRoot();

      if (root == null) {
        throw new DeploymentUnitProcessingException("No application root specified.");
      }

      if (!root.exists()) {
        throw new DeploymentUnitProcessingException(
            "Application root does not exist: " + root.getAbsolutePath());
      }

      VirtualFile virtualRoot = VFS.getChild(root.toURI());
      MountHandle mountHandle = null;

      if (!root.isDirectory()) {
        // Expand the referenced root if it's not a directory (ie .ima archive)
        mountHandle =
            new MountHandle(
                VFS.mountZipExpanded(virtualRoot, virtualRoot, TempFileProviderService.provider()));
      }

      deploymentUnit.putAttachment(
          Attachments.DEPLOYMENT_ROOT, new ResourceRoot(virtualRoot, mountHandle));
      deploymentUnit.putAttachment(ClojureMetaData.DESCRIPTOR_FILE, descriptor.getPhysicalFile());

    } catch (Exception e) {
      throw new DeploymentUnitProcessingException(e);
    }
    t.done();
  }
  @Override
  public void deploy(final DeploymentPhaseContext phaseContext)
      throws DeploymentUnitProcessingException {
    final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();
    if (deploymentUnit.hasAttachment(Attachments.MODULE)) {
      BatchLogger.LOGGER.tracef("Processing deployment '%s' for batch.", deploymentUnit.getName());
      // Get the class loader
      final Module module = deploymentUnit.getAttachment(Attachments.MODULE);
      final ClassLoader moduleClassLoader = module.getClassLoader();

      final ServiceTarget serviceTarget = phaseContext.getServiceTarget();

      final BatchEnvironmentService service = new BatchEnvironmentService();

      final ServiceBuilder<BatchEnvironment> serviceBuilder =
          serviceTarget.addService(
              BatchServiceNames.batchDeploymentServiceName(deploymentUnit), service);
      serviceBuilder.addDependency(
          BatchServiceNames.BATCH_PROPERTIES, Properties.class, service.getPropertiesInjector());
      serviceBuilder.addDependency(
          BatchServiceNames.BATCH_THREAD_POOL_NAME,
          ExecutorService.class,
          service.getExecutorServiceInjector());

      // Set the class loader
      service.getClassLoaderInjector().setValue(new ImmediateValue<>(moduleClassLoader));

      // Only add transactions and the BeanManager if this is a batch deployment
      if (isBatchDeployment(deploymentUnit)) {
        serviceBuilder.addDependency(
            TxnServices.JBOSS_TXN_USER_TRANSACTION,
            UserTransaction.class,
            service.getUserTransactionInjector());

        // Add the bean manager
        serviceBuilder.addDependency(
            BatchServiceNames.beanManagerServiceName(deploymentUnit),
            new CastingInjector<>(service.getBeanManagerInjector(), BeanManager.class));
      } else {
        BatchLogger.LOGGER.tracef(
            "Skipping UserTransaction and BeanManager service dependencies for deployment %s",
            deploymentUnit.getName());
      }

      serviceBuilder.install();
    }
  }
  @Override
  public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException {

    // Check if we already have an OSGi deployment
    DeploymentUnit depUnit = phaseContext.getDeploymentUnit();
    if (depUnit.hasAttachment(OSGiConstants.OSGI_METADATA_KEY)) return;

    // Get the OSGi XService properties
    VirtualFile virtualFile = depUnit.getAttachment(Attachments.DEPLOYMENT_ROOT).getRoot();
    VirtualFile xserviceFile = virtualFile.getChild(XSERVICE_PROPERTIES_NAME);
    if (xserviceFile.exists() == false) return;

    try {
      Properties props = new Properties();
      props.load(xserviceFile.openStream());
      OSGiMetaData metadata = OSGiMetaDataBuilder.load(props);
      depUnit.putAttachment(OSGiConstants.OSGI_METADATA_KEY, metadata);
    } catch (IOException ex) {
      throw MESSAGES.cannotParseOSGiMetadata(ex, xserviceFile);
    }
  }
 /**
  * Batch deployments must have a {@code META-INF/batch.xml} and/or XML configuration files in
  * {@code META-INF/batch-jobs}. They must be in an EJB JAR or a WAR.
  *
  * @param deploymentUnit the deployment unit to check
  * @return {@code true} if a {@code META-INF/batch.xml} or a non-empty {@code META-INF/batch-jobs}
  *     directory was found otherwise {@code false}
  */
 private boolean isBatchDeployment(final DeploymentUnit deploymentUnit) {
   // Section 10.7 of JSR 352 discusses valid packaging types, of which it appears EAR should be
   // one. It seems
   // though that it's of no real use as 10.5 and 10.6 seem to indicate it must be in
   // META-INF/batch-jobs of a JAR
   // and WEB-INF/classes/META-INF/batch-jobs of a WAR.
   if (DeploymentTypeMarker.isType(DeploymentType.EAR, deploymentUnit)
       || !deploymentUnit.hasAttachment(Attachments.DEPLOYMENT_ROOT)) {
     return false;
   }
   final ResourceRoot root = deploymentUnit.getAttachment(Attachments.DEPLOYMENT_ROOT);
   final VirtualFile metaInf;
   if (DeploymentTypeMarker.isType(DeploymentType.WAR, deploymentUnit)) {
     metaInf = root.getRoot().getChild("WEB-INF/classes/META-INF");
   } else {
     metaInf = root.getRoot().getChild("META-INF");
   }
   final VirtualFile jobXmlFile = metaInf.getChild("batch.xml");
   final VirtualFile batchJobsDir = metaInf.getChild("batch-jobs");
   return (jobXmlFile.exists()
       || (batchJobsDir.exists() && !batchJobsDir.getChildren().isEmpty()));
 }
  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);
  }
  /**
   * Finds a ejb-jar.xml (at WEB-INF of a .war or META-INF of a .jar) parses the file and creates
   * metadata out of it. The metadata is then attached to the deployment unit.
   *
   * @param deploymentPhase
   * @throws DeploymentUnitProcessingException
   */
  @Override
  public void deploy(DeploymentPhaseContext deploymentPhase)
      throws DeploymentUnitProcessingException {

    // get hold of the deployment unit.
    DeploymentUnit deploymentUnit = deploymentPhase.getDeploymentUnit();

    // get the root of the deployment unit
    VirtualFile deploymentRoot =
        deploymentUnit.getAttachment(Attachments.DEPLOYMENT_ROOT).getRoot();

    // Locate a ejb-jar.xml
    VirtualFile ejbJarXml = null;
    // EJB 3.1 FR 20.4 Enterprise Beans Packaged in a .war
    // TODO: Is there a better way to do this?
    if (deploymentRoot.getName().toLowerCase().endsWith(WAR_FILE_EXTENSION)) {
      // it's a .war file, so look for the ejb-jar.xml in WEB-INF
      ejbJarXml = deploymentRoot.getChild(EJB_JAR_XML_LOCATION_IN_WAR);
    } else if (deploymentRoot.getName().toLowerCase().endsWith(JAR_FILE_EXTENSION)) {
      ejbJarXml = deploymentRoot.getChild(EJB_JAR_XML_LOCATION_IN_JAR);
    } else {
      // neither a .jar nor a .war. Return
      return;
    }

    if (ejbJarXml == null || !ejbJarXml.exists()) {
      // no ejb-jar.xml found, nothing to do!
      return;
    }
    // Mark it as a EJB deployment
    EjbDeploymentMarker.mark(deploymentUnit);
    if (!deploymentUnit.hasAttachment(EjbDeploymentAttachmentKeys.EJB_JAR_DESCRIPTION)) {
      final EEModuleDescription moduleDescription =
          deploymentUnit.getAttachment(org.jboss.as.ee.component.Attachments.EE_MODULE_DESCRIPTION);
      final EjbJarDescription ejbModuleDescription = new EjbJarDescription(moduleDescription);
      deploymentUnit.putAttachment(
          EjbDeploymentAttachmentKeys.EJB_JAR_DESCRIPTION, ejbModuleDescription);
    }

    // get the XMLStreamReader and parse the ejb-jar.xml
    MetaDataElementParser.DTDInfo dtdInfo = new MetaDataElementParser.DTDInfo();
    InputStream stream = null;
    try {
      stream = ejbJarXml.openStream();

      XMLStreamReader reader = this.getXMLStreamReader(stream, ejbJarXml, dtdInfo);

      EjbJarMetaData ejbJarMetaData = EjbJarMetaDataParser.parse(reader, dtdInfo);
      // attach the EjbJarMetaData to the deployment unit
      deploymentUnit.putAttachment(EjbDeploymentAttachmentKeys.EJB_JAR_METADATA, ejbJarMetaData);

    } catch (XMLStreamException xmlse) {
      throw new DeploymentUnitProcessingException(
          "Exception while parsing ejb-jar.xml: " + ejbJarXml.getPathName(), xmlse);
    } catch (IOException ioe) {
      throw new DeploymentUnitProcessingException(
          "Failed to create reader for ejb-jar.xml: " + ejbJarXml.getPathName(), ioe);
    } finally {
      try {
        if (stream != null) {
          stream.close();
        }
      } catch (IOException ioe) {
        logger.debug("Ignoring exception while closing the InputStream ", ioe);
      }
    }
  }
  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);
  }