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:com.googlesource.gerrit.plugins.findowners.OwnersValidatorTest.java

private static void addFiles(Git git, Map<File, byte[]> files) throws IOException, GitAPIException {
    AddCommand ac = git.add();// ww  w.  ja  va  2s. c o  m
    for (File f : files.keySet()) {
        if (!f.exists()) {
            FileUtils.touch(f);
        }
        if (files.get(f) != null) {
            FileUtils.writeByteArrayToFile(f, files.get(f));
        }
        ac = ac.addFilepattern(generateFilePattern(f, git));
    }
    ac.call();
}

From source file:com.platform.middlewares.plugins.CameraPlugin.java

private static String writeToFile(Context context, Bitmap img) {
    String name = null;//from   ww  w.ja v  a 2s .c  o m
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    try {
        img.compress(Bitmap.CompressFormat.JPEG, 50, out);
        name = CryptoHelper.base58ofSha256(out.toByteArray());
        File storageDir = new File(context.getFilesDir().getAbsolutePath() + "/pictures/");
        File image = new File(storageDir, name + ".jpeg");
        FileUtils.writeByteArrayToFile(image, out.toByteArray());
        return name;
        // PNG is a lossless format, the compression factor (100) is ignored
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return null;
}

From source file:com.servicelibre.jxsl.scenario.XslScenario.java

private File saveXmlSourceFile(byte[] xmlBytes) {

    File xmlSourceFile = new File(this.getCurrentOutputDir(), getName() + "_" + XMLSOURCE_FILENAME);
    try {// ww  w  . ja v a  2s.c  o  m
        FileUtils.writeByteArrayToFile(xmlSourceFile, xmlBytes);
    } catch (IOException e) {
        logger.error("Error while saving XML source file.", e);
    }

    return xmlSourceFile;
}

From source file:com.igormaznitsa.zxpoly.MainForm.java

private RomData loadRom(final String romPath) throws IOException {
    if (romPath != null) {
        if (romPath.contains("://")) {
            try {
                final String cached = "loaded_"
                        + Integer.toHexString(romPath.hashCode()).toUpperCase(Locale.ENGLISH) + ".rom";
                final File cacheFolder = new File(AppOptions.getInstance().getAppConfigFolder(), "cache");
                final File cachedRom = new File(cacheFolder, cached);
                RomData result = null;/*ww  w .java  2s . c  om*/
                boolean load = true;
                if (cachedRom.isFile()) {
                    log.info("Load cached ROM downloaded from '" + romPath + "' : " + cachedRom);
                    result = new RomData(FileUtils.readFileToByteArray(cachedRom));
                    load = false;
                }

                if (load) {
                    log.info("Load ROM from external URL: " + romPath);
                    result = ROMLoader.getROMFrom(romPath);
                    if (cacheFolder.isDirectory() || cacheFolder.mkdirs()) {
                        FileUtils.writeByteArrayToFile(cachedRom, result.getAsArray());
                        log.info("Loaded ROM saved in cache as file : " + romPath);
                    }
                }
                return result;
            } catch (Exception ex) {
                log.log(Level.WARNING, "Can't load ROM from '" + romPath + "\'", ex);
            }
        } else {
            log.info("Load ROM from embedded resource '" + romPath + "'");
            return RomData.read(Utils.findResourceOrError("com/igormaznitsa/zxpoly/rom/" + romPath));
        }
    }

    final String testRom = "zxpolytest.rom";
    log.info("Load ROM from embedded resource '" + testRom + "'");
    return RomData.read(Utils.findResourceOrError("com/igormaznitsa/zxpoly/rom/" + testRom));
}

From source file:at.ac.tuwien.dsg.cloud.salsa.engine.smartdeployment.main.SmartDeploymentService.java

@POST
@Path("/CAMFTosca/enrich/CSAR/{serviceName}")
@Consumes(MediaType.APPLICATION_OCTET_STREAM)
@Produces(MediaType.TEXT_PLAIN)/*w  ww .  ja  v a 2 s.c om*/
public String enrich_CAMF_CSAR(byte[] fileBytes, @PathParam("serviceName") String serviceName) {
    SalsaConfiguration.getArtifactStorage();
    // retrieve the CSAR
    String csarTmp = SalsaConfiguration.getToscaTemplateStorage() + "/" + serviceName + ".csar";
    try {
        FileUtils.writeByteArrayToFile(new File(csarTmp), fileBytes);
        return enrich_CAMF_CSAR_Process(csarTmp, serviceName);
    } catch (IOException ex) {
        EngineLogger.logger.error("Fail to get byteArray of CSAR file to save to {}", csarTmp, ex);
        return null;
    }
}

From source file:net.sf.eclipsecs.core.config.configtypes.RemoteConfigurationType.java

private void writeToCacheFile(ICheckConfiguration checkConfig, byte[] configFileBytes, byte[] bundleBytes) {

    String cacheFileLocation = checkConfig.getAdditionalData().get(KEY_CACHE_FILE_LOCATION);

    IPath cacheFilePath = CheckstylePlugin.getDefault().getStateLocation();
    cacheFilePath = cacheFilePath.append(cacheFileLocation);
    File cacheFile = cacheFilePath.toFile();

    try {/*from www. jav  a 2 s  .  co m*/
        FileUtils.writeByteArrayToFile(cacheFile, configFileBytes);
    } catch (IOException e) {
        CheckstyleLog.log(e, NLS.bind(Messages.RemoteConfigurationType_msgRemoteCachingFailed,
                checkConfig.getName(), checkConfig.getLocation()));
    }

    if (bundleBytes != null) {

        String propsCacheFileLocation = checkConfig.getAdditionalData().get(KEY_CACHE_PROPS_FILE_LOCATION);

        IPath propsCacheFilePath = CheckstylePlugin.getDefault().getStateLocation();
        propsCacheFilePath = propsCacheFilePath.append(propsCacheFileLocation);
        File propsCacheFile = propsCacheFilePath.toFile();

        try {
            FileUtils.writeByteArrayToFile(propsCacheFile, bundleBytes);
        } catch (IOException e) {
            // ignore this since there simply might be no properties file
        }
    }
}

From source file:jenkins.scm.impl.mock.MockSCMController.java

public synchronized String checkout(File workspace, String repository, String identifier) throws IOException {
    State state = resolve(repository, identifier);

    for (Map.Entry<String, byte[]> entry : state.files.entrySet()) {
        FileUtils.writeByteArrayToFile(new File(workspace, entry.getKey()), entry.getValue());
    }/*from  www.ja  v  a2 s.  c o m*/
    return state.getHash();
}

From source file:com.xpn.xwiki.plugin.packaging.ImportTest.java

/**
 * Test the regular document import when the XAR is tagged as extension.
 * //from   www .  j a va 2s  .  com
 * @throws Exception
 */
public void testImportExtension() throws Exception {
    ExtensionId extensionId = new ExtensionId("test", "1.0");

    XWikiDocument doc1 = new XWikiDocument(new DocumentReference("Test", "Test", "DocImport"));
    doc1.setDefaultLanguage("en");

    byte[] zipFile = this.createZipFile(new XWikiDocument[] { doc1 }, new String[] { "ISO-8859-1" },
            extensionId);

    // Store the extension in the local repository
    DefaultLocalExtension localExtension = new DefaultLocalExtension(null, extensionId, "xar");
    File file = File.createTempFile("temp", ".xar");
    FileUtils.writeByteArrayToFile(file, zipFile);
    localExtension.setFile(file);
    LocalExtensionRepository localeRepository = getComponentManager()
            .getInstance(LocalExtensionRepository.class);
    localeRepository.storeExtension(localExtension);

    // Listen to extension installed event
    Mock extensionListener = mock(EventListener.class);
    extensionListener.stubs().method("getEvents")
            .will(returnValue(Arrays.asList(new ExtensionInstalledEvent())));
    extensionListener.stubs().method("getName").will(returnValue("extension installed listener"));
    extensionListener.expects(once()).method("onEvent");
    ObservationManager observationManager = getComponentManager().getInstance(ObservationManager.class);
    observationManager.addListener((EventListener) extensionListener.proxy());

    // make sure no data is in the packager from the other tests run
    this.pack = new Package();
    // import and install this document
    this.pack.Import(zipFile, getContext());
    this.pack.install(getContext());

    // check if it is there
    XWikiDocument foundDocument = this.xwiki.getDocument(new DocumentReference("Test", "Test", "DocImport"),
            getContext());
    assertFalse(foundDocument.isNew());

    XWikiDocument nonExistingDocument = this.xwiki
            .getDocument(new DocumentReference("Test", "Test", "DocImportNonexisting"), getContext());
    assertTrue(nonExistingDocument.isNew());

    XWikiDocument foundTranslationDocument = foundDocument.getTranslatedDocument("fr", getContext());
    assertSame(foundDocument, foundTranslationDocument);

    XWikiDocument doc1Translation = new XWikiDocument(new DocumentReference("Test", "Test", "DocImport"));
    doc1Translation.setLanguage("fr");
    doc1Translation.setDefaultLanguage("en");
    this.xwiki.saveDocument(doc1Translation, getContext());
    foundTranslationDocument = foundDocument.getTranslatedDocument("fr", getContext());
    assertNotSame(foundDocument, foundTranslationDocument);

    // Check that the extension has been registered
    InstalledExtensionRepository installedExtensionRepository = getComponentManager()
            .getInstance(InstalledExtensionRepository.class);
    assertNotNull(installedExtensionRepository.getInstalledExtension(extensionId));
    assertNotNull(installedExtensionRepository.getInstalledExtension(extensionId.getId(),
            "wiki:" + getContext().getWikiId()));
}

From source file:com.redhat.red.offliner.ftest.SinglePlaintextDownloadOfTarballFTest.java

/**
 * In general, we should only have one test method per functional test. This allows for the best parallelism when we
 * execute the tests, especially if the setup takes some time.
 *
 * @throws Exception In case anything (anything at all) goes wrong!
 *///from  w w w  . j  ava  2s  .co  m
@Test
public void run() throws Exception {
    // Generate some test content
    String path = contentGenerator.newArtifactPath("tar.gz");
    Map<String, byte[]> entries = new HashMap<>();
    entries.put(contentGenerator.newArtifactPath("jar"), contentGenerator.newBinaryContent(2400));
    entries.put(contentGenerator.newArtifactPath("jar"), contentGenerator.newBinaryContent(2400));

    final File tgz = makeTarball(entries);

    System.out.println("tar content array has length: " + tgz.length());

    // We only need one repo server.
    ExpectationServer server = new ExpectationServer();
    server.start();

    // Register the generated content by writing it to the path within the repo server's dir structure.
    // This way when the path is requested it can be downloaded instead of returning a 404.
    server.expect("GET", server.formatUrl(path), (req, resp) -> {
        //            Content-Length: 47175
        //            Content-Type: application/x-gzip
        resp.setHeader("Content-Encoding", "gzip");
        resp.setHeader("Content-Type", "application/x-gzip");

        byte[] raw = FileUtils.readFileToByteArray(tgz);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        GzipCompressorOutputStream gzout = new GzipCompressorOutputStream(baos);
        gzout.write(raw);
        gzout.finish();

        byte[] content = baos.toByteArray();

        resp.setHeader("Content-Length", Long.toString(content.length));
        OutputStream respStream = resp.getOutputStream();
        respStream.write(content);
        respStream.flush();

        System.out.println("Wrote content with length: " + content.length);
    });

    byte[] content = FileUtils.readFileToByteArray(tgz);

    server.expect("GET", server.formatUrl(path + Main.SHA_SUFFIX), 200, sha1Hex(content));
    server.expect("GET", server.formatUrl(path + Main.MD5_SUFFIX), 200, md5Hex(content));

    // Write the plaintext file we'll use as input.
    File plaintextList = temporaryFolder.newFile("artifact-list." + getClass().getSimpleName() + ".txt");
    String pathWithChecksum = contentGenerator.newPlaintextEntryWithChecksum(path, content);
    FileUtils.write(plaintextList, pathWithChecksum);

    Options opts = new Options();
    opts.setBaseUrls(Collections.singletonList(server.getBaseUri()));

    // Capture the downloads here so we can verify the content.
    File downloads = temporaryFolder.newFolder();

    opts.setDownloads(downloads);
    opts.setLocations(Collections.singletonList(plaintextList.getAbsolutePath()));
    opts.setConnections(1);

    // run `new Main(opts).run()` and return the Main instance so we can query it for errors, etc.
    Main finishedMain = run(opts);
    ConcurrentHashMap<String, Throwable> errors = finishedMain.getErrors();
    System.out.printf("ERRORS:\n\n%s\n\n\n",
            StringUtils.join(errors.keySet().stream()
                    .map(k -> "ERROR: " + k + ": " + errors.get(k).getMessage() + "\n  "
                            + StringUtils.join(errors.get(k).getStackTrace(), "\n  "))
                    .collect(Collectors.toList()), "\n\n"));

    File downloaded = new File(downloads, path);
    assertThat("File: " + path + " doesn't seem to have been downloaded!", downloaded.exists(), equalTo(true));
    //        assertThat( "Downloaded file: " + path + " contains the wrong content!",
    //                    FileUtils.readFileToByteArray( downloaded ), equalTo( content ) );

    File tarball = new File(downloads, path);
    System.out.println("Length of downloaded file: " + tarball.length());

    File tmp = new File("/tmp/download.tar.gz");
    File tmp2 = new File("/tmp/content.tar.gz");
    FileUtils.writeByteArrayToFile(tmp2, content);
    FileUtils.copyFile(tarball, tmp);

    try (TarArchiveInputStream tarIn = new TarArchiveInputStream(
            new GzipCompressorInputStream(new FileInputStream(tarball)))) {
        TarArchiveEntry entry = null;
        while ((entry = tarIn.getNextTarEntry()) != null) {
            byte[] entryData = new byte[(int) entry.getSize()];
            int read = tarIn.read(entryData, 0, entryData.length);
            assertThat("Not enough bytes read for: " + entry.getName(), read, equalTo((int) entry.getSize()));
            assertThat(entry.getName() + ": data doesn't match input",
                    Arrays.equals(entries.get(entry.getName()), entryData), equalTo(true));
        }
    }

    assertThat("Wrong number of downloads logged. Should have been 3 including checksums.",
            finishedMain.getDownloaded(), equalTo(3));
    assertThat("Errors should be empty!", errors.isEmpty(), equalTo(true));

}

From source file:net.rptools.lib.FileUtil.java

/**
 * Writes given bytes to file indicated by <code>file</code>. This method will overwrite any existing file at that
 * location, and will create any sub-directories required.
 * /*from   w w  w . j av  a2 s  .c  om*/
 * @deprecated use {@link FileUtils#writeByteArrayToFile(File, byte[])} instead.
 * @param file
 * @param data
 * @throws IOException
 */
@Deprecated
public static void writeBytes(File file, byte[] data) throws IOException {
    FileUtils.writeByteArrayToFile(file, data);
}