Process the deployment root for module dependency information.

@param phaseContext the deployment unit context
@throws org.jboss.as.server.deployment.DeploymentUnitProcessingException
356600
public void deploy(final DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException {
        final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();
        final ServiceModuleLoader deploymentModuleLoader = deploymentUnit.getAttachment(Attachments.SERVICE_MODULE_LOADER);
        final List<ResourceRoot> allResourceRoots = DeploymentUtils.allResourceRoots(deploymentUnit);
        DeploymentUnit top = deploymentUnit.getParent() == null ? deploymentUnit : deploymentUnit.getParent();

        Set<ModuleIdentifier> additionalModules = new HashSet<>();
        for(AdditionalModuleSpecification i : top.getAttachmentList(Attachments.ADDITIONAL_MODULES)) {
            additionalModules.add(i.getModuleIdentifier());
        }
        for (final ResourceRoot resourceRoot : allResourceRoots) {
            final Manifest manifest = resourceRoot.getAttachment(Attachments.MANIFEST);
            if (manifest == null)
                continue;

            final String dependencyString = ManifestHelper.getMainAttributeValue(manifest, DEPENDENCIES_ATTR);
            if (dependencyString == null)
                continue;

            if(deploymentUnit.getParent() == null &&
                    SubDeploymentMarker.isSubDeployment(resourceRoot)) {
                //we do not want ears reading sub deployments manifests
                continue;
            }

            final String[] dependencyDefs = dependencyString.split(",");
            for (final String dependencyDef : dependencyDefs) {
                final String trimmed = dependencyDef.trim();
                if(trimmed.isEmpty()) {
                    continue;
                }
                final String[] dependencyParts = trimmed.split(" ");

                final ModuleIdentifier dependencyId = ModuleIdentifier.fromString(dependencyParts[0]);
                final boolean export = containsParam(dependencyParts, EXPORT_PARAM);
                final boolean optional = containsParam(dependencyParts, OPTIONAL_PARAM);
                final boolean services = containsParam(dependencyParts, SERVICES_PARAM);
                final boolean annotations = containsParam(dependencyParts, ANNOTATIONS_PARAM);
                final boolean metaInf = containsParam(dependencyParts, META_INF);
                final ModuleLoader dependencyLoader;
                if (dependencyId.getName().startsWith(ServiceModuleLoader.MODULE_PREFIX)) {
                    dependencyLoader = deploymentModuleLoader;
                } else {
                    dependencyLoader = Module.getBootModuleLoader();
                }
                if(annotations) {
                    deploymentUnit.addToAttachmentList(Attachments.ADDITIONAL_ANNOTATION_INDEXES, dependencyId);
                    if(dependencyLoader == deploymentModuleLoader && !additionalModules.contains(dependencyId)) {
                        //additional modules will not be created till much later, a dep on them would fail
                        phaseContext.addToAttachmentList(Attachments.NEXT_PHASE_DEPS, ServiceModuleLoader.moduleServiceName(dependencyId));
                    }
                }

                final ModuleDependency dependency = new ModuleDependency(dependencyLoader, dependencyId, optional, export, services, true);
                if(metaInf) {
                    dependency.addImportFilter(PathFilters.getMetaInfSubdirectoriesFilter(), true);
                    dependency.addImportFilter(PathFilters.getMetaInfFilter(), true);
                }
                deploymentUnit.addToAttachmentList(Attachments.MANIFEST_DEPENDENCIES, dependency);
            }
        }

    }
340340
public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException {

    DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();

    if(!ProcessApplicationAttachments.isProcessApplication(deploymentUnit)) {
      return;
    }

    final Module module = deploymentUnit.getAttachment(MODULE);

    // read @ProcessApplication annotation of PA-component
    String[] deploymentDescriptors = getDeploymentDescriptors(deploymentUnit);

    // load all processes.xml files
    List<URL> deploymentDescriptorURLs = getDeploymentDescriptorUrls(module, deploymentDescriptors);

    for (URL processesXmlResource : deploymentDescriptorURLs) {
      VirtualFile processesXmlFile = getFile(processesXmlResource);

      // parse processes.xml metadata.
      ProcessesXml processesXml = null;
      if(isEmptyFile(processesXmlResource)) {
        processesXml = ProcessesXml.EMPTY_PROCESSES_XML;
      } else {
        processesXml = parseProcessesXml(processesXmlResource);
      }

      // add the parsed metadata to the attachment list
      ProcessApplicationAttachments.addProcessesXml(deploymentUnit, new ProcessesXmlWrapper(processesXml, processesXmlFile));
    }
  }
952556
@Override
    public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException {

        final DeploymentUnit deploymentUnit = phaseContext.getDeploymentUnit();
        List<ResourceRoot> resourceRoots = DeploymentUtils.allResourceRoots(deploymentUnit);
        for (ResourceRoot resourceRoot : resourceRoots) {
            if (IgnoreMetaInfMarker.isIgnoreMetaInf(resourceRoot)) {
                continue;
            }
            Manifest manifest = getManifest(resourceRoot);
            if (manifest != null)
                resourceRoot.putAttachment(Attachments.MANIFEST, manifest);
        }
    }
205404
@Override
    public void onPrepareProviderResource(BeanCustomizerContext context) {

        EndpointInfo endpointInfo = context.getEndpointInfo();
        Set<ProviderResourceInfo> perRequestProviderAndPathInfos = endpointInfo.getPerRequestProviderAndPathInfos();
        Set<ProviderResourceInfo> singletonProviderAndPathInfos = endpointInfo.getSingletonProviderAndPathInfos();

        //The resources map may already exist on the context.  If it does we will want to add to it.
        Map<Class<?>, ManagedObject<?>> resourcesManagedbyCDI = (Map<Class<?>, ManagedObject<?>>)context.getContextObject();
        if (resourcesManagedbyCDI == null || !(resourcesManagedbyCDI instanceof ThreadBasedHashMap)) {
            resourcesManagedbyCDI = new ThreadBasedHashMap();//HashMap<Class<?>, ManagedObject<?>>();
        }

        CXFJaxRsProviderResourceHolder cxfPRHolder = context.getCxfRPHolder();
        for (ProviderResourceInfo p : perRequestProviderAndPathInfos) {
            /**
             * CDI customizer only check if the POJO type bean is CDI bean
             * because when EJB priority is higher than CDI, engine will take the bean as EJB but not CDI,
             * that means EJB already processes it, CDI should not process it again,
             * then CDI should not cache the bean's info in resourcesManagedbyCDI
             */
            if (p.getRuntimeType() != RuntimeType.POJO)
                continue;

            Class<?> clazz = p.getProviderResourceClass();
            if (!hasValidConstructor(clazz, false)) {
                continue;
            }

            Bean<?> bean = null;
            try {
                bean = getBeanFromCDI(clazz);
            } catch (Exception e1) {
                if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                    Tr.debug(tc, "ManagedObjectFactory failed to create bean", e1);
                }
            }

            if (bean != null) {

                String scopeName = bean.getScope().getName();
                p.setRuntimeType(RuntimeType.CDI);
                resourcesManagedbyCDI.put(p.getProviderResourceClass(), null);

                if (p.isJaxRsProvider()) {
                    //if CDI Scope is APPLICATION_SCOPE or DEPENDENT_SCOPE, report warning and no action: get provider from CDI
                    if (validSingletonScopeList.contains(scopeName)) {
                        logProviderMismatch(clazz, scopeName, "CDI");
                    }
                    //else report warning, keep using provider from rs: change to use RuntimeType.POJO
                    else {
                        p.setRuntimeType(RuntimeType.POJO);
                        resourcesManagedbyCDI.remove(p.getProviderResourceClass());
                        logProviderMismatch(clazz, scopeName, "JAXRS");
                    }
                } else {
                    if (!validRequestScopeList.contains(scopeName)) { //means this is @ApplicationScoped in CDI
                        logResourceMismatch(clazz, "PerRequest", scopeName, "CDI");
                    }

                }
            } else {

                if (shouldHandle(clazz, false)) {
                    p.setRuntimeType(RuntimeType.IMPLICITBEAN);
                    resourcesManagedbyCDI.put(clazz, null);
                }
                continue;

            }

        }
        for (ProviderResourceInfo o : singletonProviderAndPathInfos) {
            /**
             * CDI customizer only check if the POJO type bean is CDI bean
             * because when EJB priority is higher than CDI, engine will take the bean as EJB but not CDI,
             * that means EJB already processes it, CDI should not process it again,
             * then CDI should not cache the bean's info in resourcesManagedbyCDI
             */
            if (o.getRuntimeType() != RuntimeType.POJO)
                continue;

            Class<?> clazz = o.getProviderResourceClass();
            if (!hasValidConstructor(clazz, true)) {
                continue;
            }

            Bean<?> bean = null;
            try {
                bean = getBeanFromCDI(clazz);
            } catch (Exception e1) {
                if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                    Tr.debug(tc, "ManagedObjectFactory failed to create bean", e1);
                }
            }

            if (bean != null) {

                String scopeName = bean.getScope().getName();
                o.setRuntimeType(RuntimeType.CDI);
                resourcesManagedbyCDI.put(o.getProviderResourceClass(), null);
                if (o.isJaxRsProvider()) {
                    if (validSingletonScopeList.contains(scopeName)) {
                        logProviderMismatch(clazz, scopeName, "CDI");
                    }
                    //else report warning, keep using provider from rs: change to use RuntimeType.POJO
                    else {
                        o.setRuntimeType(RuntimeType.POJO);
                        resourcesManagedbyCDI.remove(clazz);
                        logProviderMismatch(clazz, scopeName, "JAXRS");
                    }

                    //Old check is this, need verify by using FAT:
                    //if CDI Scope is APPLICATION_SCOPE or DEPENDENT_SCOPE, report warning and no action: get provider from CDI
                    //else report warning and no action: get provider from CDI

                } else {
                    if (!validSingletonScopeList.contains(scopeName)) { // means CDI is per-request, then modify cxfPRHolder to per-request as well.
                        cxfPRHolder.removeResouceProvider(clazz);//remove from original ResourceProvider map and re-add the new one.
                        cxfPRHolder.addResouceProvider(clazz, new PerRequestResourceProvider(clazz));
                        logResourceMismatch(clazz, "Singleton", scopeName, "CDI");
                    }

                }
            } else {
                if (shouldHandle(clazz, false)) {
                    o.setRuntimeType(RuntimeType.IMPLICITBEAN);
                    resourcesManagedbyCDI.put(clazz, null);
                }
                continue;
            }

        }

        context.setContextObject(resourcesManagedbyCDI);

    }
1116711
public static ServiceName deploymentUnitName(String name, Phase phase) {
        return JBOSS_DEPLOYMENT_UNIT.append(name, phase.name());
    }
274638
@Override
    public Collection<AgentProjectInfo> collectDependencies(String rootDirectory) {
        Collection<DependencyInfo> dependencies = new ArrayList<>();
        try {
            CommandLineProcess npmLsJson = new CommandLineProcess(rootDirectory, getLsCommandParamsJson());
            npmLsJson.setTimeoutReadLineSeconds(this.npmTimeoutDependenciesCollector);
            List<String> linesOfNpmLsJson = npmLsJson.executeProcess();
            // flag that indicates if the 'npm ls' command failed
            this.npmLsFailureStatus = npmLsJson.isErrorInProcess() && !this.ignoreNpmLsErrors;
            StringBuilder json = new StringBuilder();
            for (String line : linesOfNpmLsJson) {
                json.append(line);
            }
            if (json != null && json.length() > 0 && (!npmLsJson.isErrorInProcess() || this.ignoreNpmLsErrors)) {
                logger.debug("'npm ls' output is not empty");
                if(npmLsJson.isErrorInProcess() && this.ignoreNpmLsErrors) {
                    logger.info("Ignore errors of 'npm ls'");
                }
                getDependencies(new JSONObject(json.toString()), rootDirectory, dependencies);
            }
        } catch (IOException e) {
            this.npmLsFailureStatus = true;
            logger.warn("Error getting dependencies after running 'npm ls --json' on {}, error : {}", rootDirectory, e.getMessage());
            logger.debug("Error: {}", e.getStackTrace());
        }

        if (dependencies.isEmpty()) {
            if (!showNpmLsError && this.npmLsFailureStatus) {
                logger.warn("Failed to getting dependencies after running '{}', run {} on {} folder", getLsCommandParams(), getInstallParams(), rootDirectory);
                showNpmLsError = true;
            }
        }
        return getSingleProjectList(dependencies);
    }
343568
public static void indexResourceRoot(final ResourceRoot resourceRoot) throws DeploymentUnitProcessingException {
        if (resourceRoot.getAttachment(Attachments.ANNOTATION_INDEX) != null) {
            return;
        }

        VirtualFile indexFile = resourceRoot.getRoot().getChild(ModuleIndexBuilder.INDEX_LOCATION);
        if (indexFile.exists()) {
            try {
                IndexReader reader = new IndexReader(indexFile.openStream());
                resourceRoot.putAttachment(Attachments.ANNOTATION_INDEX, reader.read());
                ServerLogger.DEPLOYMENT_LOGGER.tracef("Found and read index at: %s", indexFile);
                return;
            } catch (Exception e) {
                ServerLogger.DEPLOYMENT_LOGGER.cannotLoadAnnotationIndex(indexFile.getPathName());
            }
        }

        // if this flag is present and set to false then do not index the resource
        Boolean shouldIndexResource = resourceRoot.getAttachment(Attachments.INDEX_RESOURCE_ROOT);
        if (shouldIndexResource != null && !shouldIndexResource) {
            return;
        }

        final List<String> indexIgnorePathList = resourceRoot.getAttachment(Attachments.INDEX_IGNORE_PATHS);
        final Set<String> indexIgnorePaths;
        if (indexIgnorePathList != null && !indexIgnorePathList.isEmpty()) {
            indexIgnorePaths = new HashSet<String>(indexIgnorePathList);
        } else {
            indexIgnorePaths = null;
        }

        final VirtualFile virtualFile = resourceRoot.getRoot();
        final Indexer indexer = new Indexer();
        try {
            final VisitorAttributes visitorAttributes = new VisitorAttributes();
            visitorAttributes.setLeavesOnly(true);
            visitorAttributes.setRecurseFilter(new VirtualFileFilter() {
                public boolean accepts(VirtualFile file) {
                    return indexIgnorePaths == null || !indexIgnorePaths.contains(file.getPathNameRelativeTo(virtualFile));
                }
            });

            final List<VirtualFile> classChildren = virtualFile.getChildren(new SuffixMatchFilter(".class", visitorAttributes));
            for (VirtualFile classFile : classChildren) {
                InputStream inputStream = null;
                try {
                    inputStream = classFile.openStream();
                    indexer.index(inputStream);
                } catch (Exception e) {
                    ServerLogger.DEPLOYMENT_LOGGER.cannotIndexClass(classFile.getPathNameRelativeTo(virtualFile), virtualFile.getPathName(), e);
                } finally {
                    VFSUtils.safeClose(inputStream);
                }
            }
            final Index index = indexer.complete();
            resourceRoot.putAttachment(Attachments.ANNOTATION_INDEX, index);
            ServerLogger.DEPLOYMENT_LOGGER.tracef("Generated index for archive %s", virtualFile);
        } catch (Throwable t) {
            throw ServerLogger.ROOT_LOGGER.deploymentIndexingFailed(t);
        }
    }
149115
public void deploy(RemoteRepository target, Artifact ... artifacts) throws DeploymentException {
        deploy(target, null, Arrays.asList(artifacts));
    }
1125665
@Override
    public void initializeInjectionServices() throws CDIException {

        Set<ReferenceContext> cdiReferenceContexts = new HashSet<ReferenceContext>();

        //first we need to initialize the injection service and collect the reference contexts and the injection classes
        for (WebSphereBeanDeploymentArchive bda : getApplicationBDAs()) {
            // Don't initialize child libraries, instead aggregate for the whole module
            if (bda.getType() != ArchiveType.MANIFEST_CLASSPATH && bda.getType() != ArchiveType.WEB_INF_LIB) {
                ReferenceContext referenceContext = bda.initializeInjectionServices();
                cdiReferenceContexts.add(referenceContext);
            }
        }

        // now we need to process the injections
        for (ReferenceContext referenceContext : cdiReferenceContexts) {
            try {
                referenceContext.process();
            } catch (InjectionException e) {
                throw new CDIException(e);
            }
        }

    }
825796
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		this.applicationContext = applicationContext;

		if (servletContext == null)
			if (applicationContext instanceof WebApplicationContext) {
				servletContext = ((WebApplicationContext) applicationContext).getServletContext();
				if (servletContext == null) {
					System.err.print("this class only fit for Spring Web Application");
					return;
				}

			}

		// start up jdon
		AppContextWrapper acw = new ServletContextWrapper(servletContext);
		ContainerFinder containerFinder = new ContainerFinderImp();
		containerWrapper = containerFinder.findContainer(acw);

	}
660567
private void processOutputDirectory() {
        final String root = outputDirectory.getAbsolutePath();
        final String leaf = PhaseOneApplication.DIR_ARTIFACT;
        final String path = asPath(root, leaf);
        final File phaseIPath = new File(path);

        // Fail if the working path doesn't contain a phase I artifact
        if (!phaseIPath.isDirectory()) {
            error(NOT_A_PHASE1_DIR + ": " + phaseIPath);
            failUsage();
        }

        // Fail if the working path doesn't contain any proto-networks
        final File[] networks = phaseIPath.listFiles(new ProtonetworkFilter());
        if (networks.length == 0) {
            error(NO_PROTO_NETWORKS + " found in " + phaseIPath);
            failUsage();
        }

        // Create the directory artifact or fail
        artifactPath = createDirectoryArtifact(outputDirectory, DIR_ARTIFACT);

        processDirectories(networks);
    }
1339909
public static ServiceName deploymentUnitName(String parent, String name, Phase phase) {
        return JBOSS_DEPLOYMENT_SUB_UNIT.append(parent, name, phase.name());
    }
1203849
@Override
	protected void initServletContext(ServletContext servletContext) {
		super.initServletContext(servletContext);
		super.setExposeRequestAttributes(true);
		
		initBaseTemplatePath(servletContext);
		initSharedFunction();
	}
149183
private Object processJavaColonModule(String lookupName) throws NamingException {
        ComponentMetaData cmd = getComponentMetaData(JavaColonNamespace.MODULE, lookupName);
        ModuleMetaData mmd = cmd.getModuleMetaData();
        JavaColonNamespaceBindings<EJBBinding> modMap = getModuleBindingMap(mmd);
        EJBBinding binding = modMap.lookup(lookupName);

        return processJavaColon(binding, JavaColonNamespace.MODULE, lookupName);
    }
475398
public void createDeploymentContext(@Observes EventContext<DeploymentEvent> context) {
        DeploymentContext deploymentContext = this.deploymentContext.get();
        try {
            DeploymentEvent event = context.getEvent();
            deploymentContext.activate(event.getDeployment());

            context.proceed();
        } finally {
            deploymentContext.deactivate();
        }
    }
400903
private void deployNetwork(final NetworkContext context, final Handler<AsyncResult<NetworkContext>> doneHandler) {
    log.debug(String.format("%s - Deploying network", NetworkManager.this));
    final CountingCompletionHandler<Void> complete = new CountingCompletionHandler<Void>(context.components().size());
    complete.setHandler(new Handler<AsyncResult<Void>>() {
      @Override
      public void handle(AsyncResult<Void> result) {
        if (result.failed()) {
          new DefaultFutureResult<NetworkContext>(result.cause()).setHandler(doneHandler);
        } else {
          new DefaultFutureResult<NetworkContext>(context).setHandler(doneHandler);
        }
      }
    });
    deployComponents(context.components(), complete);
  }
147043
private void dispatchInitializationEvent(ServletContextEvent event, int operation)
    {

        if (operation == FACES_INIT_PHASE_PREINIT)
        {
            if (!loadFacesInitPluginsJDK6())
            {
                loadFacesInitPluginsJDK5();
            }
        }

        List<StartupListener> pluginEntries = (List<StartupListener>) _servletContext.getAttribute(FACES_INIT_PLUGINS);
        if (pluginEntries == null)
        {
            return;
        }

        //now we process the plugins
        for (StartupListener initializer : pluginEntries)
        {
            log.info("Processing plugin");

            //for now the initializers have to be stateless to
            //so that we do not have to enforce that the initializer
            //must be serializable
            switch (operation)
            {
                case FACES_INIT_PHASE_PREINIT:
                    initializer.preInit(event);
                    break;
                case FACES_INIT_PHASE_POSTINIT:
                    initializer.postInit(event);
                    break;
                case FACES_INIT_PHASE_PREDESTROY:
                    initializer.preDestroy(event);
                    break;
                default:
                    initializer.postDestroy(event);
                    break;
            }
        }
        log.info("Processing MyFaces plugins done");
    }