@Override
  public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException {
    DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();

    ClojureMetaData metaData = deploymentUnit.getAttachment(ClojureMetaData.ATTACHMENT_KEY);

    if (metaData == null) {
      return;
    }

    Timer t = new Timer("reading full app config");
    ResourceRoot resourceRoot = deploymentUnit.getAttachment(Attachments.DEPLOYMENT_ROOT);
    File root;
    File descriptor = deploymentUnit.getAttachment(ClojureMetaData.DESCRIPTOR_FILE);
    try {
      root = resourceRoot.getRoot().getPhysicalFile();
      metaData.setConfig(ApplicationBootstrapUtils.readFullAppConfig(descriptor, root));
      deploymentUnit.putAttachment(
          ClojureMetaData.FULL_APP_CONFIG,
          ApplicationBootstrapUtils.readFullAppConfigAsString(descriptor, root));
      deploymentUnit.putAttachment(
          ClojureMetaData.LEIN_PROJECT,
          ApplicationBootstrapUtils.readProjectAsString(descriptor, root));
    } catch (Exception e) {
      throw new DeploymentUnitProcessingException(e);
    }
    t.done();
  }
  public void deploy(final DeploymentPhaseContext phaseContext)
      throws DeploymentUnitProcessingException {
    final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();
    if (!DeploymentTypeMarker.isType(DeploymentType.EAR, deploymentUnit)) {
      return;
    }
    final ResourceRoot deploymentRoot =
        deploymentUnit.getAttachment(org.jboss.as.server.deployment.Attachments.DEPLOYMENT_ROOT);
    final VirtualFile deploymentFile = deploymentRoot.getRoot();
    final VirtualFile applicationXmlFile = deploymentFile.getChild(JBOSS_APP_XML);
    if (!applicationXmlFile.exists()) {
      return;
    }

    InputStream inputStream = null;
    try {
      inputStream = applicationXmlFile.openStream();
      final XMLInputFactory inputFactory = XMLInputFactory.newInstance();
      inputFactory.setXMLResolver(NoopXmlResolver.create());
      XMLStreamReader xmlReader = inputFactory.createXMLStreamReader(inputStream);
      final JBossAppMetaData appMetaData = JBossAppMetaDataParser.parse(xmlReader);
      if (appMetaData != null) {
        final EarMetaData earMetaData = deploymentUnit.getAttachment(Attachments.EAR_METADATA);
        if (earMetaData != null) {
          JBossAppMetaDataMerger.merge(appMetaData, null, earMetaData);
        }
        deploymentUnit.putAttachment(Attachments.JBOSS_APP_METADATA, appMetaData);
      }
    } catch (Exception e) {
      throw new DeploymentUnitProcessingException("Failed to parse " + applicationXmlFile, e);
    } finally {
      VFSUtils.safeClose(inputStream);
    }
  }
  @Override
  public Set<String> getUpdatedResources(
      final String deploymentName, final Map<String, Long> updatedResources) {
    final ModuleIdentifier moduleId = getModuleIdentifier(deploymentName);
    final ModuleClassLoader loader = loadersByModuleIdentifier.get(moduleId);
    if (loader == null) {
      return Collections.emptySet();
    }

    final DeploymentUnit deploymentUnit =
        (DeploymentUnit)
            CurrentServiceRegistry.getServiceRegistry()
                .getRequiredService(Services.deploymentUnitName(deploymentName))
                .getValue();
    final ResourceRoot root = deploymentUnit.getAttachment(Attachments.DEPLOYMENT_ROOT);

    final Set<String> resources = new HashSet<String>();
    for (final Map.Entry<String, Long> entry : updatedResources.entrySet()) {
      final VirtualFile file = root.getRoot().getChild(entry.getKey());
      if (file.exists()) {
        long last = file.getLastModified();
        if (entry.getValue() > last) {
          resources.add(entry.getKey());
        }
      }
    }
    return resources;
  }
  protected VirtualFile getFile(DeploymentUnit unit)
      throws DeploymentUnitProcessingException, IOException {
    List<VirtualFile> matches = new ArrayList<VirtualFile>();

    ResourceRoot resourceRoot = unit.getAttachment(Attachments.DEPLOYMENT_ROOT);
    if (resourceRoot == null) {
      return null;
    }
    VirtualFile root = resourceRoot.getRoot();

    if (this.knobFilter.accepts(root)) {
      return root;
    }

    matches = root.getChildren(this.knobFilter);

    if (matches.size() > 1) {
      throw new DeploymentUnitProcessingException("Multiple Immutant descriptors found in " + root);
    }

    VirtualFile file = null;
    if (matches.size() == 1) {
      file = matches.get(0);
    }

    return file;
  }
  public void deploy(final DeploymentPhaseContext phaseContext)
      throws DeploymentUnitProcessingException {
    final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();
    final List<ResourceRoot> childRoots = deploymentUnit.getAttachment(Attachments.RESOURCE_ROOTS);

    if (childRoots != null) {
      final ServiceTarget serviceTarget = phaseContext.getServiceTarget();
      for (final ResourceRoot childRoot : childRoots) {
        if (!SubDeploymentMarker.isSubDeployment(childRoot)) {
          continue;
        }
        final SubDeploymentUnitService service =
            new SubDeploymentUnitService(childRoot, deploymentUnit);
        final ServiceName serviceName =
            deploymentUnit.getServiceName().append(childRoot.getRootName());

        serviceTarget
            .addService(serviceName, service)
            .addDependency(
                Services.JBOSS_DEPLOYMENT_CHAINS,
                DeployerChains.class,
                service.getDeployerChainsInjector())
            .setInitialMode(ServiceController.Mode.ACTIVE)
            .install();
        phaseContext.addDeploymentDependency(serviceName, Attachments.SUB_DEPLOYMENTS);
      }
    }
  }
  @Override
  public void updateResource(
      final String archiveName, final Map<String, byte[]> replacedResources) {
    final ModuleIdentifier moduleId = getModuleIdentifier(archiveName);
    final ModuleClassLoader loader = loadersByModuleIdentifier.get(moduleId);
    if (loader == null) {
      return;
    }

    final DeploymentUnit deploymentUnit =
        (DeploymentUnit)
            CurrentServiceRegistry.getServiceRegistry()
                .getRequiredService(Services.deploymentUnitName(archiveName))
                .getValue();
    final ResourceRoot root = deploymentUnit.getAttachment(Attachments.DEPLOYMENT_ROOT);

    for (final Map.Entry<String, byte[]> entry : replacedResources.entrySet()) {
      final VirtualFile file = root.getRoot().getChild(entry.getKey());
      try {
        final FileOutputStream stream = new FileOutputStream(file.getPhysicalFile(), false);
        try {
          stream.write(entry.getValue());
        } finally {
          stream.close();
        }
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }
 public void undeploy(DeploymentUnit context) {
   final List<ResourceRoot> childRoots = context.removeAttachment(Attachments.RESOURCE_ROOTS);
   if (childRoots != null) {
     for (ResourceRoot childRoot : childRoots) {
       VFSUtils.safeClose(childRoot.getMountHandle());
     }
   }
 }
Exemple #8
0
  public void deploy(final DeploymentPhaseContext phaseContext)
      throws DeploymentUnitProcessingException {
    final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();
    final WarMetaData warMetaData = deploymentUnit.getAttachment(WarMetaData.ATTACHMENT_KEY);
    if (warMetaData == null) {
      return; // Nothing we can do without WarMetaData
    }
    final ResourceRoot deploymentRoot =
        deploymentUnit.getAttachment(org.jboss.as.server.deployment.Attachments.DEPLOYMENT_ROOT);
    if (deploymentRoot == null) {
      return; // We don't have a root to work with
    }

    final DeploymentUnit parent = deploymentUnit.getParent();
    if (parent == null || !DeploymentTypeMarker.isType(DeploymentType.EAR, parent)) {
      return; // Only care if this war is nested in an EAR
    }

    final EarMetaData earMetaData = parent.getAttachment(Attachments.EAR_METADATA);
    if (earMetaData == null) {
      return; // Nothing to see here
    }

    final ModulesMetaData modulesMetaData = earMetaData.getModules();
    if (modulesMetaData != null)
      for (ModuleMetaData moduleMetaData : modulesMetaData) {
        if (Web.equals(moduleMetaData.getType())
            && moduleMetaData.getFileName().equals(deploymentRoot.getRootName())) {
          String contextRoot =
              WebModuleMetaData.class.cast(moduleMetaData.getValue()).getContextRoot();

          if (contextRoot == null
              && (warMetaData.getJbossWebMetaData() == null
                  || warMetaData.getJbossWebMetaData().getContextRoot() == null)) {
            contextRoot =
                "/"
                    + parent.getName().substring(0, parent.getName().length() - 4)
                    + "/"
                    + deploymentUnit.getName().substring(0, deploymentUnit.getName().length() - 4);
          }

          if (contextRoot != null) {
            JBossWebMetaData jBossWebMetaData = warMetaData.getJbossWebMetaData();
            if (jBossWebMetaData == null) {
              jBossWebMetaData = new JBoss70WebMetaData();
              warMetaData.setJbossWebMetaData(jBossWebMetaData);
            }
            jBossWebMetaData.setContextRoot(contextRoot);
          }
          return;
        }
      }
  }
 private Set<ViewDescription> getViews(final DeploymentPhaseContext phaseContext) {
   final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();
   final EEApplicationDescription applicationDescription =
       deploymentUnit.getAttachment(EE_APPLICATION_DESCRIPTION);
   final ResourceRoot deploymentRoot = deploymentUnit.getAttachment(Attachments.DEPLOYMENT_ROOT);
   final Set<ViewDescription> componentsForViewName;
   if (beanName != null) {
     componentsForViewName =
         applicationDescription.getComponents(beanName, typeName, deploymentRoot.getRoot());
   } else {
     componentsForViewName = applicationDescription.getComponentsForViewName(typeName);
   }
   return componentsForViewName;
 }
 public void undeploy(DeploymentUnit deploymentUnit) {
   final List<ResourceRoot> childRoots = deploymentUnit.getAttachment(Attachments.RESOURCE_ROOTS);
   if (childRoots != null) {
     final ServiceRegistry serviceRegistry = deploymentUnit.getServiceRegistry();
     for (final ResourceRoot childRoot : childRoots) {
       if (!SubDeploymentMarker.isSubDeployment(childRoot)) {
         continue;
       }
       final ServiceName serviceName =
           deploymentUnit.getServiceName().append(childRoot.getRootName());
       final ServiceController<?> serviceController = serviceRegistry.getService(serviceName);
       if (serviceController != null) {
         serviceController.setMode(ServiceController.Mode.REMOVE);
       }
     }
   }
 }
  @Test
  public void testLoadCorrectJbossWeb() throws Exception {
    final VirtualFile jbossWebxml = mock(VirtualFile.class);
    when(jbossWebxml.exists()).thenReturn(Boolean.TRUE);
    when(jbossWebxml.openStream())
        .thenReturn(
            JBossWebParsingDeploymentProcessorTest.class.getResourceAsStream("jboss-web.xml"));

    final VirtualFile deploymentRoot = mock(VirtualFile.class);
    when(deploymentRoot.getChild("WEB-INF/jboss-web.xml")).thenReturn(jbossWebxml);

    final ResourceRoot resourceRoot = mock(ResourceRoot.class);
    when(resourceRoot.getRoot()).thenReturn(deploymentRoot);
    when(deploymentUnit.getAttachment(org.jboss.as.server.deployment.Attachments.DEPLOYMENT_ROOT))
        .thenReturn(resourceRoot);
    processor.deploy(phaseContext);
  }
 private void handlingExistingClassPathEntry(
     final DeploymentUnit deploymentUnit,
     final ArrayDeque<RootEntry> resourceRoots,
     final DeploymentUnit topLevelDeployment,
     final VirtualFile topLevelRoot,
     final Map<VirtualFile, ResourceRoot> subDeployments,
     final Map<VirtualFile, AdditionalModuleSpecification> additionalModules,
     final Set<VirtualFile> existingAccessibleRoots,
     final ResourceRoot resourceRoot,
     final Attachable target,
     final VirtualFile classPathFile)
     throws DeploymentUnitProcessingException {
   if (existingAccessibleRoots.contains(classPathFile)) {
     ServerLogger.DEPLOYMENT_LOGGER.debugf(
         "Class-Path entry %s in %s ignored, as target is already accessible",
         classPathFile, resourceRoot.getRoot());
   } else if (additionalModules.containsKey(classPathFile)) {
     final AdditionalModuleSpecification moduleSpecification =
         additionalModules.get(classPathFile);
     // as class path entries are exported, transitive dependencies will also be available
     target.addToAttachmentList(
         Attachments.CLASS_PATH_ENTRIES, moduleSpecification.getModuleIdentifier());
   } else if (subDeployments.containsKey(classPathFile)) {
     // now we need to calculate the sub deployment module identifier
     // unfortunately the sub deployment has not been setup yet, so we cannot just
     // get it from the sub deployment directly
     final ResourceRoot otherRoot = subDeployments.get(classPathFile);
     target.addToAttachmentList(
         Attachments.CLASS_PATH_ENTRIES,
         ModuleIdentifierProcessor.createModuleIdentifier(
             otherRoot.getRootName(), otherRoot, topLevelDeployment, topLevelRoot, false));
   } else {
     ModuleIdentifier identifier =
         createAdditionalModule(
             resourceRoot,
             topLevelDeployment,
             topLevelRoot,
             additionalModules,
             classPathFile,
             resourceRoots);
     target.addToAttachmentList(Attachments.CLASS_PATH_ENTRIES, identifier);
   }
 }
  private static PersistenceUnitMetadata getPersistenceUnit(
      DeploymentUnit current, final String absolutePath, String puName) {
    final String path;
    if (absolutePath.startsWith("../")) {
      path = absolutePath.substring(3);
    } else {
      path = absolutePath;
    }
    final VirtualFile parent =
        current.getAttachment(Attachments.DEPLOYMENT_ROOT).getRoot().getParent();
    final VirtualFile resolvedPath = parent.getChild(path);

    List<ResourceRoot> resourceRoots =
        DeploymentUtils.allResourceRoots(DeploymentUtils.getTopDeploymentUnit(current));

    for (ResourceRoot resourceRoot : resourceRoots) {
      if (resourceRoot.getRoot().equals(resolvedPath)) {
        PersistenceUnitMetadataHolder holder =
            resourceRoot.getAttachment(PersistenceUnitMetadataHolder.PERSISTENCE_UNITS);
        if (holder != null) {
          for (PersistenceUnitMetadata pu : holder.getPersistenceUnits()) {
            if (traceEnabled) {
              ROOT_LOGGER.tracef(
                  "getPersistenceUnit check '%s' against pu '%s'",
                  puName, pu.getPersistenceUnitName());
            }
            if (pu.getPersistenceUnitName().equals(puName)) {
              if (traceEnabled) {
                ROOT_LOGGER.tracef(
                    "getPersistenceUnit matched '%s' against pu '%s'",
                    puName, pu.getPersistenceUnitName());
              }
              return pu;
            }
          }
        }
      }
    }

    throw MESSAGES.persistenceUnitNotFound(absolutePath, puName, current);
  }
 /**
  * Find the logging profile attached to any resource.
  *
  * @param resourceRoot the root resource
  * @return the logging profile name or {@code null} if one was not found
  */
 private String findLoggingProfile(final ResourceRoot resourceRoot) {
   final Manifest manifest = resourceRoot.getAttachment(Attachments.MANIFEST);
   if (manifest != null) {
     final String loggingProfile = manifest.getMainAttributes().getValue(LOGGING_PROFILE);
     if (loggingProfile != null) {
       LoggingLogger.ROOT_LOGGER.debugf(
           "Logging profile '%s' found in '%s'.", loggingProfile, resourceRoot);
       return loggingProfile;
     }
   }
   return null;
 }
  /*
   * When finding the default persistence unit, the first persistence unit encountered is returned.
   */
  private static PersistenceUnitMetadata findWithinDeployment(
      DeploymentUnit unit, String persistenceUnitName) {
    if (traceEnabled) {
      ROOT_LOGGER.tracef("pu findWithinDeployment searching for %s", persistenceUnitName);
    }

    for (ResourceRoot root : DeploymentUtils.allResourceRoots(unit)) {
      PersistenceUnitMetadataHolder holder =
          root.getAttachment(PersistenceUnitMetadataHolder.PERSISTENCE_UNITS);
      if (holder == null || holder.getPersistenceUnits() == null) {
        if (traceEnabled) {
          ROOT_LOGGER.tracef(
              "pu findWithinDeployment skipping empty pu holder for %s", persistenceUnitName);
        }
        continue;
      }

      ambiguousPUError(unit, persistenceUnitName, holder);
      persistenceUnitName = defaultPersistenceUnitName(persistenceUnitName, holder);

      for (PersistenceUnitMetadata persistenceUnit : holder.getPersistenceUnits()) {
        if (traceEnabled) {
          ROOT_LOGGER.tracef(
              "findWithinDeployment check '%s' against pu '%s'",
              persistenceUnitName, persistenceUnit.getPersistenceUnitName());
        }
        if (persistenceUnitName == null
            || persistenceUnitName.length() == 0
            || persistenceUnit.getPersistenceUnitName().equals(persistenceUnitName)) {
          if (traceEnabled) {
            ROOT_LOGGER.tracef(
                "findWithinDeployment matched '%s' against pu '%s'",
                persistenceUnitName, persistenceUnit.getPersistenceUnitName());
          }
          return persistenceUnit;
        }
      }
    }
    return null;
  }
  /**
   * Creates new Web Service deployment.
   *
   * @param unit deployment unit
   * @return archive deployment
   */
  private ArchiveDeployment newDeployment(final DeploymentUnit unit) {
    ROOT_LOGGER.creatingUnifiedWebservicesDeploymentModel(unit);
    final ResourceRoot deploymentRoot = unit.getAttachment(Attachments.DEPLOYMENT_ROOT);
    final VirtualFile root = deploymentRoot != null ? deploymentRoot.getRoot() : null;
    final ClassLoader classLoader;
    final Module module = unit.getAttachment(Attachments.MODULE);
    if (module == null) {
      classLoader = unit.getAttachment(CLASSLOADER_KEY);
      if (classLoader == null) {
        throw MESSAGES.classLoaderResolutionFailed(unit);
      }
    } else {
      classLoader = module.getClassLoader();
    }
    final ArchiveDeployment dep = this.newDeployment(unit.getName(), classLoader);

    if (unit.getParent() != null) {
      final String parentDeploymentName = unit.getParent().getName();
      final Module parentModule = unit.getParent().getAttachment(Attachments.MODULE);
      if (parentModule == null) {
        throw MESSAGES.classLoaderResolutionFailed(deploymentRoot);
      }
      final ClassLoader parentClassLoader = parentModule.getClassLoader();

      ROOT_LOGGER.creatingUnifiedWebservicesDeploymentModel(unit.getParent());
      final ArchiveDeployment parentDep =
          this.newDeployment(parentDeploymentName, parentClassLoader);
      dep.setParent(parentDep);
    }

    if (root != null) {
      dep.setRootFile(new VirtualFileAdaptor(root));
    } else {
      dep.setRootFile(new ResourceLoaderAdapter(classLoader));
    }
    dep.setRuntimeClassLoader(classLoader);
    dep.setType(deploymentType);

    return dep;
  }
  @Override
  protected void doDeploy(DeploymentPhaseContext phaseContext)
      throws DeploymentUnitProcessingException {
    final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();
    final WarMetaData warMetaData = deploymentUnit.getAttachment(WarMetaData.ATTACHMENT_KEY);
    final ResourceRoot deploymentRoot =
        deploymentUnit.getAttachment(org.jboss.as.server.deployment.Attachments.DEPLOYMENT_ROOT);
    final DeploymentUnit parent = deploymentUnit.getParent();
    final EarMetaData earMetaData = parent.getAttachment(Attachments.EAR_METADATA);
    final ModulesMetaData modulesMetaData = earMetaData.getModules();
    if (modulesMetaData != null)
      for (ModuleMetaData moduleMetaData : modulesMetaData) {
        if (Web.equals(moduleMetaData.getType())
            && moduleMetaData.getFileName().equals(deploymentRoot.getRootName())) {
          String contextRoot =
              WebModuleMetaData.class.cast(moduleMetaData.getValue()).getContextRoot();

          if (contextRoot == null
              && (warMetaData.getJbossWebMetaData() == null
                  || warMetaData.getJbossWebMetaData().getContextRoot() == null)) {
            contextRoot =
                "/"
                    + parent.getName().substring(0, parent.getName().length() - 4)
                    + "/"
                    + deploymentUnit.getName().substring(0, deploymentUnit.getName().length() - 4);
          }

          if (contextRoot != null) {
            JBossWebMetaData jBossWebMetaData = warMetaData.getJbossWebMetaData();
            if (jBossWebMetaData == null) {
              // jBossWebMetaData = new JBoss70WebMetaData();
              jBossWebMetaData = new JBoss70ConvergedSipMetaData(); // josemrecio
              warMetaData.setJbossWebMetaData(jBossWebMetaData);
            }
            jBossWebMetaData.setContextRoot(contextRoot);
          }
          return;
        }
      }
  }
 /**
  * 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()));
 }
  public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException {
    final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();
    final ResourceRoot resourceRoot = deploymentUnit.getAttachment(Attachments.DEPLOYMENT_ROOT);
    if (resourceRoot == null) {
      return;
    }
    final VirtualFile deploymentRoot = resourceRoot.getRoot();
    if (deploymentRoot == null || !deploymentRoot.exists()) {
      return;
    }

    final String deploymentRootName = deploymentRoot.getLowerCaseName();
    if (!deploymentRootName.endsWith(RAR_EXTENSION)) {
      return;
    }
    // we do not load classes from the module resource root
    ModuleRootMarker.mark(resourceRoot, false);

    try {
      final List<VirtualFile> childArchives = deploymentRoot.getChildren(CHILD_ARCHIVE_FILTER);

      for (final VirtualFile child : childArchives) {
        final Closeable closable =
            child.isFile()
                ? VFS.mountZip(child, child, TempFileProviderService.provider())
                : NO_OP_CLOSEABLE;
        final MountHandle mountHandle = new MountHandle(closable);
        final ResourceRoot childResource = new ResourceRoot(child, mountHandle);
        ModuleRootMarker.mark(childResource);
        deploymentUnit.addToAttachmentList(Attachments.RESOURCE_ROOTS, childResource);
        resourceRoot.addToAttachmentList(
            Attachments.INDEX_IGNORE_PATHS, child.getPathNameRelativeTo(deploymentRoot));
      }
    } catch (IOException e) {
      throw new DeploymentUnitProcessingException(
          "Failed to process RA child archives for [" + deploymentRoot + "]", e);
    }
  }
 private static String[] getClassPathEntries(final ResourceRoot resourceRoot) {
   final Manifest manifest = resourceRoot.getAttachment(Attachments.MANIFEST);
   if (manifest == null) {
     // no class path to process!
     return EMPTY_STRING_ARRAY;
   }
   final String classPathString =
       manifest.getMainAttributes().getValue(Attributes.Name.CLASS_PATH);
   if (classPathString == null) {
     // no entry
     return EMPTY_STRING_ARRAY;
   }
   return classPathString.split("\\s+");
 }
  @Test
  public void testLoadIncorrectJbossWeb() throws Exception {
    expectedException.expect(DeploymentUnitProcessingException.class);
    expectedException.expectMessage(
        "JBAS018014: Failed to parse XML descriptor \"/content/basic.war/WEB-INF/jboss-web.xml\" at [4,5]");

    final VirtualFile jbossWebxml = mock(VirtualFile.class);
    when(jbossWebxml.exists()).thenReturn(Boolean.TRUE);
    when(jbossWebxml.openStream())
        .thenReturn(
            JBossWebParsingDeploymentProcessorTest.class.getResourceAsStream(
                "jboss-error-web.xml"));
    when(jbossWebxml.toString()).thenReturn("\"/content/basic.war/WEB-INF/jboss-web.xml\"");

    final VirtualFile deploymentRoot = mock(VirtualFile.class);
    when(deploymentRoot.getChild("WEB-INF/jboss-web.xml")).thenReturn(jbossWebxml);

    final ResourceRoot resourceRoot = mock(ResourceRoot.class);
    when(resourceRoot.getRoot()).thenReturn(deploymentRoot);
    when(deploymentUnit.getAttachment(org.jboss.as.server.deployment.Attachments.DEPLOYMENT_ROOT))
        .thenReturn(resourceRoot);
    processor.deploy(phaseContext);
  }
  private static PersistenceUnitMetadata findWithinLibraryJar(
      DeploymentUnit unit, ResourceRoot moduleResourceRoot, String persistenceUnitName) {

    final ResourceRoot deploymentRoot = moduleResourceRoot;
    PersistenceUnitMetadataHolder holder =
        deploymentRoot.getAttachment(PersistenceUnitMetadataHolder.PERSISTENCE_UNITS);
    if (holder == null || holder.getPersistenceUnits() == null) {
      if (traceEnabled) {
        ROOT_LOGGER.tracef(
            "findWithinLibraryJar checking for '%s' found no persistence units",
            persistenceUnitName);
      }
      return null;
    }

    ambiguousPUError(unit, persistenceUnitName, holder);
    persistenceUnitName = defaultPersistenceUnitName(persistenceUnitName, holder);

    for (PersistenceUnitMetadata persistenceUnit : holder.getPersistenceUnits()) {
      if (traceEnabled) {
        ROOT_LOGGER.tracef(
            "findWithinLibraryJar check '%s' against pu '%s'",
            persistenceUnitName, persistenceUnit.getPersistenceUnitName());
      }
      if (persistenceUnitName == null
          || persistenceUnitName.length() == 0
          || persistenceUnit.getPersistenceUnitName().equals(persistenceUnitName)) {
        if (traceEnabled) {
          ROOT_LOGGER.tracef(
              "findWithinLibraryJar matched '%s' against pu '%s'",
              persistenceUnitName, persistenceUnit.getPersistenceUnitName());
        }
        return persistenceUnit;
      }
    }
    return null;
  }
  private ModuleIdentifier createAdditionalModule(
      final ResourceRoot resourceRoot,
      final DeploymentUnit topLevelDeployment,
      final VirtualFile topLevelRoot,
      final Map<VirtualFile, AdditionalModuleSpecification> additionalModules,
      final VirtualFile classPathFile,
      final ArrayDeque<RootEntry> resourceRoots)
      throws DeploymentUnitProcessingException {
    final ResourceRoot root = createResourceRoot(classPathFile);

    final String pathName = root.getRoot().getPathNameRelativeTo(topLevelRoot);
    ModuleIdentifier identifier =
        ModuleIdentifier.create(
            ServiceModuleLoader.MODULE_PREFIX + topLevelDeployment.getName() + "." + pathName);
    AdditionalModuleSpecification module = new AdditionalModuleSpecification(identifier, root);
    topLevelDeployment.addToAttachmentList(Attachments.ADDITIONAL_MODULES, module);
    additionalModules.put(classPathFile, module);
    resourceRoot.addToAttachmentList(Attachments.CLASS_PATH_RESOURCE_ROOTS, root);

    // add this to the list of roots to be processed, so transitive class path entries will be
    // respected
    resourceRoots.add(new RootEntry(module, root));
    return identifier;
  }
  private static String[] getClassPathEntries(final ResourceRoot resourceRoot) {

    final Manifest manifest;
    try {
      manifest = VFSUtils.getManifest(resourceRoot.getRoot());
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
    if (manifest == null) {
      // no class path to process!
      return EMPTY_STRING_ARRAY;
    }
    final String classPathString =
        manifest.getMainAttributes().getValue(Attributes.Name.CLASS_PATH);
    if (classPathString == null) {
      // no entry
      return EMPTY_STRING_ARRAY;
    }
    return classPathString.split("\\s+");
  }
 private static UnifiedVirtualFile getUnifiedVirtualFile(
     final DeploymentUnit deploymentUnit) { // TODO: refactor to common code
   final ResourceRoot resourceRoot =
       deploymentUnit.getAttachment(org.jboss.as.server.deployment.Attachments.DEPLOYMENT_ROOT);
   return new VirtualFileAdaptor(resourceRoot.getRoot());
 }
  @Override
  public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException {
    final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();
    if (!DeploymentTypeMarker.isType(DeploymentType.WAR, deploymentUnit)) {
      return; // Skip non web deployments
    }
    final ResourceRoot deploymentRoot = deploymentUnit.getAttachment(Attachments.DEPLOYMENT_ROOT);
    final VirtualFile alternateDescriptor =
        deploymentRoot.getAttachment(
            org.jboss.as.ee.structure.Attachments.ALTERNATE_WEB_DEPLOYMENT_DESCRIPTOR);
    // Locate the descriptor
    final VirtualFile webXml;
    if (alternateDescriptor != null) {
      webXml = alternateDescriptor;
    } else {
      webXml = deploymentRoot.getRoot().getChild(WEB_XML);
    }
    final WarMetaData warMetaData = deploymentUnit.getAttachment(WarMetaData.ATTACHMENT_KEY);
    assert warMetaData != null;
    if (webXml.exists()) {
      InputStream is = null;
      try {
        is = webXml.openStream();
        final XMLInputFactory inputFactory = XMLInputFactory.newInstance();

        MetaDataElementParser.DTDInfo dtdInfo = new MetaDataElementParser.DTDInfo();
        inputFactory.setXMLResolver(dtdInfo);
        final XMLStreamReader xmlReader = inputFactory.createXMLStreamReader(is);

        WebMetaData webMetaData =
            WebMetaDataParser.parse(
                xmlReader,
                dtdInfo,
                SpecDescriptorPropertyReplacement.propertyReplacer(deploymentUnit));

        if (schemaValidation && webMetaData.getSchemaLocation() != null) {
          XMLSchemaValidator validator = new XMLSchemaValidator(new XMLResourceResolver());
          InputStream xmlInput = webXml.openStream();
          try {
            if (webMetaData.is23())
              validator.validate(
                  "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN", xmlInput);
            else if (webMetaData.is24())
              validator.validate("http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd", xmlInput);
            else if (webMetaData.is25())
              validator.validate("http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd", xmlInput);
            else if (webMetaData.is30())
              validator.validate("http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd", xmlInput);
            else if (webMetaData.is31())
              validator.validate("http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd", xmlInput);
            else
              validator.validate(
                  "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN", xmlInput);
          } catch (SAXException e) {
            throw new DeploymentUnitProcessingException("Failed to validate " + webXml, e);
          } finally {
            xmlInput.close();
          }
        }
        warMetaData.setWebMetaData(webMetaData);

      } catch (XMLStreamException e) {
        throw new DeploymentUnitProcessingException(
            MESSAGES.failToParseXMLDescriptor(
                webXml, e.getLocation().getLineNumber(), e.getLocation().getColumnNumber()));
      } catch (IOException e) {
        throw new DeploymentUnitProcessingException(MESSAGES.failToParseXMLDescriptor(webXml), e);
      } finally {
        try {
          if (is != null) {
            is.close();
          }
        } catch (IOException e) {
          // Ignore
        }
      }
    }
  }
  /**
   * We only allow a single deployment at a time to be run through the class path processor.
   *
   * <p>This is because if multiple sibling deployments reference the same item we need to make sure
   * that they end up with the same external module, and do not both create an external module with
   * the same name.
   */
  public synchronized void deploy(final DeploymentPhaseContext phaseContext)
      throws DeploymentUnitProcessingException {
    final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();

    final DeploymentUnit parent = deploymentUnit.getParent();
    final DeploymentUnit topLevelDeployment = parent == null ? deploymentUnit : parent;
    final VirtualFile topLevelRoot =
        topLevelDeployment.getAttachment(Attachments.DEPLOYMENT_ROOT).getRoot();
    final ExternalModuleService externalModuleService =
        topLevelDeployment.getAttachment(Attachments.EXTERNAL_MODULE_SERVICE);
    final ResourceRoot deploymentRoot = deploymentUnit.getAttachment(Attachments.DEPLOYMENT_ROOT);

    // These are resource roots that are already accessible by default
    // such as ear/lib jars an web-inf/lib jars
    final Set<VirtualFile> existingAccessibleRoots = new HashSet<VirtualFile>();

    final Map<VirtualFile, ResourceRoot> subDeployments = new HashMap<VirtualFile, ResourceRoot>();
    for (ResourceRoot root : DeploymentUtils.allResourceRoots(topLevelDeployment)) {
      if (SubDeploymentMarker.isSubDeployment(root)) {
        subDeployments.put(root.getRoot(), root);
      } else if (ModuleRootMarker.isModuleRoot(root)) {
        // top level module roots are already accessible, as they are either
        // ear/lib jars, or jars that are already part of the deployment
        existingAccessibleRoots.add(root.getRoot());
      }
    }

    final ArrayDeque<RootEntry> resourceRoots = new ArrayDeque<RootEntry>();
    if (deploymentUnit.getParent() != null) {
      // top level deployments already had their exiting roots processed above
      for (ResourceRoot root : DeploymentUtils.allResourceRoots(deploymentUnit)) {

        if (ModuleRootMarker.isModuleRoot(root)) {
          // if this is a sub deployment of an ear we need to make sure we don't
          // re-add existing module roots as class path entries
          // this will mainly be WEB-INF/(lib|classes) entries
          existingAccessibleRoots.add(root.getRoot());
        }
      }
    }

    for (ResourceRoot root : DeploymentUtils.allResourceRoots(deploymentUnit)) {
      // add this to the list of roots to be processed
      resourceRoots.add(new RootEntry(deploymentUnit, root));
    }

    // build a map of the additional module locations
    // note that if a resource root has been added to two different additional modules
    // and is then referenced via a Class-Path entry the behaviour is undefined
    final Map<VirtualFile, AdditionalModuleSpecification> additionalModules =
        new HashMap<VirtualFile, AdditionalModuleSpecification>();
    for (AdditionalModuleSpecification module :
        topLevelDeployment.getAttachmentList(Attachments.ADDITIONAL_MODULES)) {
      for (ResourceRoot additionalModuleResourceRoot : module.getResourceRoots()) {
        additionalModules.put(additionalModuleResourceRoot.getRoot(), module);
      }
    }

    // additional resource roots may be added as
    while (!resourceRoots.isEmpty()) {
      final RootEntry entry = resourceRoots.pop();
      final ResourceRoot resourceRoot = entry.resourceRoot;
      final Attachable target = entry.target;

      // if this is a top level deployment we do not want to process sub deployments
      if (SubDeploymentMarker.isSubDeployment(resourceRoot) && resourceRoot != deploymentRoot) {
        continue;
      }

      final String[] items = getClassPathEntries(resourceRoot);
      for (final String item : items) {
        if (item.isEmpty()) {
          continue;
        }
        // first try and resolve relative to the manifest resource root
        final VirtualFile classPathFile = resourceRoot.getRoot().getParent().getChild(item);
        // then resolve relative to the deployment root
        final VirtualFile topLevelClassPathFile =
            deploymentRoot.getRoot().getParent().getChild(item);
        if (item.startsWith("/")) {
          if (externalModuleService.isValid(item)) {
            final ModuleIdentifier moduleIdentifier = externalModuleService.addExternalModule(item);
            target.addToAttachmentList(Attachments.CLASS_PATH_ENTRIES, moduleIdentifier);
            ServerLogger.DEPLOYMENT_LOGGER.debugf(
                "Resource %s added as external jar %s", classPathFile, resourceRoot.getRoot());
          } else {
            ServerLogger.DEPLOYMENT_LOGGER.classPathEntryNotValid(
                item, resourceRoot.getRoot().getPathName());
          }
        } else {
          if (classPathFile.exists()) {
            // we need to check that this class path item actually lies within the deployment
            boolean found = false;
            VirtualFile file = classPathFile.getParent();
            while (file != null) {
              if (file.equals(topLevelRoot)) {
                found = true;
              }
              file = file.getParent();
            }
            if (!found) {
              ServerLogger.DEPLOYMENT_LOGGER.classPathEntryNotValid(
                  item, resourceRoot.getRoot().getPathName());
            } else {
              handlingExistingClassPathEntry(
                  deploymentUnit,
                  resourceRoots,
                  topLevelDeployment,
                  topLevelRoot,
                  subDeployments,
                  additionalModules,
                  existingAccessibleRoots,
                  resourceRoot,
                  target,
                  classPathFile);
            }
          } else if (topLevelClassPathFile.exists()) {
            boolean found = false;
            VirtualFile file = topLevelClassPathFile.getParent();
            while (file != null) {
              if (file.equals(topLevelRoot)) {
                found = true;
              }
              file = file.getParent();
            }
            if (!found) {
              ServerLogger.DEPLOYMENT_LOGGER.classPathEntryNotValid(
                  item, resourceRoot.getRoot().getPathName());
            } else {
              handlingExistingClassPathEntry(
                  deploymentUnit,
                  resourceRoots,
                  topLevelDeployment,
                  topLevelRoot,
                  subDeployments,
                  additionalModules,
                  existingAccessibleRoots,
                  resourceRoot,
                  target,
                  topLevelClassPathFile);
            }
          } else {
            ServerLogger.DEPLOYMENT_LOGGER.classPathEntryNotValid(
                item, resourceRoot.getRoot().getPathName());
          }
        }
      }
    }
  }
 /** {@inheritDoc} */
 public void deploy(final DeploymentPhaseContext phaseContext)
     throws DeploymentUnitProcessingException {
   final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();
   final List<ResourceRoot> resourceRoots = DeploymentUtils.allResourceRoots(deploymentUnit);
   for (ResourceRoot resourceRoot : resourceRoots) {
     final Manifest manifest = resourceRoot.getAttachment(Attachments.MANIFEST);
     if (manifest == null) {
       // no class path to process!
       continue;
     }
     final Attributes mainAttributes = manifest.getMainAttributes();
     final String extensionListString = mainAttributes.getValue(EXTENSION_LIST);
     if (extensionListString == null) {
       // no entry
       continue;
     }
     final String[] items = extensionListString.split("\\s+");
     boolean added = false;
     for (String item : items) {
       final String extensionName = mainAttributes.getValue(item + "-" + EXTENSION_NAME);
       if (extensionName == null) {
         ServerLogger.DEPLOYMENT_LOGGER.extensionMissingManifestAttribute(
             item, item, EXTENSION_NAME);
         continue;
       }
       final String specificationVersion =
           mainAttributes.getValue(item + "-" + SPECIFICATION_VERSION);
       final String implementationVersion =
           mainAttributes.getValue(item + "-" + IMPLEMENTATION_VERSION);
       final String implementationVendorId =
           mainAttributes.getValue(item + "-" + IMPLEMENTATION_VENDOR_ID);
       final String implementationUrl = mainAttributes.getValue(item + "-" + IMPLEMENTATION_URL);
       URI implementationUri = null;
       if (implementationUrl == null) {
         ServerLogger.DEPLOYMENT_LOGGER.debugf(
             "Extension %s is missing the required manifest attribute %s-%s",
             item, item, IMPLEMENTATION_URL);
       } else {
         try {
           implementationUri = new URI(implementationUrl);
         } catch (URISyntaxException e) {
           ServerLogger.DEPLOYMENT_LOGGER.invalidExtensionURI(item, e);
         }
       }
       resourceRoot.addToAttachmentList(
           Attachments.EXTENSION_LIST_ENTRIES,
           new ExtensionListEntry(
               item,
               extensionName,
               specificationVersion,
               implementationVersion,
               implementationVendorId,
               implementationUri));
       added = true;
     }
     if (added) {
       // Require the extension list before we proceed
       phaseContext.addToAttachmentList(
           Attachments.NEXT_PHASE_DEPS, Services.JBOSS_DEPLOYMENT_EXTENSION_INDEX);
     }
   }
 }
  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);
  }
  /** {@inheritDoc} */
  public void deploy(final DeploymentPhaseContext phaseContext)
      throws DeploymentUnitProcessingException {
    final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();
    final List<ResourceRoot> resourceRoots = DeploymentUtils.allResourceRoots(deploymentUnit);

    if (!DeploymentTypeMarker.isType(DeploymentType.EAR, deploymentUnit)) {
      return;
    }

    final DeploymentUnit parent = deploymentUnit.getParent();
    final DeploymentUnit topLevelDeployment = parent == null ? deploymentUnit : parent;
    final VirtualFile toplevelRoot =
        topLevelDeployment.getAttachment(Attachments.DEPLOYMENT_ROOT).getRoot();
    final ExternalModuleService externalModuleService =
        topLevelDeployment.getAttachment(Attachments.EXTERNAL_MODULE_SERVICE);

    final Map<VirtualFile, ResourceRoot> files = new HashMap<VirtualFile, ResourceRoot>();
    for (ResourceRoot resourceRoot : resourceRoots) {
      files.put(resourceRoot.getRoot(), resourceRoot);
    }
    final Deque<ResourceRoot> libResourceRoots = new ArrayDeque<ResourceRoot>();
    // scan /lib entries for class-path items
    for (ResourceRoot resourceRoot : resourceRoots) {
      if (ModuleRootMarker.isModuleRoot(resourceRoot)
          && !SubDeploymentMarker.isSubDeployment(resourceRoot)) {
        libResourceRoots.add(resourceRoot);
      }
    }
    while (!libResourceRoots.isEmpty()) {
      final ResourceRoot resourceRoot = libResourceRoots.pop();
      final String[] items = getClassPathEntries(resourceRoot);
      for (String item : items) {
        final VirtualFile classPathFile = resourceRoot.getRoot().getParent().getChild(item);
        if (!classPathFile.exists()) {
          log.warnf("Class Path entry %s in %s not found. ", item, resourceRoot.getRoot());
        } else if (isInside(classPathFile, toplevelRoot)) {
          if (!files.containsKey(classPathFile)) {
            log.warnf(
                "Class Path entry %s in %s does not point to a valid jar for a Class-Path reference.",
                item, resourceRoot.getRoot());
          } else {
            final ResourceRoot target = files.get(classPathFile);
            if (SubDeploymentMarker.isSubDeployment(target)) {
              // for now we do not allow ear Class-Path references to subdeployments
              log.warnf(
                  "Class Path entry  in "
                      + resourceRoot.getRoot()
                      + "  may not point to a sub deployment.");
            } else if (!ModuleRootMarker.isModuleRoot(target)) {
              // otherwise just add it to the lib dir
              ModuleRootMarker.mark(target);
              libResourceRoots.push(target);
              log.debugf(
                  "Resource %s added to logical lib directory due to Class-Path entry in %s",
                  classPathFile, target.getRoot());
            }
            // otherwise it is already part of lib, so we leave it alone for now
          }
        } else if (item.startsWith("/")) {
          ModuleIdentifier moduleIdentifier = externalModuleService.addExternalModule(item);
          deploymentUnit.addToAttachmentList(Attachments.CLASS_PATH_ENTRIES, moduleIdentifier);
          log.debugf("Resource %s added as external jar %s", classPathFile, resourceRoot.getRoot());
        } else {
          // this is a dep on another deployment
          deploymentUnit.addToAttachmentList(
              Attachments.CLASS_PATH_ENTRIES,
              ModuleIdentifier.create(ServiceModuleLoader.MODULE_PREFIX + classPathFile.getName()));
        }
      }
    }
  }