Example usage for org.apache.commons.collections CollectionUtils subtract

List of usage examples for org.apache.commons.collections CollectionUtils subtract

Introduction

In this page you can find the example usage for org.apache.commons.collections CollectionUtils subtract.

Prototype

public static Collection subtract(final Collection a, final Collection b) 

Source Link

Document

Returns a new Collection containing a - b.

Usage

From source file:org.apache.sysml.runtime.transform.encode.EncoderFactory.java

@SuppressWarnings("unchecked")
public static Encoder createEncoder(String spec, String[] colnames, ValueType[] schema, FrameBlock meta)
        throws DMLRuntimeException {
    Encoder encoder = null;/*from  ww  w .ja v  a 2s  .  c om*/
    int clen = schema.length;

    try {
        //parse transform specification
        JSONObject jSpec = new JSONObject(spec);
        List<Encoder> lencoders = new ArrayList<Encoder>();

        //prepare basic id lists (recode, dummycode, pass-through)
        //note: any dummycode column requires recode as preparation
        List<Integer> rcIDs = Arrays.asList(
                ArrayUtils.toObject(TfMetaUtils.parseJsonIDList(jSpec, colnames, TfUtils.TXMETHOD_RECODE)));
        List<Integer> dcIDs = Arrays.asList(
                ArrayUtils.toObject(TfMetaUtils.parseJsonIDList(jSpec, colnames, TfUtils.TXMETHOD_DUMMYCODE)));
        rcIDs = new ArrayList<Integer>(CollectionUtils.union(rcIDs, dcIDs));
        List<Integer> binIDs = TfMetaUtils.parseBinningColIDs(jSpec, colnames);
        List<Integer> ptIDs = new ArrayList<Integer>(CollectionUtils
                .subtract(CollectionUtils.subtract(UtilFunctions.getSequenceList(1, clen, 1), rcIDs), binIDs));
        List<Integer> oIDs = Arrays.asList(
                ArrayUtils.toObject(TfMetaUtils.parseJsonIDList(jSpec, colnames, TfUtils.TXMETHOD_OMIT)));
        List<Integer> mvIDs = Arrays.asList(ArrayUtils
                .toObject(TfMetaUtils.parseJsonObjectIDList(jSpec, colnames, TfUtils.TXMETHOD_IMPUTE)));

        //create individual encoders
        if (!rcIDs.isEmpty()) {
            RecodeAgent ra = new RecodeAgent(jSpec, colnames, clen);
            ra.setColList(ArrayUtils.toPrimitive(rcIDs.toArray(new Integer[0])));
            lencoders.add(ra);
        }
        if (!ptIDs.isEmpty())
            lencoders.add(new EncoderPassThrough(ArrayUtils.toPrimitive(ptIDs.toArray(new Integer[0])), clen));
        if (!dcIDs.isEmpty())
            lencoders.add(new DummycodeAgent(jSpec, colnames, schema.length));
        if (!binIDs.isEmpty())
            lencoders.add(new BinAgent(jSpec, colnames, schema.length, true));
        if (!oIDs.isEmpty())
            lencoders.add(new OmitAgent(jSpec, colnames, schema.length));
        if (!mvIDs.isEmpty()) {
            MVImputeAgent ma = new MVImputeAgent(jSpec, colnames, schema.length);
            ma.initRecodeIDList(rcIDs);
            lencoders.add(ma);
        }

        //create composite decoder of all created encoders
        //and initialize meta data (recode, dummy, bin, mv)
        encoder = new EncoderComposite(lencoders);
        if (meta != null)
            encoder.initMetaData(meta);
    } catch (Exception ex) {
        throw new DMLRuntimeException(ex);
    }

    return encoder;
}

From source file:org.beanfuse.lang.SeqStringUtil.java

/**
 * ???a-b. ,,?<br>//  www. ja  va  2s.c  o  m
 * 
 * @param first
 * @param second
 * @param delimiter
 * @return
 */
public static String subtractSeq(String first, String second, String delimiter) {
    if (StringUtils.isEmpty(first)) {
        return "";
    }
    if (StringUtils.isEmpty(second)) {
        StringBuilder builder = new StringBuilder();
        if (!first.startsWith(delimiter)) {
            builder.append(delimiter).append(first);
        }
        if (!first.endsWith(delimiter)) {
            builder.append(first).append(delimiter);
        }
        return builder.toString();
    }
    List firstSeq = Arrays.asList(StringUtils.split(first, delimiter));
    List secondSeq = Arrays.asList(StringUtils.split(second, delimiter));
    Collection rs = CollectionUtils.subtract(firstSeq, secondSeq);
    StringBuilder buf = new StringBuilder();
    for (Iterator iter = rs.iterator(); iter.hasNext();) {
        String ele = (String) iter.next();
        buf.append(delimiter).append(ele);
    }
    if (buf.length() > 0) {
        buf.append(delimiter);
    }

    return buf.toString();
}

From source file:org.beanfuse.security.menu.service.MenuAuthorityServiceImpl.java

/**
 * @deprecated/*w w  w  .  j  a va 2 s  .c o m*/
 */
public void copyAuthority(MenuProfile profile, Group fromGroup, Collection toGroups) {
    List fromAuthorities = getMenuAuthorities(profile, fromGroup);
    List allAdded = new ArrayList();
    for (Iterator iter = toGroups.iterator(); iter.hasNext();) {
        Group toGroup = (Group) iter.next();
        List toAuthorities = getMenuAuthorities(profile, toGroup);
        Collection newAuthorities = CollectionUtils.subtract(fromAuthorities, toAuthorities);
        for (Iterator iterator = newAuthorities.iterator(); iterator.hasNext();) {
            // GroupAuthority auth = (GroupAuthority) iterator.next();
            // allAdded.add(auth.clone());
        }
    }
    entityService.saveOrUpdate(allAdded);
}

From source file:org.beanfuse.security.service.AuthorityServiceImpl.java

public void copyAuthority(Group fromGroup, Collection toGroups) {
    List fromAuthorities = getAuthorities(fromGroup);
    List allAdded = new ArrayList();
    for (Iterator iter = toGroups.iterator(); iter.hasNext();) {
        Group toGroup = (Group) iter.next();
        List toAuthorities = getAuthorities(toGroup);
        Collection newAuthorities = CollectionUtils.subtract(fromAuthorities, toAuthorities);
        for (Iterator iterator = newAuthorities.iterator(); iterator.hasNext();) {
            Authority auth = (Authority) iterator.next();
            allAdded.add(auth.clone());/*ww  w. j av  a2 s.co m*/
        }
    }
    entityService.saveOrUpdate(allAdded);
}

From source file:org.beangle.commons.lang.StrUtils.java

/**
 * ???a-b. ,,?<br>/*from  w  w w. j a v  a2 s  . c  om*/
 * 
 * @param first
 * @param second
 * @param delimiter
 * @return
 */
public static String subtractSeq(String first, String second, String delimiter) {
    if (StringUtils.isEmpty(first)) {
        return "";
    }
    if (StringUtils.isEmpty(second)) {
        StringBuilder builder = new StringBuilder();
        if (!first.startsWith(delimiter)) {
            builder.append(delimiter).append(first);
        }
        if (!first.endsWith(delimiter)) {
            builder.append(first).append(delimiter);
        }
        return builder.toString();
    }
    List<String> firstSeq = Arrays.asList(StringUtils.split(first, delimiter));
    List<String> secondSeq = Arrays.asList(StringUtils.split(second, delimiter));
    @SuppressWarnings("unchecked")
    Collection<String> rs = CollectionUtils.subtract(firstSeq, secondSeq);
    StringBuilder buf = new StringBuilder();
    for (final String ele : rs) {
        buf.append(delimiter).append(ele);
    }
    if (buf.length() > 0) {
        buf.append(delimiter);
    }
    return buf.toString();
}

From source file:org.beangle.model.persist.hibernate.CriterionUtils.java

/**
 * ?. ??./* www.  ja  va2 s.  co m*/
 * 
 * @param entity
 * @param excludePropertes
 * @param mode
 * @return
 */
@SuppressWarnings("rawtypes")
public static List<Criterion> getEntityCriterions(String nestedName, Object entity, String[] excludePropertes,
        MatchMode mode, boolean ignoreZero) {
    if (null == entity) {
        return Collections.emptyList();
    }
    List<Criterion> criterions = CollectUtils.newArrayList();
    BeanMap map = new BeanMap(entity);
    Set keySet = map.keySet();
    Collection properties = null;
    if (null == excludePropertes) {
        List proList = CollectUtils.newArrayList();
        proList.addAll(keySet);
        properties = proList;
    } else {
        properties = CollectionUtils.subtract(keySet, Arrays.asList(excludePropertes));
    }
    properties.remove("class");

    for (Iterator iter = properties.iterator(); iter.hasNext();) {
        String propertyName = (String) iter.next();
        if (!PropertyUtils.isWriteable(entity, propertyName)) {
            continue;
        }
        Object value = map.get(propertyName);
        addCriterion(nestedName, entity, excludePropertes, propertyName, value, criterions, mode, ignoreZero);
    }
    return criterions;
}

From source file:org.broadinstitute.gatk.engine.recalibration.BQSRGatherer.java

/**
 * Gathers the input recalibration reports into a single report.
 *
 * @param inputs Input recalibration GATK reports
 * @return gathered recalibration GATK report
 *///  ww  w  . j a v a 2 s  .c o m
public static GATKReport gatherReport(final List<File> inputs) {
    final SortedSet<String> allReadGroups = new TreeSet<String>();
    final LinkedHashMap<File, Set<String>> inputReadGroups = new LinkedHashMap<File, Set<String>>();

    // Get the read groups from each input report
    for (final File input : inputs) {
        final Set<String> readGroups = RecalibrationReport.getReadGroups(input);
        inputReadGroups.put(input, readGroups);
        allReadGroups.addAll(readGroups);
    }

    // Log the read groups that are missing from specific inputs
    for (Map.Entry<File, Set<String>> entry : inputReadGroups.entrySet()) {
        final File input = entry.getKey();
        final Set<String> readGroups = entry.getValue();
        if (allReadGroups.size() != readGroups.size()) {
            // Since this is not completely unexpected, more than debug, but less than a proper warning.
            logger.info(MISSING_READ_GROUPS + ": " + input.getAbsolutePath());
            for (final Object readGroup : CollectionUtils.subtract(allReadGroups, readGroups)) {
                logger.info("  " + readGroup);
            }
        }
    }

    RecalibrationReport generalReport = null;
    for (File input : inputs) {
        final RecalibrationReport inputReport = new RecalibrationReport(input, allReadGroups);
        if (inputReport.isEmpty()) {
            continue;
        }

        if (generalReport == null)
            generalReport = inputReport;
        else
            generalReport.combine(inputReport);
    }
    if (generalReport == null)
        throw new ReviewedGATKException(EMPTY_INPUT_LIST);

    generalReport.calculateQuantizedQualities();

    return generalReport.createGATKReport();
}

From source file:org.cidarlab.eugene.dom.collection.CollectionOps.java

public static org.cidarlab.eugene.dom.collection.EugeneCollection minus(
        org.cidarlab.eugene.dom.collection.EugeneCollection col1,
        org.cidarlab.eugene.dom.collection.EugeneCollection col2) {
    if (null == col1 || null == col2) {
        return null;
    }//from ww  w. j  ava 2 s .co  m

    EugeneCollection objCollection = new EugeneCollection(col1.getName() + "-" + col2.getName());

    java.util.Collection objCol = CollectionUtils.subtract(col1.getElements(), col2.getElements());

    // TODO: add the objCol elements to a hash map
    objCollection.setElements((Set<CollectionElement>) objCol);

    // objCollection.setElements(objCol);
    return objCollection;
}

From source file:org.codehaus.mojo.nbm.CreateWebstartAppMojo.java

/**
 *
 * @throws org.apache.maven.plugin.MojoExecutionException
 * @throws org.apache.maven.plugin.MojoFailureException
 *//*from  w  w  w .ja  v a2s.c  o m*/
@Override
public void execute() throws MojoExecutionException, MojoFailureException {
    if ("none".equalsIgnoreCase(includeLocales)) {
        includeLocales = "";
    }

    if (signingThreads < 1) {
        signingThreads = Runtime.getRuntime().availableProcessors();
    }

    if ((signingMaximumThreads > 0) && (signingThreads > signingMaximumThreads)) {
        signingThreads = signingMaximumThreads;
    }

    getLog().info("Using " + signingThreads + " signing threads.");

    if (!"nbm-application".equals(project.getPackaging())) {
        throw new MojoExecutionException(
                "This goal only makes sense on project with nbm-application packaging.");
    }

    final Project antProject = antProject();

    getLog().warn(
            "WARNING: Unsigned and self-signed WebStart applications are deprecated from JDK7u21 onwards. To ensure future correct functionality please use trusted certificate.");

    if (keystore != null && keystorealias != null && keystorepassword != null) {
        File ks = new File(keystore);
        if (!ks.exists()) {
            throw new MojoFailureException("Cannot find keystore file at " + ks.getAbsolutePath());
        } else {
            //proceed..
        }
    } else if (keystore != null || keystorepassword != null || keystorealias != null) {
        throw new MojoFailureException(
                "If you want to sign the jnlp application, you need to define all three keystore related parameters.");
    } else {
        File generatedKeystore = new File(outputDirectory, "generated.keystore");
        if (!generatedKeystore.exists()) {
            getLog().warn("Keystore related parameters not set, generating a default keystore.");
            GenerateKey genTask = (GenerateKey) antProject.createTask("genkey");
            genTask.setAlias("jnlp");
            genTask.setStorepass("netbeans");
            genTask.setDname("CN=" + System.getProperty("user.name"));
            genTask.setKeystore(generatedKeystore.getAbsolutePath());
            genTask.execute();
        }
        keystore = generatedKeystore.getAbsolutePath();
        keystorepassword = "netbeans";
        keystorealias = "jnlp";
    }

    Taskdef taskdef = (Taskdef) antProject.createTask("taskdef");
    taskdef.setClassname(MakeJnlp2.class.getName());
    taskdef.setName("makejnlp");
    taskdef.execute();

    taskdef = (Taskdef) antProject.createTask("taskdef");
    taskdef.setClassname(Jar.class.getName());
    taskdef.setName("jar");
    taskdef.execute();

    taskdef = (Taskdef) antProject.createTask("taskdef");
    taskdef.setClassname(VerifyJNLP.class.getName());
    taskdef.setName("verifyjnlp");
    taskdef.execute();
    // +p

    try {
        final File webstartBuildDir = new File(
                outputDirectory + File.separator + "webstart" + File.separator + brandingToken);

        if (webstartBuildDir.exists()) {
            FileUtils.deleteDirectory(webstartBuildDir);
        }

        webstartBuildDir.mkdirs();

        // P: copy webappResources --[

        MavenResourcesExecution mavenResourcesExecution = new MavenResourcesExecution(webappResources,
                webstartBuildDir, project, encoding, Collections.EMPTY_LIST, Collections.EMPTY_LIST, session);
        mavenResourcesExecution.setEscapeWindowsPaths(true);
        mavenResourcesFiltering.filterResources(mavenResourcesExecution);

        // ]--

        final String localCodebase = codebase != null ? codebase : webstartBuildDir.toURI().toString();
        getLog().info("Generating webstartable binaries at " + webstartBuildDir.getAbsolutePath());

        final File nbmBuildDirFile = new File(outputDirectory, brandingToken);

        // +p (needs to be before make jnlp)

        //TODO is it really netbeans/
        if (masterJnlpFileName == null) {
            masterJnlpFileName = brandingToken;
        }

        Properties props = new Properties();
        props.setProperty("jnlp.codebase", localCodebase);
        props.setProperty("app.name", brandingToken);
        props.setProperty("app.title", project.getName());
        if (project.getOrganization() != null) {
            props.setProperty("app.vendor", project.getOrganization().getName());
        } else {
            props.setProperty("app.vendor", "Nobody");
        }
        String description = project.getDescription() != null ? project.getDescription()
                : "No Project Description";
        props.setProperty("app.description", description);
        props.setProperty("branding.token", brandingToken);
        props.setProperty("master.jnlp.file.name", masterJnlpFileName);
        props.setProperty("netbeans.jnlp.fixPolicy", "false");

        StringBuilder stBuilder = new StringBuilder();
        if (additionalArguments != null) {
            StringTokenizer st = new StringTokenizer(additionalArguments);
            while (st.hasMoreTokens()) {
                String arg = st.nextToken();
                if (arg.startsWith("-J")) {
                    if (stBuilder.length() > 0) {
                        stBuilder.append(' ');
                    }
                    stBuilder.append(arg.substring(2));
                }
            }
        }
        props.setProperty("netbeans.run.params", stBuilder.toString());

        final File masterJnlp = new File(webstartBuildDir, masterJnlpFileName + ".jnlp");

        filterCopy(masterJnlpFile, "master.jnlp", masterJnlp, props);

        if (generateJnlpTimestamp) //  \/\/\/\/  bad bad bad  \/\/\/\/
        {
            final File masterJnlpFileTmp = File.createTempFile(masterJnlpFileName + "_", "");

            Files.append(JnlpUtils.getCurrentJnlpTimestamp() + "\n", masterJnlpFileTmp,
                    Charset.forName("UTF-8"));

            ByteSink sink = Files.asByteSink(masterJnlpFileTmp, FileWriteMode.APPEND);

            sink.write(Files.toByteArray(masterJnlp));

            Files.copy(masterJnlpFileTmp, masterJnlp);
        }

        File startup = copyLauncher(outputDirectory, nbmBuildDirFile);

        String masterJnlpStr = FileUtils.fileRead(masterJnlp);

        // P: JNLP-INF/APPLICATION_TEMPLATE.JNLP support --[
        // this can be done better and will
        // ashamed
        if (generateJnlpApplicationTemplate) {
            File jnlpInfDir = new File(outputDirectory, "JNLP-INF");

            getLog().info("Generate JNLP application template under: " + jnlpInfDir);

            jnlpInfDir.mkdirs();

            File jnlpTemplate = new File(jnlpInfDir, "APPLICATION_TEMPLATE.JNLP");

            masterJnlpStr = masterJnlpStr.replaceAll("(<jnlp.*codebase\\ *=\\ *)\"((?!\").)*", "$1\"*")
                    .replaceAll("(<jnlp.*href\\ *=\\ *)\"((?!\").)*", "$1\"*");

            FileUtils.fileWrite(jnlpTemplate, masterJnlpStr);

            File startupMerged = new File(outputDirectory, "startup-jnlpinf.jar");

            Jar jar = (Jar) antProject.createTask("jar");
            jar.setDestFile(startupMerged);
            jar.setFilesetmanifest((FilesetManifestConfig) EnumeratedAttribute
                    .getInstance(FilesetManifestConfig.class, "merge"));

            FileSet jnlpInfDirectoryFileSet = new FileSet();
            jnlpInfDirectoryFileSet.setDir(outputDirectory);
            jnlpInfDirectoryFileSet.setIncludes("JNLP-INF/**");

            jar.addFileset(jnlpInfDirectoryFileSet);

            ZipFileSet startupJar = new ZipFileSet();
            startupJar.setSrc(startup);

            jar.addZipfileset(startupJar);

            jar.execute();

            startup = startupMerged;

            getLog().info("APPLICATION_TEMPLATE.JNLP generated - startup.jar: " + startup);
        }

        final JarsConfig startupConfig = new JarsConfig();

        ManifestEntries startupManifestEntries = new ManifestEntries();

        startupConfig.setManifestEntries(startupManifestEntries);

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

        if (!validateJnlpDtd) {
            factory.setValidating(false);
            factory.setNamespaceAware(true);
            factory.setFeature("http://xml.org/sax/features/namespaces", false);
            factory.setFeature("http://xml.org/sax/features/validation", false);
            factory.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false);
            factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
        }
        DocumentBuilder builder = factory.newDocumentBuilder();

        final BufferedReader masterJnlpStrReader = new BufferedReader(new StringReader(masterJnlpStr));

        if (generateJnlpTimestamp) {
            masterJnlpStrReader.readLine();
        }

        Document doc = builder.parse(new InputSource(masterJnlpStrReader));

        Element jnlpRoot = doc.getDocumentElement();

        jarCodebase = jnlpRoot.getAttribute("codebase");

        if (jarCodebase.isEmpty()) {
            jarCodebase = "*";
        }

        startupManifestEntries.setCodebase(jarCodebase);

        XPath xpath = XPathFactory.newInstance().newXPath();

        Node jnlpSecurityPermission = (Node) xpath.evaluate(
                "(/jnlp/security/all-permissions | /jnlp/security/j2ee-application-client-permissions)[1]", doc,
                XPathConstants.NODE);

        if (jnlpSecurityPermission == null) {
            jarPermissions = "sandbox";
            jnlpSecurity = "";
        } else {
            jarPermissions = "all-permissions";
            jnlpSecurity = "<security><" + jnlpSecurityPermission.getNodeName() + "/></security>";
        }

        startupManifestEntries.setPermissions(jarPermissions);

        if (applicationName == null) {
            String jnlpApplicationTitle = (String) xpath.evaluate("/jnlp/information/title", doc,
                    XPathConstants.STRING);

            applicationName = jnlpApplicationTitle == null ? brandingToken : jnlpApplicationTitle;
        }

        startupManifestEntries.setApplicationName(applicationName);

        // +p

        if (autoManifestSecurityEntries) {
            if (jarsConfigs == null) {
                jarsConfigs = new ArrayList<JarsConfig>();
            }

            jarsConfigs.add(0, startupConfig);
        }

        final List<SignJar.JarsConfig> signJarJarsConfigs = buildSignJarJarsConfigs(jarsConfigs);

        File jnlpDestination = new File(webstartBuildDir.getAbsolutePath() + File.separator + "startup.jar");

        SignJar signTask = (SignJar) antProject.createTask("signjar");
        signTask.setKeystore(keystore);
        signTask.setStorepass(keystorepassword);
        signTask.setAlias(keystorealias);

        if (keystoretype != null) {
            signTask.setStoretype(keystoretype);
        }

        signTask.setForce(signingForce);
        signTask.setTsacert(signingTsaCert);
        signTask.setTsaurl(signingTsaUrl);
        signTask.setMaxmemory(signingMaxMemory);
        signTask.setRetryCount(signingRetryCount);

        signTask.setUnsignFirst(signingRemoveExistingSignatures);

        signTask.setJarsConfigs(buildSignJarJarsConfigs(Collections.singletonList(startupConfig)));

        signTask.setBasedir(nbmBuildDirFile);

        signTask.setSignedjar(jnlpDestination);

        signTask.setJar(startup);

        signTask.setPack200(pack200);
        signTask.setPack200Effort(pack200Effort);

        signTask.execute();
        // <-- all of this will be refactored soon ]--

        //            FileUtils.copyDirectoryStructureIfModified( nbmBuildDirFile, webstartBuildDir );

        MakeJnlp2 jnlpTask = (MakeJnlp2) antProject.createTask("makejnlp");
        jnlpTask.setOptimize(optimize);
        jnlpTask.setIncludelocales(includeLocales);
        jnlpTask.setDir(webstartBuildDir);
        jnlpTask.setCodebase(localCodebase);
        //TODO, how to figure verify excludes..
        jnlpTask.setVerify(false);
        jnlpTask.setPermissions(jnlpSecurity);
        jnlpTask.setSignJars(true);

        jnlpTask.setAlias(keystorealias);
        jnlpTask.setKeystore(keystore);
        jnlpTask.setStorePass(keystorepassword);
        if (keystoretype != null) {
            jnlpTask.setStoreType(keystoretype);
        }

        jnlpTask.setSigningForce(signingForce);
        jnlpTask.setSigningTsaCert(signingTsaCert);
        jnlpTask.setSigningTsaUrl(signingTsaUrl);
        jnlpTask.setUnsignFirst(signingRemoveExistingSignatures);
        jnlpTask.setJarsConfigs(signJarJarsConfigs);
        jnlpTask.setSigningMaxMemory(signingMaxMemory);
        jnlpTask.setSigningRetryCount(signingRetryCount);
        jnlpTask.setBasedir(nbmBuildDirFile);

        jnlpTask.setNbThreads(signingThreads);

        jnlpTask.setProcessJarVersions(processJarVersions);

        jnlpTask.setPack200(pack200);
        jnlpTask.setPack200Effort(pack200Effort);

        FileSet fs = jnlpTask.createModules();
        fs.setDir(nbmBuildDirFile);
        OrSelector or = new OrSelector();
        AndSelector and = new AndSelector();
        FilenameSelector inc = new FilenameSelector();
        inc.setName("*/modules/**/*.jar");
        or.addFilename(inc);
        inc = new FilenameSelector();
        inc.setName("*/lib/**/*.jar");
        or.addFilename(inc);
        inc = new FilenameSelector();
        inc.setName("*/core/**/*.jar");
        or.addFilename(inc);

        ModuleSelector ms = new ModuleSelector();
        Parameter included = new Parameter();
        included.setName("includeClusters");
        included.setValue("");
        Parameter excluded = new Parameter();
        excluded.setName("excludeClusters");
        excluded.setValue("");
        Parameter exModules = new Parameter();
        exModules.setName("excludeModules");
        exModules.setValue("");
        ms.setParameters(new Parameter[] { included, excluded, exModules });
        and.add(or);
        and.add(ms);
        fs.addAnd(and);
        jnlpTask.execute();

        Set<String> locales = jnlpTask.getExecutedLocales();

        String extSnippet = generateExtensions(fs, antProject, ""); // "netbeans/"

        //branding
        DirectoryScanner ds = new DirectoryScanner();
        ds.setBasedir(nbmBuildDirFile);

        final List<String> localeIncludes = new ArrayList<String>();
        final List<String> localeExcludes = new ArrayList<String>();

        localeIncludes.add("**/locale/*.jar");

        if (includeLocales != null) {
            List<String> excludes = Splitter.on(',').trimResults().omitEmptyStrings()
                    .splitToList(includeLocales);

            for (String exclude : (Collection<String>) CollectionUtils.subtract(locales, excludes)) {
                localeExcludes.add("**/locale/*_" + exclude + ".jar");
            }
        }

        ds.setIncludes(localeIncludes.toArray(new String[localeIncludes.size()]));
        ds.setExcludes(localeExcludes.toArray(new String[localeExcludes.size()]));
        ds.scan();
        String[] includes = ds.getIncludedFiles();

        StringBuilder brandRefs = new StringBuilder(
                "<property name=\"jnlp.packEnabled\" value=\"" + String.valueOf(pack200) + "\"/>\n");

        if (includes != null && includes.length > 0) {
            final File brandingDir = new File(webstartBuildDir, "branding");
            brandingDir.mkdirs();
            for (String incBran : includes) {
                File source = new File(nbmBuildDirFile, incBran);
                File dest = new File(brandingDir, source.getName());
                brandRefs.append("    <jar href=\'branding/").append(dest.getName()).append("\'/>\n");
            }

            final ExecutorService executorService = Executors.newFixedThreadPool(signingThreads);

            final List<Exception> threadException = new ArrayList<Exception>();

            for (final String toSign : includes) {
                executorService.execute(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            File toSignFile = new File(nbmBuildDirFile, toSign);

                            SignJar signTask = (SignJar) antProject.createTask("signjar");
                            if (keystoretype != null) {
                                signTask.setStoretype(keystoretype);
                            }
                            signTask.setKeystore(keystore);
                            signTask.setStorepass(keystorepassword);
                            signTask.setAlias(keystorealias);
                            signTask.setForce(signingForce);
                            signTask.setTsacert(signingTsaCert);
                            signTask.setTsaurl(signingTsaUrl);
                            signTask.setMaxmemory(signingMaxMemory);
                            signTask.setRetryCount(signingRetryCount);
                            signTask.setUnsignFirst(signingRemoveExistingSignatures);
                            signTask.setJarsConfigs(signJarJarsConfigs);
                            signTask.setJar(toSignFile);
                            signTask.setDestDir(brandingDir);
                            signTask.setBasedir(nbmBuildDirFile);
                            signTask.setDestFlatten(true);
                            signTask.setPack200(pack200);
                            signTask.setPack200Effort(pack200Effort);
                            signTask.execute();
                        } catch (Exception e) {
                            threadException.add(e);
                        }
                    }
                });
            }

            executorService.shutdown();

            executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);

            if (!threadException.isEmpty()) {
                throw threadException.get(0);
            }
        }

        File modulesJnlp = new File(webstartBuildDir.getAbsolutePath() + File.separator + "modules.jnlp");
        props.setProperty("jnlp.branding.jars", brandRefs.toString());
        props.setProperty("jnlp.resources", extSnippet);
        filterCopy(null, /* filename is historical */"branding.jnlp", modulesJnlp, props);

        if (verifyJnlp) {
            getLog().info("Verifying generated webstartable content.");
            VerifyJNLP verifyTask = (VerifyJNLP) antProject.createTask("verifyjnlp");
            FileSet verify = new FileSet();
            verify.setFile(masterJnlp);
            verifyTask.addConfiguredFileset(verify);
            verifyTask.execute();
        }

        // create zip archive
        if (destinationFile.exists()) {
            destinationFile.delete();
        }
        ZipArchiver archiver = new ZipArchiver();
        if (codebase != null) {
            getLog().warn("Defining <codebase>/${nbm.webstart.codebase} is generally unnecessary");
            archiver.addDirectory(webstartBuildDir);
        } else {
            archiver.addDirectory(webstartBuildDir, null, new String[] { "**/*.jnlp" });
            for (final File jnlp : webstartBuildDir.listFiles()) {
                if (!jnlp.getName().endsWith(".jnlp")) {
                    continue;
                }
                archiver.addResource(new PlexusIoResource() {
                    public @Override InputStream getContents() throws IOException {
                        return new ByteArrayInputStream(FileUtils.fileRead(jnlp, "UTF-8")
                                .replace(localCodebase, "$$codebase").getBytes("UTF-8"));
                    }

                    public @Override long getLastModified() {
                        return jnlp.lastModified();
                    }

                    public @Override boolean isExisting() {
                        return true;
                    }

                    public @Override long getSize() {
                        return UNKNOWN_RESOURCE_SIZE;
                    }

                    public @Override URL getURL() throws IOException {
                        return null;
                    }

                    public @Override String getName() {
                        return jnlp.getAbsolutePath();
                    }

                    public @Override boolean isFile() {
                        return true;
                    }

                    public @Override boolean isDirectory() {
                        return false;
                    }
                }, jnlp.getName(), archiver.getDefaultFileMode());
            }
        }
        File jdkhome = new File(System.getProperty("java.home"));
        File servlet = new File(jdkhome, "sample/jnlp/servlet/jnlp-servlet.jar");
        if (!servlet.exists()) {
            servlet = new File(jdkhome.getParentFile(), "sample/jnlp/servlet/jnlp-servlet.jar");

            if (!servlet.exists()) {
                servlet = File.createTempFile("nbm_", "jnlp-servlet.jar");

                FileUtils.copyURLToFile(
                        Thread.currentThread().getContextClassLoader().getResource("jnlp-servlet.jar"),
                        servlet);
            }
        }
        if (servlet.exists()) {
            File servletDir = new File(webstartBuildDir, "WEB-INF/lib");

            servletDir.mkdirs();

            signTask = (SignJar) antProject.createTask("signjar");
            signTask.setKeystore(keystore);
            signTask.setStorepass(keystorepassword);
            signTask.setAlias(keystorealias);
            signTask.setForce(signingForce);
            signTask.setTsacert(signingTsaCert);
            signTask.setTsaurl(signingTsaUrl);
            signTask.setMaxmemory(signingMaxMemory);
            signTask.setRetryCount(signingRetryCount);
            signTask.setJar(servlet);
            signTask.setSignedjar(new File(servletDir, "jnlp-servlet.jar"));
            signTask.execute();

            //archiver.addFile( servlet, "WEB-INF/lib/jnlp-servlet.jar" );
            archiver.addResource(new PlexusIoResource() {
                public @Override InputStream getContents() throws IOException {
                    return new ByteArrayInputStream(("" + "<web-app>\n" + "    <servlet>\n"
                            + "        <servlet-name>JnlpDownloadServlet</servlet-name>\n"
                            + "        <servlet-class>jnlp.sample.servlet.JnlpDownloadServlet</servlet-class>\n"
                            + "    </servlet>\n" + "    <servlet-mapping>\n"
                            + "        <servlet-name>JnlpDownloadServlet</servlet-name>\n"
                            + "        <url-pattern>*.jnlp</url-pattern>\n" + "    </servlet-mapping>\n"
                            + "    <servlet-mapping>\n"
                            + "        <servlet-name>JnlpDownloadServlet</servlet-name>\n"
                            + "        <url-pattern>*.jar</url-pattern>\n" + "    </servlet-mapping>\n"
                            + "    <mime-mapping>\n" + "        <extension>jnlp</extension>\n"
                            + "        <mime-type>application/x-java-jnlp-file</mime-type>\n"
                            + "    </mime-mapping>\n" + "</web-app>\n").getBytes());
                }

                public @Override long getLastModified() {
                    return UNKNOWN_MODIFICATION_DATE;
                }

                public @Override boolean isExisting() {
                    return true;
                }

                public @Override long getSize() {
                    return UNKNOWN_RESOURCE_SIZE;
                }

                public @Override URL getURL() throws IOException {
                    return null;
                }

                public @Override String getName() {
                    return "web.xml";
                }

                public @Override boolean isFile() {
                    return true;
                }

                public @Override boolean isDirectory() {
                    return false;
                }
            }, "WEB-INF/web.xml", archiver.getDefaultFileMode());
        }
        archiver.setDestFile(destinationFile);
        archiver.createArchive();

        if (signWar) {
            signTask = (SignJar) antProject.createTask("signjar");
            signTask.setKeystore(keystore);
            signTask.setStorepass(keystorepassword);
            signTask.setAlias(keystorealias);
            signTask.setForce(signingForce);
            signTask.setTsacert(signingTsaCert);
            signTask.setTsaurl(signingTsaUrl);
            signTask.setMaxmemory(signingMaxMemory);
            signTask.setRetryCount(signingRetryCount);
            signTask.setJar(destinationFile);
            signTask.execute();
        }

        // attach standalone so that it gets installed/deployed
        projectHelper.attachArtifact(project, "war", webstartClassifier, destinationFile);

    } catch (Exception ex) {
        throw new MojoExecutionException("Error creating webstartable binary.", ex);
    }
}

From source file:org.compiere.mfg_scm.pluginManager.Mfg_scmUtils.java

/**
 * Take a dominant and recessive Map and merge the key:value pairs where the
 * recessive Map may add key:value pairs to the dominant Map but may not
 * override any existing key:value pairs.
 * /*from  ww w .  j  a  v a2s.  com*/
 * If we have two Maps, a dominant and recessive, and their respective keys
 * are as follows:
 * 
 * dominantMapKeys = { a, b, c, d, e, f } recessiveMapKeys = { a, b, c, x, y, z }
 * 
 * Then the result should be the following:
 * 
 * resultantKeys = { a, b, c, d, e, f, x, y, z }
 * 
 * @param dominantMap
 *            Dominant Map.
 * @param recessiveMap
 *            Recessive Map.
 * @return The result map with combined dominant and recessive values.
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
public static Map mergeMaps(Map dominantMap, Map recessiveMap) {
    Map result = new HashMap();

    if (dominantMap == null && recessiveMap == null) {
        return null;
    }

    if (dominantMap != null && recessiveMap == null) {
        return dominantMap;
    }

    if (dominantMap == null) {
        return recessiveMap;
    }

    // Grab the keys from the dominant and recessive maps.
    Set dominantMapKeys = dominantMap.keySet();
    Set recessiveMapKeys = recessiveMap.keySet();

    // Create the set of keys that will be contributed by the
    // recessive Map by subtracting the intersection of keys
    // from the recessive Map's keys.
    Collection contributingRecessiveKeys = CollectionUtils.subtract(recessiveMapKeys,
            CollectionUtils.intersection(dominantMapKeys, recessiveMapKeys));

    result.putAll(dominantMap);

    // Now take the keys we just found and extract the values from
    // the recessiveMap and put the key:value pairs into the dominantMap.
    for (Iterator i = contributingRecessiveKeys.iterator(); i.hasNext();) {
        Object key = i.next();
        result.put(key, recessiveMap.get(key));
    }

    return result;
}