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.platform.APIClient.java

public void downloadDiff(File bundleFile, String currentTarVersion) {
    Request diffRequest = new Request.Builder()
            .url(String.format("%s/assets/bundles/%s/diff/%s", BASE_URL, BREAD_BUY, currentTarVersion)).get()
            .build();//ww w.ja  v a2  s .com
    Response diffResponse = sendRequest(diffRequest, false, 0);
    File patchFile = null;
    File tempFile = null;
    byte[] patchBytes = null;
    try {
        patchFile = new File(String.format("/%s/%s.diff", BUNDLES, "patch"));
        patchBytes = diffResponse.body().bytes();
        FileUtils.writeByteArrayToFile(patchFile, patchBytes);

        String compression = System.getProperty("jbsdiff.compressor", "tar");
        compression = compression.toLowerCase();
        tempFile = new File(String.format("/%s/%s.tar", BUNDLES, "temp"));
        FileUI.diff(bundleFile, tempFile, patchFile, compression);

        byte[] updatedBundleBytes = IOUtils.toByteArray(new FileInputStream(tempFile));
        FileUtils.writeByteArrayToFile(bundleFile, updatedBundleBytes);

    } catch (IOException | InvalidHeaderException | CompressorException | NullPointerException e) {
        e.printStackTrace();
    } finally {
        if (patchFile != null)
            patchFile.delete();
        if (tempFile != null)
            tempFile.delete();
    }
}

From source file:cz.cas.lib.proarc.common.fedora.RemoteStorageTest.java

@Test
public void testDatastreamEditorWriteReference_External() throws Exception {
    LocalStorage storage = new LocalStorage();
    LocalObject local = storage.create();
    local.setLabel(test.getMethodName());
    String dsID = "dsID";
    MediaType mime = MediaType.TEXT_PLAIN_TYPE;
    String label = "label";
    DatastreamProfile dsProfile = FoxmlUtils.externalProfile(dsID, mime, label);

    RemoteStorage fedora = new RemoteStorage(client);
    fedora.ingest(local, support.getTestUser());

    // prepare referenced contents
    byte[] data = "data".getBytes("UTF-8");
    File file = tmp.newFile();//from   w  w w  .j a  v  a 2s.  c o  m
    FileUtils.writeByteArrayToFile(file, data);

    RemoteObject remote = fedora.find(local.getPid());
    XmlStreamEditor reditor = remote.getEditor(dsProfile);
    assertNotNull(reditor);
    reditor.write(file.toURI(), reditor.getLastModified(), "add");

    // test read cached
    InputStream is = reditor.readStream();
    assertNotNull(is);
    ByteArrayOutputStream resultData = new ByteArrayOutputStream();
    FoxmlUtils.copy(is, resultData);
    is.close();
    assertArrayEquals(data, resultData.toByteArray());
    assertEquals(mime.toString(), reditor.getProfile().getDsMIME());
    assertEquals(ControlGroup.EXTERNAL.toExternal(), reditor.getProfile().getDsControlGroup());

    // test remote read
    remote.flush();
    remote = fedora.find(local.getPid());
    reditor = remote.getEditor(dsProfile);
    is = reditor.readStream();
    assertNotNull(is);
    resultData = new ByteArrayOutputStream();
    FoxmlUtils.copy(is, resultData);
    is.close();
    assertArrayEquals(data, resultData.toByteArray());
    assertEquals(mime.toString(), reditor.getProfile().getDsMIME());
    assertEquals(ControlGroup.EXTERNAL.toExternal(), reditor.getProfile().getDsControlGroup());

    // test update MIME + location
    MediaType mime2 = MediaType.APPLICATION_OCTET_STREAM_TYPE;
    byte[] data2 = "data2".getBytes("UTF-8");
    File file2 = tmp.newFile();
    FileUtils.writeByteArrayToFile(file2, data2);
    remote = fedora.find(local.getPid());
    reditor = remote.getEditor(dsProfile);
    DatastreamProfile dsProfile2 = FoxmlUtils.externalProfile(dsID, mime2, label);
    reditor.setProfile(dsProfile2);
    reditor.write(file2.toURI(), reditor.getLastModified(), "update");
    remote.flush();

    remote = fedora.find(local.getPid());
    reditor = remote.getEditor(dsProfile);
    is = reditor.readStream();
    assertNotNull(is);
    resultData = new ByteArrayOutputStream();
    FoxmlUtils.copy(is, resultData);
    is.close();
    assertArrayEquals(data2, resultData.toByteArray());
    assertEquals(mime2.toString(), reditor.getProfile().getDsMIME());
    assertEquals(ControlGroup.EXTERNAL.toExternal(), reditor.getProfile().getDsControlGroup());
}

From source file:net.link.util.common.KeyUtils.java

public static void extractCertificate(PrivateKeyEntry privateKeyEntry, File certificateFile) {

    Certificate certificate = privateKeyEntry.getCertificate();
    try {/*  w  w w .  j av a 2s .  co  m*/
        FileUtils.writeByteArrayToFile(certificateFile, certificate.getEncoded());
    } catch (CertificateEncodingException e) {
        throw new InternalInconsistencyException("error encoding certificate ", e);
    } catch (IOException e) {
        throw new InternalInconsistencyException("error writing out certificate ", e);
    }
}

From source file:com.seleniumtests.driver.CustomEventFiringWebDriver.java

public static void uploadFile(String fileName, String base64Content, DriverMode driverMode,
        SeleniumGridConnector gridConnector) throws IOException {

    if (driverMode == DriverMode.LOCAL) {
        byte[] byteArray = base64Content.getBytes();
        File tempFile = new File("tmp/" + fileName);
        byte[] decodeBuffer = Base64.decodeBase64(byteArray);
        FileUtils.writeByteArrayToFile(tempFile, decodeBuffer);

        try {/*  www  .  j  av a  2 s  . c o  m*/
            uploadFileUsingClipboard(tempFile);
        } catch (IllegalStateException e) {
            uploadFileUsingKeyboardTyping(tempFile);
        }
    } else if (driverMode == DriverMode.GRID && gridConnector != null) {
        gridConnector.uploadFileToBrowser(fileName, base64Content);
    } else {
        throw new ScenarioException("driver supports uploadFile only in local and grid mode");
    }
}

From source file:com.platform.APIClient.java

public byte[] writeBundleToFile(Response response, File bundleFile) {
    byte[] bodyBytes;
    FileOutputStream fileOutputStream = null;
    assert (response != null);
    try {//w w w.  java2 s.  c o m
        if (response == null) {
            Log.e(TAG, "writeBundleToFile: WARNING, response is null");
            return null;
        }
        bodyBytes = response.body().bytes();
        FileUtils.writeByteArrayToFile(bundleFile, bodyBytes);
        return bodyBytes;
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (fileOutputStream != null) {
                fileOutputStream.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return null;
}

From source file:com.frostwire.bittorrent.BTDownload.java

private void serializeResumeData(SaveResumeDataAlert alert) {
    try {/*  w ww  .  j  a va2  s.  co m*/
        if (th.isValid()) {
            String infoHash = th.infoHash().toString();
            File file = engine.resumeDataFile(infoHash);
            entry e = add_torrent_params.write_resume_data(alert.swig().getParams());
            e.dict().set(EXTRA_DATA_KEY, Entry.fromMap(extra).swig());
            FileUtils.writeByteArrayToFile(file, Vectors.byte_vector2bytes(e.bencode()));
        }
    } catch (Throwable e) {
        LOG.warn("Error saving resume data", e);
    }
}

From source file:com.platform.APIClient.java

public boolean tryExtractTar(File inputFile) {
    String extractFolderName = MainActivity.app.getFilesDir().getAbsolutePath() + bundlesFileName + "/"
            + extractedFolder;//  w  ww .  j  av a  2s. c  o  m
    boolean result = false;
    TarArchiveInputStream debInputStream = null;
    try {
        final InputStream is = new FileInputStream(inputFile);
        debInputStream = (TarArchiveInputStream) new ArchiveStreamFactory().createArchiveInputStream("tar", is);
        TarArchiveEntry entry = null;
        while ((entry = (TarArchiveEntry) debInputStream.getNextEntry()) != null) {

            final String outPutFileName = entry.getName().replace("./", "");
            final File outputFile = new File(extractFolderName, outPutFileName);
            if (!entry.isDirectory()) {
                FileUtils.writeByteArrayToFile(outputFile,
                        org.apache.commons.compress.utils.IOUtils.toByteArray(debInputStream));
            }
        }

        result = true;
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            if (debInputStream != null)
                debInputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return result;

}

From source file:cz.cas.lib.proarc.common.fedora.RemoteStorageTest.java

@Test
public void testDatastreamEditorRewriteControlGroup() throws Exception {
    // prepare referenced contents
    byte[] data1 = "data1".getBytes("UTF-8");
    File file1 = tmp.newFile();/* www  .  j  av  a 2 s .com*/
    FileUtils.writeByteArrayToFile(file1, data1);
    byte[] data2 = "data2".getBytes("UTF-8");
    File file2 = tmp.newFile();
    FileUtils.writeByteArrayToFile(file2, data2);

    LocalStorage storage = new LocalStorage();
    LocalObject local = storage.create();
    System.out.println(local.getPid());
    local.setLabel(test.getMethodName());
    String dsID = "dsID";
    String label = "label";
    MediaType mime1 = MediaType.APPLICATION_OCTET_STREAM_TYPE;
    DatastreamProfile dsProfile1 = FoxmlUtils.managedProfile(dsID, mime1, label);
    XmlStreamEditor leditor = local.getEditor(dsProfile1);
    assertNotNull(leditor);
    leditor.write(file1.toURI(), leditor.getLastModified(), null);
    local.flush();

    RemoteStorage fedora = new RemoteStorage(client);
    fedora.ingest(local, support.getTestUser());

    MediaType mime2 = MediaType.TEXT_PLAIN_TYPE;
    DatastreamProfile dsProfile2 = FoxmlUtils.externalProfile(dsID, mime2, label);
    RemoteObject remote = fedora.find(local.getPid());
    XmlStreamEditor reditor = remote.getEditor(dsProfile1);
    assertNotNull(reditor);
    reditor.setProfile(dsProfile2);
    reditor.write(file2.toURI(), reditor.getLastModified(), null);

    // test read cached
    InputStream is = reditor.readStream();
    assertNotNull(is);
    ByteArrayOutputStream resultData = new ByteArrayOutputStream();
    FoxmlUtils.copy(is, resultData);
    is.close();
    assertArrayEquals(data2, resultData.toByteArray());
    assertEquals(mime2.toString(), reditor.getProfile().getDsMIME());
    assertEquals(ControlGroup.EXTERNAL.toExternal(), reditor.getProfile().getDsControlGroup());

    // test remote read
    remote.flush();
    remote = fedora.find(local.getPid());
    reditor = remote.getEditor(dsProfile1);
    is = reditor.readStream();
    assertNotNull(is);
    resultData = new ByteArrayOutputStream();
    FoxmlUtils.copy(is, resultData);
    is.close();
    assertArrayEquals(data2, resultData.toByteArray());
    assertEquals(mime2.toString(), reditor.getProfile().getDsMIME());
    assertEquals(ControlGroup.EXTERNAL.toExternal(), reditor.getProfile().getDsControlGroup());
}

From source file:com.mhs.hboxmaintenanceserver.utils.Utils.java

/**
 * Blowfish encryption/*from  w w w . j ava 2s .com*/
 *
 * @param value
 * @return
 * @throws java.lang.Exception
 */
public static String encrypt(String value) throws Exception {
    // create a key generator based upon the Blowfish cipher
    KeyGenerator keygenerator = KeyGenerator.getInstance("Blowfish");

    File file = new File(DefaultConfig.SECRET_KEY);
    SecretKey secretkey;

    if (file.exists()) {
        // Load key from file
        secretkey = new SecretKeySpec(FileUtils.readFileToByteArray(file), "Blowfish");
    } else {
        // create a key
        secretkey = keygenerator.generateKey();
        FileUtils.writeByteArrayToFile(file, secretkey.getEncoded());
    }

    // create a cipher based upon Blowfish
    Cipher cipher = Cipher.getInstance("Blowfish");

    // initialise cipher to with secret key
    cipher.init(Cipher.ENCRYPT_MODE, secretkey);

    // encrypt message
    return bytesToHex(cipher.doFinal(value.getBytes()));
}

From source file:com.edduarte.protbox.core.registry.PReg.java

private PbxEntry addOnlyToPRegFromProt(File file, boolean conflicted) throws ProtboxException {
    try {/*from w  w  w .  j  a v  a  2s .  c o  m*/
        String realName = file.getName();
        if (conflicted && !file.isDirectory()) {
            realName = realNameToConflicted(realName);
            File newConflictFile = new File(file.getParentFile(), realName);
            SKIP_WATCHER_ENTRIES.add(newConflictFile.getAbsolutePath());
            SKIP_WATCHER_ENTRIES.add(file.getAbsolutePath());

            // get the data from the added file
            byte[] protFileData = FileUtils.readFileToByteArray(file);

            // move data to a new conflicted file and delete old file
            FileUtils.writeByteArrayToFile(newConflictFile, protFileData);
            Constants.delete(file);
        }
        String encodedName = convertRealNameToEncodedName(realName);

        String parentPath = file.getParentFile().getAbsolutePath();
        PbxFolder parent = null;
        if (!parentPath.equalsIgnoreCase(pair.getProtFolderPath()))
            parent = goToFolder(parentPath, FolderOption.PROT);

        if (parent == null)
            parent = root;

        return addFinal(file, parent, realName, encodedName, FolderOption.PROT);
    } catch (IOException | GeneralSecurityException ex) {
        throw new ProtboxException(ex);
    }
}