Generates deployment for given application.

@param type Module type to generate
@param basename Base name of module to generate
@param doFiltering should do basic filtering
@return EnterpriseArchive containing given module and all dependencies
1247
public static EnterpriseArchive getModuleDeployment(ModuleType type, String basename, boolean doFiltering) {
        String name = basename + "." + type.getExtension();
        String testJarName = basename + "-tests.jar";
//        LOG.debug("Creating Arquillian deployment for [" + name + "]");
        try {
            EarDescriptorBuilder descriptorBuilder = new EarDescriptorBuilder(basename);
            MavenResolverSystem maven = Maven.resolver();
            //ConfigurableMavenResolverSystem maven = Maven.configureResolver().workOffline().withMavenCentralRepo(false);
            EnterpriseArchive ear = ShrinkWrap.create(EnterpriseArchive.class, basename + "-full.ear");
            PomEquippedResolveStage resolveStage = maven.loadPomFromFile("pom.xml");

            // przejrzenie dependency oznaczonych jako provided w celu znalezienia EJB'ków
            MavenResolvedArtifact[] provided = resolveStage.importRuntimeDependencies().importDependencies(ScopeType.PROVIDED).resolve().using(new AcceptScopesStrategy(ScopeType.PROVIDED)).asResolvedArtifact();
            for (MavenResolvedArtifact mra : provided) {
//                System.out.println("Checking provided: " + mra.getCoordinate().toCanonicalForm());
                if (isArtifactEjb(mra.getCoordinate())) {
                    ear.addAsModule(mra.as(JavaArchive.class));
                    // dodajemy jako moduł
                    descriptorBuilder.addEjb(mra.asFile().getName());
                    // przeglądamy dependency EJB'ka w celu pobrania także zależności z EJB'ka
                    for (MavenArtifactInfo mai : mra.getDependencies()) {
//                            LOG.debug("Resolved: " + mai.getCoordinate().getGroupId() + ":" + mai.getCoordinate().getArtifactId());
                        // pomijamy wzajemne zależności do innych EJB'ków
                        if (!isArtifactEjb(mai.getCoordinate())) {
                            for (MavenResolvedArtifact reqMra : provided) {
                                if (reqMra.getCoordinate().toCanonicalForm().equals(mai.getCoordinate().toCanonicalForm())) {
                                    // dodanie zależności do lib'ów
                                    ear.addAsLibrary(reqMra.asFile());
                                    break;
                                }
                            }
                        }
                    }
                }
            }
            MavenResolvedArtifact[] deps = resolveStage.importRuntimeAndTestDependencies().resolve().withTransitivity().asResolvedArtifact();

            for (MavenResolvedArtifact mra : deps) {
                MavenCoordinate mc = mra.getCoordinate();
                PackagingType packaging = mc.getPackaging();
                if (doFiltering && isFiltered(mc)) {
                    continue;
                }
                LOG.log(Level.FINEST, "Adding: {0}", mc.toCanonicalForm());
                if (isArtifactEjb(mc)) {
                    // dependency w postaci ejb'ków
                    ear.addAsModule(mra.as(JavaArchive.class));
                    descriptorBuilder.addEjb(mra.asFile().getName());
                } else if (packaging.equals(PackagingType.WAR)) {
                    // dependency w postaci war'ów
                    ear.addAsModule(mra.as(WebArchive.class));
                    descriptorBuilder.addWeb(mra.asFile().getName());
                } else {
                    // resztę dodajemy jako lib
                    ear.addAsLibrary(mra.asFile());
                }
            }
            // utworzenie głównego archiwum
//            Archive<?> module = ShrinkWrap.create(MavenImporter.class, name)
//                    .loadPomFromFile("pom.xml")
//                    .as(type.getType());

            Archive<?> module = ShrinkWrap.create(ExplodedImporter.class, name)
                    .importDirectory(type.getExplodedDir(basename))
                    .as(type.getType());

            JavaArchive testJar = ShrinkWrap.create(ExplodedImporter.class, testJarName)
                    .importDirectory("target/test-classes")
                    .as(JavaArchive.class);

            module = module.merge(testJar, type.getMergePoint());
//            mergeReplace(ear, module, testJar);

            module.add(new StringAsset(RUN_AT_ARQUILLIAN_CONTENT), RUN_AT_ARQUILLIAN_PATH);
            LOG.log(Level.FINE, module.toString(true));

            addMainModule(ear, type, module, descriptorBuilder);
            
            // Workaround for arquillian bug
            if (!descriptorBuilder.containsWar()) {
                String testModuleName = ModuleType.WAR.generateModuleName() + ".war";
                ear.addAsModule(ShrinkWrap.create(WebArchive.class, testModuleName));
                descriptorBuilder.addWeb(testModuleName);
            }

            ear.setApplicationXML(new StringAsset(descriptorBuilder.render()));
            ear.addManifest();
            LOG.log(Level.INFO, "Created deployment [{0}]", ear.getName());
//            System.out.println(ear.toString(true));
//            System.out.println(descriptorBuilder.render());
            return ear;
        } catch (IllegalArgumentException ex) {
            throw new IllegalStateException("Error in creating deployment [" + ex + "]", ex);
        } catch (InvalidConfigurationFileException ex) {
            throw new IllegalStateException("Error in creating deployment [" + ex + "]", ex);
        } catch (ArchiveImportException ex) {
            throw new IllegalStateException("Error in creating deployment [" + ex + "]", ex);
        }
    }
451097
public FileFilter build() {
        if (filenames.isEmpty() && extensions.isEmpty() && fileFilters.isEmpty()) {
            throw new IllegalStateException("May only be invoked after at least one add... method has been invoked.");
        }
        final OrFileFilter filter = new OrFileFilter();
        if (!filenames.isEmpty()) {
            filter.addFileFilter(new NameFileFilter(new ArrayList<>(filenames)));
        }
        if (!extensions.isEmpty()) {
            filter.addFileFilter(new SuffixFileFilter(new ArrayList<>(extensions), IOCase.INSENSITIVE));
        }
        for (IOFileFilter iof : fileFilters) {
            filter.addFileFilter(iof);
        }
        return filter;
    }
1285540
public TypeSpec generateType(Type type) {
    AdapterConstant adapterConstant = profile.getAdapter(type.type());
    if (adapterConstant != null) {
      return generateAdapterForCustomType(type);
    }
    if (type instanceof MessageType) {
      //noinspection deprecation: Only deprecated as a public API.
      return generateMessage((MessageType) type);
    }
    if (type instanceof EnumType) {
      //noinspection deprecation: Only deprecated as a public API.
      return generateEnum((EnumType) type);
    }
    if (type instanceof EnclosingType) {
      return generateEnclosingType((EnclosingType) type);
    }
    throw new IllegalStateException("Unknown type: " + type);
  }
489165
private JdepsFilter dependencyFilter(JdepsConfiguration config) {
        // Filter specified by -filter, -package, -regex, and --require options
        JdepsFilter.Builder builder = new JdepsFilter.Builder();

        // source filters
        builder.includePattern(options.includePattern);

        // target filters
        builder.filter(options.filterSamePackage, options.filterSameArchive);
        builder.findJDKInternals(options.findJDKInternals);

        // --require
        if (!options.requires.isEmpty()) {
            options.requires.stream()
                .forEach(mn -> {
                    Module m = config.findModule(mn).get();
                    builder.requires(mn, m.packages());
                });
        }
        // -regex
        if (options.regex != null)
            builder.regex(options.regex);
        // -package
        if (!options.packageNames.isEmpty())
            builder.packages(options.packageNames);
        // -filter
        if (options.filterRegex != null)
            builder.filter(options.filterRegex);

        return builder.build();
    }
1205092
public static InstanceFilter createFilter( final String path, String installerName ) {

		List<String> types = Utils.splitNicely( path, ALTERNATIVE );
		OrNode rootNode = new OrNode();
		for( String type : types ) {
			Node node = buildNodeForPath( type );
			rootNode.delegates.add( node );
		}

		return new InstanceFilter( path, rootNode, installerName );
	}
486714
@Override
    public Filter createFilter(FilterConfig filterConfig) {
        Binding binding = new Binding();
        SecurityComponents sc = this.createSecurityComponents();
        binding.setVariable("securityComponents", sc);
        binding.setVariable("securityRealm",this);
        BeanBuilder builder = new BeanBuilder();
        builder.parse(filterConfig.getServletContext().getResourceAsStream("/WEB-INF/security/SecurityFilters.groovy"),binding);
        
        WebApplicationContext context = builder.createApplicationContext();
        
        return (Filter) context.getBean("legacy");
    }
193734
private void generateCopies(final Element topicref, final List<FilterUtils> filters) {
        final List<FilterUtils> fs = combineFilterUtils(topicref, filters);

        final String copyTo = topicref.getAttribute(BRANCH_COPY_TO);
        if (!copyTo.isEmpty()) {
            final URI dstUri = map.resolve(copyTo);
            final URI dstAbsUri = job.tempDirURI.resolve(dstUri);
            final String href = topicref.getAttribute(ATTRIBUTE_NAME_HREF);
            final URI srcUri = map.resolve(href);
            final URI srcAbsUri = job.tempDirURI.resolve(srcUri);
            final FileInfo srcFileInfo = job.getFileInfo(srcUri);
            if (srcFileInfo != null) {
//                final FileInfo fi = new FileInfo.Builder(srcFileInfo).uri(dstUri).build();
//                 TODO: Maybe Job should be updated earlier?
//                job.add(fi);
                logger.info("Filtering " + srcAbsUri + " to " + dstAbsUri);
                final ProfilingFilter writer = new ProfilingFilter();
                writer.setLogger(logger);
                writer.setJob(job);
                writer.setFilterUtils(fs);
                writer.setCurrentFile(dstAbsUri);
                final List<XMLFilter> pipe = singletonList(writer);

                final File dstDirUri = new File(dstAbsUri.resolve("."));
                if (!dstDirUri.exists() && !dstDirUri.mkdirs()) {
                    logger.error("Failed to create directory " + dstDirUri);
                }
                try {
                    xmlUtils.transform(srcAbsUri,
                                       dstAbsUri,
                                       pipe);
                } catch (final DITAOTException e) {
                    logger.error("Failed to filter " + srcAbsUri + " to " + dstAbsUri + ": " + e.getMessage(), e);
                }
                topicref.setAttribute(ATTRIBUTE_NAME_HREF, copyTo);
                topicref.removeAttribute(BRANCH_COPY_TO);
                // disable filtering again
                topicref.setAttribute(SKIP_FILTER, Boolean.TRUE.toString());
            }
        }
        for (final Element child: getChildElements(topicref, MAP_TOPICREF)) {
            if (DITAVAREF_D_DITAVALREF.matches(child)) {
                continue;
            }
            generateCopies(child, fs);
        }
    }
506739
function getAppFolders(input, deploymentApplicationType) {
    const destinationPath = this.destinationPath(input);
    const files = shelljs.ls('-l', destinationPath);
    const appsFolders = [];

    files.forEach(file => {
        if (file.isDirectory()) {
            if (shelljs.test('-f', `${destinationPath}/${file.name}/.yo-rc.json`)) {
                try {
                    const fileData = this.fs.readJSON(`${destinationPath}/${file.name}/.yo-rc.json`);
                    if (
                        fileData['generator-jhipster'].baseName !== undefined &&
                        (deploymentApplicationType === undefined ||
                            deploymentApplicationType === fileData['generator-jhipster'].applicationType ||
                            (deploymentApplicationType === 'microservice' &&
                                fileData['generator-jhipster'].applicationType === 'gateway') ||
                            (deploymentApplicationType === 'microservice' && fileData['generator-jhipster'].applicationType === 'uaa'))
                    ) {
                        appsFolders.push(file.name.match(/([^/]*)\/*$/)[1]);
                    }
                } catch (err) {
                    this.log(chalk.red(`${file}: this .yo-rc.json can't be read`));
                    this.debug('Error:', err);
                }
            }
        }
    });

    return appsFolders;
}
15755
private JavaFile generateModuleAdapter(TypeElement type,
      Map<String, Object> module, List<ExecutableElement> providerMethods) {
    Object[] staticInjections = (Object[]) module.get("staticInjections");
    Object[] injects = (Object[]) module.get("injects");
    Object[] includes = (Object[]) module.get("includes");
    boolean overrides = (Boolean) module.get("overrides");
    boolean complete = (Boolean) module.get("complete");
    boolean library = (Boolean) module.get("library");

    List<Object> duplicateInjects = extractDuplicates(injects);
    if (!duplicateInjects.isEmpty()) {
      error("'injects' list contains duplicate entries: " + duplicateInjects, type);
    }
    List<Object> duplicateIncludes = extractDuplicates(includes);
    if (!duplicateIncludes.isEmpty()) {
      error("'includes' list contains duplicate entries: " + duplicateIncludes, type);
    }

    ClassName moduleClassName = ClassName.get(type);
    ClassName adapterClassName = Util.adapterName(moduleClassName, MODULE_ADAPTER_SUFFIX);

    TypeSpec.Builder adapterBuilder = TypeSpec.classBuilder(adapterClassName.simpleName())
        .addOriginatingElement(type)
        .addJavadoc(AdapterJavadocs.MODULE_TYPE, Provides.class)
        .superclass(ParameterizedTypeName.get(ClassName.get(ModuleAdapter.class), moduleClassName))
        .addModifiers(PUBLIC, FINAL);

    adapterBuilder.addField(FieldSpec.builder(String[].class, "INJECTS")
        .addModifiers(PRIVATE, STATIC, FINAL)
        .initializer("$L", injectsInitializer(injects))
        .build());
    adapterBuilder.addField(FieldSpec.builder(ARRAY_OF_CLASS, "STATIC_INJECTIONS")
        .addModifiers(PRIVATE, STATIC, FINAL)
        .initializer("$L", staticInjectionsInitializer(staticInjections))
        .build());
    adapterBuilder.addField(FieldSpec.builder(ARRAY_OF_CLASS, "INCLUDES")
        .addModifiers(PRIVATE, STATIC, FINAL)
        .initializer("$L", includesInitializer(type, includes))
        .build());
    adapterBuilder.addMethod(MethodSpec.constructorBuilder()
        .addModifiers(PUBLIC)
        .addStatement("super($T.class, INJECTS, STATIC_INJECTIONS, $L /*overrides*/, "
                + "INCLUDES, $L /*complete*/, $L /*library*/)",
            type.asType(), overrides, complete, library)
        .build());

    ExecutableElement noArgsConstructor = getNoArgsConstructor(type);
    if (noArgsConstructor != null && isCallableConstructor(noArgsConstructor)) {
      adapterBuilder.addMethod(MethodSpec.methodBuilder("newModule")
          .addAnnotation(Override.class)
          .addModifiers(PUBLIC)
          .returns(moduleClassName)
          .addStatement("return new $T()", type.asType())
          .build());
    }

    // Caches.
    Map<ExecutableElement, ClassName> methodToClassName
        = new LinkedHashMap<ExecutableElement, ClassName>();
    Map<String, AtomicInteger> methodNameToNextId = new LinkedHashMap<String, AtomicInteger>();

    if (!providerMethods.isEmpty()) {
      MethodSpec.Builder getBindings = MethodSpec.methodBuilder("getBindings")
          .addJavadoc(AdapterJavadocs.GET_DEPENDENCIES_METHOD)
          .addAnnotation(Override.class)
          .addModifiers(PUBLIC)
          .addParameter(BindingsGroup.class, "bindings")
          .addParameter(moduleClassName, "module");

      for (ExecutableElement providerMethod : providerMethods) {
        Provides provides = providerMethod.getAnnotation(Provides.class);
        switch (provides.type()) {
          case UNIQUE: {
            getBindings.addStatement("bindings.contributeProvidesBinding($S, new $T(module))",
                GeneratorKeys.get(providerMethod),
                bindingClassName(adapterClassName, providerMethod, methodToClassName,
                    methodNameToNextId));
            break;
          }
          case SET: {
            getBindings.addStatement("$T.add(bindings, $S, new $T(module))",
                SetBinding.class,
                GeneratorKeys.getSetKey(providerMethod),
                bindingClassName(adapterClassName, providerMethod, methodToClassName,
                    methodNameToNextId));
            break;
          }
          case SET_VALUES: {
            getBindings.addStatement("$T.add(bindings, $S, new $T(module))",
                SetBinding.class,
                GeneratorKeys.get(providerMethod),
                bindingClassName(adapterClassName, providerMethod, methodToClassName,
                    methodNameToNextId));
            break;
          }
          default:
            throw new AssertionError("Unknown @Provides type " + provides.type());
        }
      }
      adapterBuilder.addMethod(getBindings.build());
    }

    for (ExecutableElement providerMethod : providerMethods) {
      adapterBuilder.addType(generateProvidesAdapter(moduleClassName, adapterClassName,
          providerMethod, methodToClassName, methodNameToNextId, library));
    }

    return JavaFile.builder(adapterClassName.packageName(), adapterBuilder.build())
        .addFileComment(AdapterJavadocs.GENERATED_BY_DAGGER)
        .build();
  }
593088
public String generateJava2ContentParser(TypeName paramTypeName) {
		if (!managedParams.containsKey(paramTypeName)) {
			managedParams.put(paramTypeName, "" + (managedParams.size() + 1));
		}

		return PARAM_PARSER_PREFIX + managedParams.get(paramTypeName);
	}
641983
public List<String> getModuleVersions(final String name, final FiltersHolder filters) {
        final List<String> versions = repositoryHandler.getModuleVersions(name, filters);

        if (versions.isEmpty()) {
            throw new WebApplicationException(Response.status(Response.Status.NOT_FOUND)
                    .entity("Module " + name + " does not exist.").build());
        }

        return versions;
    }
1084867
private static void addMainModule(EnterpriseArchive ear, ModuleType type, Archive<?> module, EarDescriptorBuilder descriptorBuilder) {
        if (type.isModule()) {
            ear.addAsModule(module);
            if (type == ModuleType.EJB) {
                descriptorBuilder.addEjb(module.getName());
            }
            if (type == ModuleType.WAR) {
                descriptorBuilder.addWeb(module.getName());
            }
        } else {
            ear.addAsLibrary(module);
        }
    }
242374
public static void buildModulesPackage(List<String> modulesNames) {
		System.out.println(System.getProperty("user.dir"));
		try {
			String baseDir = System.getProperty("user.dir");
			List<File> filesArray = new ArrayList<>();
			for (String module : modulesNames) {
				module = "/"+module.replace(".", "/")+".class";
				filesArray.add(new File(baseDir+module));
			}
			String output = System.getProperty("user.home") + "/modules.jar";

			Manifest manifest = new Manifest();
			manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION,
					"1.0");
			manifest.getMainAttributes().put(Attributes.Name.IMPLEMENTATION_URL,
					"http://samoa.yahoo.com");
			manifest.getMainAttributes().put(
					Attributes.Name.IMPLEMENTATION_VERSION, "0.1");
			manifest.getMainAttributes().put(Attributes.Name.IMPLEMENTATION_VENDOR,
					"Yahoo");
			manifest.getMainAttributes().put(
					Attributes.Name.IMPLEMENTATION_VENDOR_ID, "SAMOA");

			BufferedOutputStream bo;

			bo = new BufferedOutputStream(new FileOutputStream(output));
			JarOutputStream jo = new JarOutputStream(bo, manifest);

			File[] files = filesArray.toArray(new File[filesArray.size()]);
			addEntries(jo,files, baseDir, "");

			jo.close();
			bo.close();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}
804753
@Bean
    FilterRegistrationBean eTagFilter() {

        final FilterRegistrationBean filterRegBean = new FilterRegistrationBean();
        // Exclude the URLs for downloading artifacts, so no eTag is generated
        // in the ShallowEtagHeaderFilter, just using the SH1 hash of the
        // artifact itself as 'ETag', because otherwise the file will be copied
        // in memory!
        filterRegBean.setFilter(new ExcludePathAwareShallowETagFilter("/UI/**",
                "/rest/v1/softwaremodules/{smId}/artifacts/{artId}/download",
                "/{tenant}/controller/v1/{controllerId}/softwaremodules/{softwareModuleId}/artifacts/**",
                "/api/v1/downloadserver/**"));

        return filterRegBean;
    }
421673
public DeploymentCache deployments(long applicationId)
    {
        DeploymentCache cache = deployments.get(applicationId);
        if(cache == null)
            deployments.put(applicationId, cache = new DeploymentCache(applicationId));
        return cache;
    }
392714
protected void generateModuleIdMap(IDependencies deps) throws IOException {
		final String methodName = "generateModuleIdMap"; //$NON-NLS-1$
		boolean isTraceLogging = log.isLoggable(Level.FINER);
		if (isTraceLogging) {
			log.entering(sourceClass, methodName);
		}
		if (getModuleIdRegFunctionName() == null) {
			if (isTraceLogging) {
				log.finer("No module id list registration function - returning"); //$NON-NLS-1$
				log.exiting(sourceClass, methodName);
			}
			return;
		}
		Map<String, String> names = new TreeMap<String, String>(); // Use TreeMap to get consistent ordering

		for (String name : deps.getDependencyNames()) {
			names.put(name, isTraceLogging ? deps.getURI(name).toString() : null);
		}
		for (String name : getSyntheticModuleNames()) {
			names.put(name, isTraceLogging ? "transport added" : null); //$NON-NLS-1$
		}
		if (isTraceLogging) {
			// Log the module name id list.  This information is useful when trying to determine
			// why different servers in the same cluster might be generating different list hashes.
			StringBuffer sb = new StringBuffer("Module ID list:\r\n"); //$NON-NLS-1$
			int i = 1;
			for (Map.Entry<String, String> entry : names.entrySet()) {
				sb.append(i++).append(": ").append(entry.getKey()).append(" - ").append(entry.getValue()).append("\r\n"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
			}
			log.finer(sb.toString());
		}

		Map<String, Integer> idMap = new HashMap<String, Integer>(names.size());
		List<String> idList = new ArrayList<String>(names.size()+1);
		idList.add("");	// slot 0 is unused //$NON-NLS-1$
		idList.addAll(names.keySet());
		for (int i = 1; i < idList.size(); i++) {
			idMap.put(idList.get(i), i);
		}

		MessageDigest md = null;
		try {
			md = MessageDigest.getInstance("MD5"); //$NON-NLS-1$
		} catch (NoSuchAlgorithmException e) {
			if (log.isLoggable(Level.WARNING)) {
				log.log(Level.WARNING, e.getMessage(), e);
			}
			throw new IOException(e);
		}
		moduleIdListHash = md.digest(idList.toString().getBytes("UTF-8")); //$NON-NLS-1$
		moduleIdMap = Collections.unmodifiableMap(idMap);
		moduleIdList = idList;

		if (log.isLoggable(Level.INFO)) {
			log.info("Module ID List hash = " + TypeUtil.byteArray2String(moduleIdListHash)); //$NON-NLS-1$
		}
		if (isTraceLogging) {
			log.exiting(sourceClass, methodName);
		}
	}
1169044
public static List<Dependency> getCorporateDependencies(final Module module, final List<String> corporateFilters) {
        final List<Dependency> corporateDependencies = new ArrayList<Dependency>();
        final Pattern corporatePattern = generateCorporatePattern(corporateFilters);

        for(final Dependency dependency: getAllDependencies(module)){
            if(dependency.getTarget().getGavc().matches(corporatePattern.pattern())){
                corporateDependencies.add(dependency);
            }
        }

        return corporateDependencies;
    }