Example usage for org.apache.commons.io FileUtils writeByteArrayToFile

List of usage examples for org.apache.commons.io FileUtils writeByteArrayToFile

Introduction

In this page you can find the example usage for org.apache.commons.io FileUtils writeByteArrayToFile.

Prototype

public static void writeByteArrayToFile(File file, byte[] data) throws IOException 

Source Link

Document

Writes a byte array to a file creating the file if it does not exist.

Usage

From source file:org.broadinstitute.sting.utils.help.GATKDoclet.java

/**
 * @param rootDoc/*w w  w .  j a  va2 s . c om*/
 */
private void processDocs(RootDoc rootDoc) {
    // setup the global access to the root
    this.rootDoc = rootDoc;

    try {
        // basic setup
        DESTINATION_DIR.mkdirs();
        FileUtils.copyFile(new File(SETTINGS_DIR + "/bootstrap.min.css"),
                new File(DESTINATION_DIR + "/bootstrap.min.css"));
        FileUtils.copyFile(new File(SETTINGS_DIR + "/bootstrap.min.js"),
                new File(DESTINATION_DIR + "/bootstrap.min.js"));
        FileUtils.copyFile(new File(SETTINGS_DIR + "/jquery.min.js"),
                new File(DESTINATION_DIR + "/jquery.min.js"));
        // print the Version number
        FileUtils.writeByteArrayToFile(new File(DESTINATION_DIR + "/current.version.txt"),
                getSimpleVersion(absoluteVersion).getBytes());

        /* ------------------------------------------------------------------- */
        /* You should do this ONLY ONCE in the whole application life-cycle:   */

        Configuration cfg = new Configuration();
        // Specify the data source where the template files come from.
        cfg.setDirectoryForTemplateLoading(SETTINGS_DIR);
        // Specify how templates will see the data-model. This is an advanced topic...
        cfg.setObjectWrapper(new DefaultObjectWrapper());

        myWorkUnits = computeWorkUnits();

        List<Map<String, String>> groups = new ArrayList<Map<String, String>>();
        Set<String> seenDocumentationFeatures = new HashSet<String>();
        List<Map<String, String>> data = new ArrayList<Map<String, String>>();
        for (GATKDocWorkUnit workUnit : myWorkUnits) {
            data.add(workUnit.indexDataMap());
            if (!seenDocumentationFeatures.contains(workUnit.annotation.groupName())) {
                groups.add(toMap(workUnit.annotation));
                seenDocumentationFeatures.add(workUnit.annotation.groupName());
            }
        }

        for (GATKDocWorkUnit workUnit : myWorkUnits) {
            processDocWorkUnit(cfg, workUnit, groups, data);
        }

        processIndex(cfg, new ArrayList<GATKDocWorkUnit>(myWorkUnits));

        File forumKeyFile = new File(FORUM_KEY_FILE);
        if (forumKeyFile.exists()) {
            String forumKey = null;
            // Read in a one-line file so we can do a for loop
            for (String line : new XReadLines(forumKeyFile))
                forumKey = line;
            updateForum(myWorkUnits, forumKey);
        }
    } catch (FileNotFoundException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.candlepin.CRLBenchmark.java

@Setup(Level.Trial)
public void buildMassiveCRL() throws Exception {
    X500Name issuer = new X500Name("CN=Test Issuer");

    KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");

    generator.initialize(2048);/*from   w w w.  jav a2s.c o m*/
    KeyPair keyPair = generator.generateKeyPair();

    Provider bc = new BouncyCastleProvider();
    ContentSigner signer = new JcaContentSignerBuilder("SHA256WithRSAEncryption").setProvider(bc)
            .build(keyPair.getPrivate());

    X509v2CRLBuilder crlBuilder = new X509v2CRLBuilder(issuer, new Date());

    crlBuilder.addExtension(X509Extension.authorityKeyIdentifier, false,
            new AuthorityKeyIdentifierStructure(keyPair.getPublic()));
    /* With a CRL number of 127, incrementing it should cause the number of bytes in the length
     * portion of the TLV to increase by one.*/
    crlBuilder.addExtension(X509Extension.cRLNumber, false, new CRLNumber(new BigInteger("127")));

    for (int i = 0; i < 2000000; i++) {
        crlBuilder.addCRLEntry(new BigInteger(String.valueOf(i)), new Date(), CRLReason.unspecified);
    }

    X509CRLHolder holder = crlBuilder.build(signer);
    X509CRL crl = new JcaX509CRLConverter().setProvider(bc).getCRL(holder);

    crlFile = File.createTempFile("crl", ".der");
    System.out.println("\nWrote test crl to " + crlFile.getAbsolutePath());
    FileUtils.writeByteArrayToFile(crlFile, crl.getEncoded());
}

From source file:org.candlepin.CRLWriteBenchmark.java

@Benchmark
@Fork(value = 1, jvmArgsAppend = { "-Xloggc:gc_in_memory_write.log", "-verbose:gc", "-XX:+PrintGCDetails",
        "-XX:+PrintGCTimeStamps" })
public void inMemory() {
    ASN1InputStream stream = null;
    try {//from  w w w.  ja va 2  s  .co m
        stream = new ASN1InputStream(new BufferedInputStream(new FileInputStream(crlFile)));
        DERObject o = stream.readObject();

        X509CRLHolder oldCrl = new X509CRLHolder(o.getDEREncoded());

        X509v2CRLBuilder crlBuilder = new X509v2CRLBuilder(issuer, new Date());
        crlBuilder.addCRL(oldCrl);

        crlBuilder.addCRLEntry(new BigInteger("25000000000"), new Date(), CRLReason.unspecified);

        X509CRLHolder holder = crlBuilder.build(signer);
        X509CRL crl = new JcaX509CRLConverter().setProvider(bc).getCRL(holder);

        File newCrlFile = File.createTempFile("new_crl", ".der");
        FileUtils.writeByteArrayToFile(newCrlFile, crl.getEncoded());
        System.out.println("\nWrote new crl to " + newCrlFile.getAbsolutePath());
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (stream != null) {
            try {
                stream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

From source file:org.candlepin.CRLWriteBenchmark.java

@Setup(Level.Trial)
public void buildMassiveCRL() throws Exception {
    issuer = new X500Name("CN=Test Issuer");

    KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");

    generator.initialize(2048);/*from ww  w.  j a  v  a  2s.  c o m*/
    KeyPair keyPair = generator.generateKeyPair();

    bc = new BouncyCastleProvider();
    signer = new JcaContentSignerBuilder("SHA256WithRSAEncryption").setProvider(bc).build(keyPair.getPrivate());

    X509v2CRLBuilder crlBuilder = new X509v2CRLBuilder(issuer, new Date());
    crlBuilder.addExtension(X509Extension.authorityKeyIdentifier, false,
            new AuthorityKeyIdentifierStructure(keyPair.getPublic()));
    /* With a CRL number of 127, incrementing it should cause the number of bytes in the length
     * portion of the TLV to increase by one.*/
    crlBuilder.addExtension(X509Extension.cRLNumber, false, new CRLNumber(new BigInteger("127")));

    for (int i = 0; i < 2000000; i++) {
        crlBuilder.addCRLEntry(new BigInteger(String.valueOf(i)), new Date(), CRLReason.unspecified);
    }

    X509CRLHolder holder = crlBuilder.build(signer);
    X509CRL crl = new JcaX509CRLConverter().setProvider(bc).getCRL(holder);

    crlFile = File.createTempFile("crl", ".der");
    System.out.println("\nWrote test crl to " + crlFile.getAbsolutePath());
    FileUtils.writeByteArrayToFile(crlFile, crl.getEncoded());
}

From source file:org.candlepin.util.X509CRLEntryStreamTest.java

@Test
public void testIterateOverEmptyCrl() throws Exception {
    X509v2CRLBuilder crlBuilder = new X509v2CRLBuilder(issuer, new Date());

    crlBuilder.addExtension(X509Extension.authorityKeyIdentifier, false,
            new AuthorityKeyIdentifierStructure(keyPair.getPublic()));
    crlBuilder.addExtension(X509Extension.cRLNumber, false, new CRLNumber(new BigInteger("127")));

    X509CRLHolder holder = crlBuilder.build(signer);

    File noUpdateTimeCrl = new File(folder.getRoot(), "test.crl");
    FileUtils.writeByteArrayToFile(noUpdateTimeCrl, holder.getEncoded());

    X509CRLEntryStream stream = new X509CRLEntryStream(noUpdateTimeCrl);
    try {/* ww w  .j  a v a 2  s  .  co m*/
        Set<BigInteger> streamedSerials = new HashSet<BigInteger>();
        while (stream.hasNext()) {
            streamedSerials.add(stream.next().getSerialNumber());
        }

        assertEquals(0, streamedSerials.size());
    } finally {
        stream.close();
    }
}

From source file:org.candlepin.util.X509CRLEntryStreamTest.java

@Test
public void testIterateOverEmptyCrlWithNoExtensions() throws Exception {
    X509v2CRLBuilder crlBuilder = new X509v2CRLBuilder(issuer, new Date());

    X509CRLHolder holder = crlBuilder.build(signer);

    File noUpdateTimeCrl = new File(folder.getRoot(), "test.crl");
    FileUtils.writeByteArrayToFile(noUpdateTimeCrl, holder.getEncoded());

    X509CRLEntryStream stream = new X509CRLEntryStream(noUpdateTimeCrl);

    thrown.expect(IllegalStateException.class);
    thrown.expectMessage(matchesPattern("v1.*"));

    try {/*w w w  . ja  v  a  2 s.com*/
        while (stream.hasNext()) {
            stream.next();
        }
    } finally {
        stream.close();
    }
}

From source file:org.candlepin.util.X509CRLEntryStreamTest.java

@Test
public void testCRLwithoutUpdateTime() throws Exception {
    X509v2CRLBuilder crlBuilder = new X509v2CRLBuilder(issuer, new Date());
    crlBuilder.addExtension(X509Extension.authorityKeyIdentifier, false,
            new AuthorityKeyIdentifierStructure(keyPair.getPublic()));
    crlBuilder.addExtension(X509Extension.cRLNumber, false, new CRLNumber(new BigInteger("127")));
    crlBuilder.addCRLEntry(new BigInteger("100"), new Date(), CRLReason.unspecified);

    X509CRLHolder holder = crlBuilder.build(signer);

    File noUpdateTimeCrl = new File(folder.getRoot(), "test.crl");
    FileUtils.writeByteArrayToFile(noUpdateTimeCrl, holder.getEncoded());

    X509CRLEntryStream stream = new X509CRLEntryStream(noUpdateTimeCrl);
    try {/*w  ww .j  a  v a2  s  . com*/
        Set<BigInteger> streamedSerials = new HashSet<BigInteger>();
        while (stream.hasNext()) {
            streamedSerials.add(stream.next().getSerialNumber());
        }

        assertEquals(1, streamedSerials.size());
        assertTrue(streamedSerials.contains(new BigInteger("100")));
    } finally {
        stream.close();
    }
}

From source file:org.candlepin.util.X509CRLStreamWriterTest.java

private File writeCRL(X509CRLHolder crl) throws Exception {
    File crlToChange = new File(folder.getRoot(), "test.crl");
    FileUtils.writeByteArrayToFile(crlToChange, crl.getEncoded());
    return crlToChange;
}

From source file:org.cloudifysource.esc.driver.provisioning.ElasticMachineProvisioningCloudifyAdapter.java

private void handleServiceCloudConfiguration() throws IOException {
    final byte[] serviceCloudConfigurationContents = this.config.getServiceCloudConfiguration();
    if (serviceCloudConfigurationContents != null) {
        logger.info("Found service cloud configuration - saving to file");
        final File tempZipFile = File.createTempFile("__CLOUD_DRIVER_SERVICE_CONFIGURATION_FILE", ".zip");
        FileUtils.writeByteArrayToFile(tempZipFile, serviceCloudConfigurationContents);
        logger.info("Wrote file: " + tempZipFile);

        final File tempServiceConfigurationDirectory = File
                .createTempFile("__CLOUD_DRIVER_SERVICE_CONFIGURATION_DIRECTORY", ".tmp");
        logger.info("Unzipping file to: " + tempServiceConfigurationDirectory);
        FileUtils.forceDelete(tempServiceConfigurationDirectory);
        tempServiceConfigurationDirectory.mkdirs();

        ZipUtils.unzip(tempZipFile, tempServiceConfigurationDirectory);

        final File[] childFiles = tempServiceConfigurationDirectory.listFiles();

        logger.info("Unzipped configuration contained top-level entries: " + Arrays.toString(childFiles));
        if (childFiles.length != 1) {
            throw new BeanConfigurationException("Received a service cloud configuration file, "
                    + "but root of zip file had more then one entry!");
        }//from  w  ww  .jav a2  s .com

        final File serviceCloudConfigurationFile = childFiles[0];

        if (this.cloudifyProvisioning instanceof CustomServiceDataAware) {
            logger.info(
                    "Setting service cloud configuration in cloud driver to: " + serviceCloudConfigurationFile);
            final CustomServiceDataAware custom = (CustomServiceDataAware) this.cloudifyProvisioning;
            custom.setCustomDataFile(serviceCloudConfigurationFile);
        } else {
            throw new BeanConfigurationException(
                    "Cloud driver configuration inclouded a service cloud configuration file,"
                            + " but the cloud driver " + this.cloudifyProvisioning.getClass().getName()
                            + " does not implement the " + CustomServiceDataAware.class.getName()
                            + " interface");
        }
    }
}

From source file:org.cloudifysource.quality.iTests.test.cli.cloudify.util.NewRestTestUtils.java

public static File getProcessingUnitsDumpFile(final String restUrl, final long fileSizeLimit,
        final String errMessageContain)
        throws IOException, RestClientException, WrongMessageException, FailedToCreateDumpException {

    // connect to the REST
    RestClient restClient = createAndConnect(restUrl);

    // get dump data using REST API
    GetPUDumpFileResponse response;/* w  w  w.ja va  2 s  . c  o m*/
    try {
        response = restClient.getPUDumpFile(fileSizeLimit);
        if (errMessageContain != null) {
            LogUtils.log("RestClientException expected [" + errMessageContain + "]");
            throw new WrongMessageException("", errMessageContain);
        }
        // write the result data to a temporary file.
        File file = File.createTempFile("dump", ".zip");
        FileUtils.writeByteArrayToFile(file, response.getDumpData());
        return file;
    } catch (RestClientException e) {
        String message = e.getMessageFormattedText();
        if (errMessageContain == null) {
            throw new FailedToCreateDumpException(message);
        } else {
            if (!message.contains(errMessageContain)) {
                throw new WrongMessageException(message, errMessageContain);
            }
            return null;
        }
    }
}