Example usage for com.google.common.io ByteSink write

List of usage examples for com.google.common.io ByteSink write

Introduction

In this page you can find the example usage for com.google.common.io ByteSink write.

Prototype

public void write(byte[] bytes) throws IOException 

Source Link

Document

Writes all the given bytes to this sink.

Usage

From source file:me.tatarka.silentsupport.lint.ApiLookup.java

/**
 * See the {@link #readData(LintClient, File, File)} for documentation on the data format.
 *//*from w w  w  .  j av  a2 s  .  c o m*/
private static void writeDatabase(File file, Api info, boolean isSupport) throws IOException {
    Map<String, ApiClass> classMap = info.getClasses();

    List<ApiPackage> packages = Lists.newArrayList(info.getPackages().values());
    Collections.sort(packages);

    // Compute members of each class that must be included in the database; we can
    // skip those that have the same since-level as the containing class. And we
    // also need to keep those entries that are marked deprecated.
    int estimatedSize = 0;
    for (ApiPackage pkg : packages) {
        estimatedSize += 4; // offset entry
        estimatedSize += pkg.getName().length() + 20; // package entry

        if (assertionsEnabled() && !isRelevantOwner(pkg.getName() + "/")
                && !pkg.getName().startsWith("android/support")) {
            System.out.println("Warning: isRelevantOwner fails for " + pkg.getName() + "/");
        }

        for (ApiClass apiClass : pkg.getClasses()) {
            estimatedSize += 4; // offset entry
            estimatedSize += apiClass.getName().length() + 20; // class entry

            Set<String> allMethods = apiClass.getAllMethods(info);
            Set<String> allFields = apiClass.getAllFields(info);
            // Strip out all members that have been supported since version 1.
            // This makes the database *much* leaner (down from about 4M to about
            // 1.7M), and this just fills the table with entries that ultimately
            // don't help the API checker since it just needs to know if something
            // requires a version *higher* than the minimum. If in the future the
            // database needs to answer queries about whether a method is public
            // or not, then we'd need to put this data back in.
            int clsSince = apiClass.getSince();
            List<String> members = new ArrayList<>(allMethods.size() + allFields.size());
            for (String member : allMethods) {
                if (isSupport || apiClass.getMethod(member, info) != clsSince
                        || apiClass.getMemberDeprecatedIn(member, info) > 0) {
                    members.add(member);
                }
            }
            for (String member : allFields) {
                if (isSupport || apiClass.getField(member, info) != clsSince
                        || apiClass.getMemberDeprecatedIn(member, info) > 0) {
                    members.add(member);
                }
            }

            estimatedSize += 2 + 4 * (apiClass.getInterfaces().size());
            if (apiClass.getSuperClasses().size() > 1) {
                estimatedSize += 2 + 4 * (apiClass.getSuperClasses().size());
            }

            // Only include classes that have one or more members requiring version 2 or higher:
            Collections.sort(members);
            apiClass.members = members;
            for (String member : members) {
                estimatedSize += member.length();
                estimatedSize += 16;
            }
        }

        // Ensure the classes are sorted
        Collections.sort(pkg.getClasses());
    }

    // Write header
    ByteBuffer buffer = ByteBuffer.allocate(estimatedSize);
    buffer.order(ByteOrder.BIG_ENDIAN);
    buffer.put(FILE_HEADER.getBytes(Charsets.US_ASCII));
    buffer.put((byte) BINARY_FORMAT_VERSION);

    int indexCountOffset = buffer.position();
    int indexCount = 0;

    buffer.putInt(0); // placeholder

    // Write the number of packages in the package index
    buffer.putInt(packages.size());

    // Write package index
    int newIndex = buffer.position();
    for (ApiPackage pkg : packages) {
        pkg.indexOffset = newIndex;
        newIndex += 4;
        indexCount++;
    }

    // Write class index
    for (ApiPackage pkg : packages) {
        for (ApiClass cls : pkg.getClasses()) {
            cls.indexOffset = newIndex;
            cls.index = indexCount;
            newIndex += 4;
            indexCount++;
        }
    }

    // Write member indices
    for (ApiPackage pkg : packages) {
        for (ApiClass cls : pkg.getClasses()) {
            if (cls.members != null && !cls.members.isEmpty()) {
                cls.memberOffsetBegin = newIndex;
                cls.memberIndexStart = indexCount;
                for (String ignored : cls.members) {
                    newIndex += 4;
                    indexCount++;
                }
                cls.memberOffsetEnd = newIndex;
                cls.memberIndexLength = indexCount - cls.memberIndexStart;
            } else {
                cls.memberOffsetBegin = -1;
                cls.memberOffsetEnd = -1;
                cls.memberIndexStart = -1;
                cls.memberIndexLength = 0;
            }
        }
    }

    // Fill in the earlier index count
    buffer.position(indexCountOffset);
    buffer.putInt(indexCount);
    buffer.position(newIndex);

    // Write member entries
    for (ApiPackage pkg : packages) {
        for (ApiClass apiClass : pkg.getClasses()) {
            String clz = apiClass.getName();
            int index = apiClass.memberOffsetBegin;
            for (String member : apiClass.members) {
                // Update member offset to point to this entry
                int start = buffer.position();
                buffer.position(index);
                buffer.putInt(start);
                index = buffer.position();
                buffer.position(start);

                int since;
                if (member.indexOf('(') != -1) {
                    since = apiClass.getMethod(member, info);
                } else {
                    since = apiClass.getField(member, info);
                }
                if (since == Integer.MAX_VALUE) {
                    assert false : clz + ':' + member;
                    since = 1;
                }

                int deprecatedIn = apiClass.getMemberDeprecatedIn(member, info);
                if (deprecatedIn != 0) {
                    assert deprecatedIn != -1 : deprecatedIn + " for " + member;
                }

                byte[] signature = member.getBytes(Charsets.UTF_8);
                for (byte b : signature) {
                    // Make sure all signatures are really just simple ASCII
                    assert b == (b & 0x7f) : member;
                    buffer.put(b);
                    // Skip types on methods
                    if (b == (byte) ')') {
                        break;
                    }
                }
                buffer.put((byte) 0);
                int api = since;
                assert api == UnsignedBytes.toInt((byte) api);
                assert api >= 1 && api < 0xFF; // max that fits in a byte

                boolean isDeprecated = deprecatedIn > 0;
                if (isDeprecated) {
                    api |= HAS_DEPRECATION_BYTE_FLAG;
                }

                buffer.put((byte) api);

                if (isDeprecated) {
                    assert deprecatedIn == UnsignedBytes.toInt((byte) deprecatedIn);
                    buffer.put((byte) deprecatedIn);
                }
            }
            assert index == apiClass.memberOffsetEnd : apiClass.memberOffsetEnd;
        }
    }

    // Write class entries. These are written together, rather than
    // being spread out among the member entries, in order to have
    // reference locality (search that a binary search through the classes
    // are likely to look at entries near each other.)
    for (ApiPackage pkg : packages) {
        List<ApiClass> classes = pkg.getClasses();
        for (ApiClass cls : classes) {
            int index = buffer.position();
            buffer.position(cls.indexOffset);
            buffer.putInt(index);
            buffer.position(index);
            String name = cls.getSimpleName();

            byte[] nameBytes = name.getBytes(Charsets.UTF_8);
            assert nameBytes.length < 254 : name;
            buffer.put((byte) (nameBytes.length + 2)); // 2: terminating 0, and this byte itself
            buffer.put(nameBytes);
            buffer.put((byte) 0);

            // 3 bytes for beginning, 2 bytes for *length*
            put3ByteInt(buffer, cls.memberIndexStart);
            put2ByteInt(buffer, cls.memberIndexLength);

            ApiClass apiClass = classMap.get(cls.getName());
            assert apiClass != null : cls.getName();
            int since = apiClass.getSince();
            assert since == UnsignedBytes.toInt((byte) since) : since; // make sure it fits
            int deprecatedIn = apiClass.getDeprecatedIn();
            boolean isDeprecated = deprecatedIn > 0;
            // The first byte is deprecated in
            if (isDeprecated) {
                since |= HAS_DEPRECATION_BYTE_FLAG;
                assert since == UnsignedBytes.toInt((byte) since) : since; // make sure it fits
            }
            buffer.put((byte) since);
            if (isDeprecated) {
                assert deprecatedIn == UnsignedBytes.toInt((byte) deprecatedIn) : deprecatedIn;
                buffer.put((byte) deprecatedIn);
            }

            List<Pair<String, Integer>> interfaces = apiClass.getInterfaces();
            int count = 0;
            if (interfaces != null && !interfaces.isEmpty()) {
                for (Pair<String, Integer> pair : interfaces) {
                    int api = pair.getSecond();
                    if (api > apiClass.getSince()) {
                        count++;
                    }
                }
            }
            List<Pair<String, Integer>> supers = apiClass.getSuperClasses();
            if (supers != null && !supers.isEmpty()) {
                for (Pair<String, Integer> pair : supers) {
                    int api = pair.getSecond();
                    if (api > apiClass.getSince()) {
                        count++;
                    }
                }
            }
            buffer.put((byte) count);
            if (count > 0) {
                if (supers != null) {
                    for (Pair<String, Integer> pair : supers) {
                        int api = pair.getSecond();
                        if (api > apiClass.getSince()) {
                            ApiClass superClass = classMap.get(pair.getFirst());
                            assert superClass != null : cls;
                            put3ByteInt(buffer, superClass.index);
                            buffer.put((byte) api);
                        }
                    }
                }
                if (interfaces != null) {
                    for (Pair<String, Integer> pair : interfaces) {
                        int api = pair.getSecond();
                        if (api > apiClass.getSince()) {
                            ApiClass interfaceClass = classMap.get(pair.getFirst());
                            assert interfaceClass != null : cls;
                            put3ByteInt(buffer, interfaceClass.index);
                            buffer.put((byte) api);
                        }
                    }
                }
            }
        }
    }

    for (ApiPackage pkg : packages) {
        int index = buffer.position();
        buffer.position(pkg.indexOffset);
        buffer.putInt(index);
        buffer.position(index);

        byte[] bytes = pkg.getName().getBytes(Charsets.UTF_8);
        buffer.put(bytes);
        buffer.put((byte) 0);

        List<ApiClass> classes = pkg.getClasses();
        if (classes.isEmpty()) {
            put3ByteInt(buffer, 0);
            put2ByteInt(buffer, 0);
        } else {
            // 3 bytes for beginning, 2 bytes for *length*
            int firstClassIndex = classes.get(0).index;
            int classCount = classes.get(classes.size() - 1).index - firstClassIndex + 1;
            put3ByteInt(buffer, firstClassIndex);
            put2ByteInt(buffer, classCount);
        }
    }

    int size = buffer.position();
    assert size <= buffer.limit();
    buffer.mark();

    if (WRITE_STATS) {
        System.out.print("Actual binary size: " + size + " bytes");
        System.out.println(String.format(" (%.1fM)", size / (1024 * 1024.f)));
    }

    // Now dump this out as a file
    // There's probably an API to do this more efficiently; TODO: Look into this.
    byte[] b = new byte[size];
    buffer.rewind();
    buffer.get(b);
    if (file.exists()) {
        boolean deleted = file.delete();
        assert deleted : file;
    }
    ByteSink sink = Files.asByteSink(file);
    sink.write(b);
}

From source file:eu.eubrazilcc.lvl.core.entrez.EntrezHelper.java

private void efetchFlatFiles(final List<String> ids, final int retstart, final int retmax, final File directory)
        throws Exception {
    // save the bulk of files to a temporary file
    final File tmpFile = createTempFile("gb-", ".tmp", directory);
    final String idsParam = Joiner.on(",").skipNulls().join(ids);
    LOGGER.trace("Fetching " + ids.size() + " files from GenBank, retstart=" + retstart + ", retmax=" + retmax
            + ", file=" + tmpFile.getPath());
    httpClient.request(EFETCH_BASE_URI).post()
            .bodyForm(efetchForm(NUCLEOTIDE_DB, idsParam, retstart, retmax, "text").build())
            .saveContent(tmpFile, true);
    // go over the file extracting the sequences
    final ListenableFuture<String[]> future = TASK_RUNNER.submit(new Callable<String[]>() {
        @Override/*from  ww w. j  a va 2  s.  c  om*/
        public String[] call() throws Exception {
            final Set<String> files = newHashSet();
            final BufferedReader reader = newBufferedReader(tmpFile.toPath(), DEFAULT_CHARSET);
            int i = -1;
            File file = null;
            ByteSink sink = null;
            String line = null;
            while ((line = reader.readLine()) != null) {
                // start parsing a new fragment
                if (file == null && i < ids.size() - 1) {
                    file = new File(directory, ids.get(++i) + ".gb");
                    sink = asByteSink(file, FileWriteMode.APPEND);
                    LOGGER.info("Processing file: " + file.getCanonicalPath());
                }
                if (i < ids.size()) {
                    // write non-empty lines to the file
                    if (isNotBlank(line)) {
                        if (sink != null) {
                            sink.write((line + "\n").getBytes(DEFAULT_CHARSET));
                        } else {
                            LOGGER.warn("Ingoring line when all files were closed: " + line);
                        }
                    }
                    // process line
                    if (line.startsWith("VERSION    ")) {
                        checkState(line.contains(ids.get(i)), "Id not found in the VERSION section");
                    } else if (line.startsWith("//")) {
                        files.add(file.getCanonicalPath());
                        file = null;
                    }
                } else {
                    if (isNotBlank(line)) {
                        LOGGER.warn("Ingoring line after all sequences were processed: " + line);
                    }
                }
            }
            return files.toArray(new String[files.size()]);
        }
    });
    addCallback(future, new FutureCallback<String[]>() {
        @Override
        public void onSuccess(final String[] result) {
            LOGGER.info("One bulk sequence file was processed successfully: " + tmpFile.getName()
                    + ", number of created files: " + result.length);
            deleteQuietly(tmpFile);
        }

        @Override
        public void onFailure(final Throwable error) {
            LOGGER.error("Failed to process bulk sequence file " + tmpFile.getName(), error);
        }
    });
    // wait for files to be processed
    future.get();
}

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

/**
 *
 * @throws org.apache.maven.plugin.MojoExecutionException
 * @throws org.apache.maven.plugin.MojoFailureException
 *//*from   ww w .ja v  a 2s .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);
    }
}