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

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

Introduction

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

Prototype

public static byte[] readFileToByteArray(File file) throws IOException 

Source Link

Document

Reads the contents of a file into a byte array.

Usage

From source file:ezbake.deployer.utilities.PackageDeployer.java

/**
 * Builds a deployment artifact//  w w  w .ja v  a 2 s. co m
 *
 * @param artifactMetadata      The metadata from the manifest
 * @param manifestFile          The yml file 
 * @param archive               The file containing the artifact already in the form of tar.gz that does not contain manifest file
 * @param applicationSecurityId The application's security id, or null to use the value in the manifest
 * @return A serialized tar file of everything to be deployed
 * @throws IOException          If the files cannot be read
 * @throws DeploymentException  If the tar file cannot be created
 */
public static ByteBuffer buildArtifact(ArtifactManifest artifactMetadata, File manifestFile, File archive,
        String applicationSecurityId) throws IOException, DeploymentException {
    List<ArtifactDataEntry> injectFiles = new ArrayList<>();

    //add the yml file
    injectFiles.add(new ArtifactDataEntry(new TarArchiveEntry(getFqAppId(artifactMetadata) + "-manifest.yml"),
            FileUtils.readFileToByteArray(manifestFile)));

    if (applicationSecurityId != null) {
        // Assumption: override manifest's application security id with one from registration form
        // given this is passed to constructor and not based on actual application from manifest
        // only one sec id will be set for n number of manifest as only one manifest is currently supported
        // per deployment
        artifactMetadata.applicationInfo.setSecurityId(applicationSecurityId);
    }

    ByteArrayOutputStream output = new ByteArrayOutputStream();

    Utilities.appendFilesInTarArchive(output, FileUtils.readFileToByteArray(archive), injectFiles);
    return ByteBuffer.wrap(output.toByteArray());
}

From source file:com.ruesga.rview.misc.CacheHelper.java

public static byte[] readAccountDiffCacheFile(Context context, Account account, String name)
        throws IOException {
    return FileUtils.readFileToByteArray(new File(getAccountDiffCacheDir(context, account), name));
}

From source file:com.falkonry.TestAddDataStream.java

/**
 * Should add wide data to datastream in stream JSON format
 * @throws Exception/*from   w ww .j  ava2 s .  co  m*/
 */
@Test
public void addWideDataJsonStream() throws Exception {

    Datastream ds = new Datastream();
    ds.setName("Test-DS2-" + Math.random());
    TimeObject time = new TimeObject();
    time.setIdentifier("time");
    time.setFormat("millis");
    time.setZone("GMT");

    Datasource dataSource = new Datasource();
    dataSource.setType("STANDALONE");

    List<Input> inputList = new ArrayList<Input>();

    Input input1 = new Input();
    input1.setName("signal1");
    EventType eventType1 = new EventType();
    eventType1.setType("Samples");
    input1.setEventType(eventType1);
    ValueType valueType1 = new ValueType();
    valueType1.setType("Numeric");
    input1.setValueType(valueType1);
    inputList.add(input1);

    Input input2 = new Input();
    input2.setName("signal2");
    EventType eventType2 = new EventType();
    eventType2.setType("Samples");
    input2.setEventType(eventType2);
    ValueType valueType2 = new ValueType();
    valueType2.setType("Numeric");
    input2.setValueType(valueType2);
    inputList.add(input2);

    Input input3 = new Input();
    input3.setName("signal3");
    EventType eventType3 = new EventType();
    eventType3.setType("Samples");
    input3.setEventType(eventType3);
    ValueType valueType3 = new ValueType();
    valueType3.setType("Numeric");
    input3.setValueType(valueType3);
    inputList.add(input3);

    Input input4 = new Input();
    input4.setName("signal4");
    EventType eventType4 = new EventType();
    eventType4.setType("Samples");
    input4.setEventType(eventType4);
    ValueType valueType4 = new ValueType();
    valueType4.setType("Numeric");
    input4.setValueType(valueType4);
    inputList.add(input4);

    Input input5 = new Input();
    input5.setName("signal5");
    EventType eventType5 = new EventType();
    eventType5.setType("Samples");
    input5.setEventType(eventType5);
    ValueType valueType5 = new ValueType();
    valueType5.setType("Numeric");
    input5.setValueType(valueType5);
    inputList.add(input5);

    ds.setInputList(inputList);

    Field field = new Field();
    field.setTime(time);
    field.setEntityIdentifier("thing");

    ds.setDatasource(dataSource);
    ds.setField(field);

    Datastream datastream = falkonry.createDatastream(ds);
    datastreams.add(datastream);

    Map<String, String> options = new HashMap<String, String>();

    File file = new File("res/data_wide.json");
    ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(FileUtils.readFileToByteArray(file));

    InputStatus inputStatus = falkonry.addInputStream(datastream.getId(), byteArrayInputStream, options);
    Assert.assertEquals(inputStatus.getAction(), "ADD_DATA_DATASTREAM");
    Assert.assertEquals(inputStatus.getStatus(), "PENDING");

    Datastream datastream1 = falkonry.getDatastream(datastream.getId());
    Assert.assertEquals(datastream1.getId(), datastream.getId());
    Assert.assertEquals(datastream1.getName(), datastream.getName());
    Assert.assertEquals(datastream1.getInputList().size(), datastream.getInputList().size());
}

From source file:com.intuit.tank.harness.functions.JexlIOFunctions.java

/**
 * /*from   www .  j  a  va  2s . com*/
 * @param fileName
 * @return
 */
public String getFileData(String fileName) {
    byte[] ret = fileDataMap.get(fileName);
    if (ret == null) {
        String datafileDir = "src/test/resources";
        try {
            datafileDir = APITestHarness.getInstance().getTankConfig().getAgentConfig()
                    .getAgentDataFileStorageDir();
        } catch (Exception e) {
            LOG.warn(LogUtil.getLogMessage("Cannot read config. Using datafileDir of " + datafileDir,
                    LogEventType.System));
        }
        File f = new File(datafileDir, fileName);
        try {
            if (f.exists()) {
                ret = FileUtils.readFileToByteArray(f);
            }
        } catch (Exception e) {
            LOG.warn(LogUtil.getLogMessage("Cannot read file " + f.getAbsolutePath() + ": " + e,
                    LogEventType.System));
        }
        if (ret == null) {
            ret = new byte[0];
        }
        fileDataMap.put(fileName, ret);
    }

    return new String(ret);
}

From source file:gov.nih.nci.firebird.service.file.FileServiceBean.java

@Override
public FirebirdFile createFile(File file, FileMetadata fileMetadata) throws IOException {
    return createFile(FileUtils.readFileToByteArray(file), fileMetadata);
}

From source file:com.amazon.aws.samplecode.travellog.util.DataExtractor.java

public void run() {
    try {//from w w  w .  j  av  a 2 s .  c o m
        //Create temporary directory
        File tmpDir = File.createTempFile("travellog", "");
        tmpDir.delete(); //Wipe out temporary file to replace with a directory
        tmpDir.mkdirs();

        logger.log(Level.INFO, "Extract temp dir: " + tmpDir);

        //Store journal to props file
        Journal journal = dao.getJournal();
        Properties journalProps = buildProps(journal);
        File journalFile = new File(tmpDir, "journal");
        journalProps.store(new FileOutputStream(journalFile), "");

        //Iterate through entries and grab related photos
        List<Entry> entries = dao.getEntries(journal);
        int entryIndex = 1;
        int imageFileIndex = 1;
        for (Entry entry : entries) {
            Properties entryProps = buildProps(entry);
            File entryFile = new File(tmpDir, "entry." + (entryIndex++));
            entryProps.store(new FileOutputStream(entryFile), "");

            List<Photo> photos = dao.getPhotos(entry);
            int photoIndex = 1;
            for (Photo photo : photos) {
                Properties photoProps = buildProps(photo);

                InputStream photoData = S3PhotoUtil.loadOriginalPhoto(photo);
                String imageFileName = "imgdata." + (imageFileIndex++);
                File imageFile = new File(tmpDir, imageFileName);

                FileOutputStream outputStream = new FileOutputStream(imageFile);
                IOUtils.copy(photoData, outputStream);
                photoProps.setProperty("file", imageFileName);
                outputStream.close();
                photoData.close();

                File photoFile = new File(tmpDir, "photo." + (entryIndex - 1) + "." + (photoIndex++));
                photoProps.store(new FileOutputStream(photoFile), "");
            }

            List<Comment> comments = dao.getComments(entry);
            int commentIndex = 1;
            for (Comment comment : comments) {
                Properties commentProps = buildProps(comment);
                File commentFile = new File(tmpDir, "comment." + (entryIndex - 1) + "." + commentIndex++);
                commentProps.store(new FileOutputStream(commentFile), "");
            }
        }

        //Bundle up the folder as a zip
        final File zipOut;

        //If we have an output path store locally
        if (outputPath != null) {
            zipOut = new File(outputPath);
        } else {
            //storing to S3
            zipOut = File.createTempFile("export", ".zip");
        }

        zipOut.getParentFile().mkdirs(); //make sure directory structure is in place
        ZipArchiveOutputStream zaos = new ZipArchiveOutputStream(zipOut);

        //Create the zip file
        File[] files = tmpDir.listFiles();
        for (File file : files) {
            ZipArchiveEntry archiveEntry = new ZipArchiveEntry(file.getName());
            byte[] fileData = FileUtils.readFileToByteArray(file);
            archiveEntry.setSize(fileData.length);
            zaos.putArchiveEntry(archiveEntry);
            zaos.write(fileData);
            zaos.flush();
            zaos.closeArchiveEntry();
        }
        zaos.close();

        //If outputpath
        if (outputPath == null) {
            TravelLogStorageObject obj = new TravelLogStorageObject();
            obj.setBucketName(bucketName);
            obj.setStoragePath(storagePath);
            obj.setData(FileUtils.readFileToByteArray(zipOut));
            obj.setMimeType("application/zip");

            S3StorageManager mgr = new S3StorageManager();
            mgr.store(obj, false, null); //Store with full redundancy and default permissions
        }

    } catch (Exception e) {
        logger.log(Level.SEVERE, e.getMessage(), e);
    }

}

From source file:de.undercouch.gradle.tasks.download.DownloadTaskPluginTest.java

/**
 * Tests if a single file can be downloaded from a URL
 * @throws Exception if anything goes wrong
 *///from  w ww  .  j  a  v  a  2 s .com
@Test
public void downloadSingleURL() throws Exception {
    Download t = makeProjectAndTask();
    t.src(new URL(makeSrc(TEST_FILE_NAME)));
    File dst = folder.newFile();
    t.dest(dst);
    t.execute();

    byte[] dstContents = FileUtils.readFileToByteArray(dst);
    assertArrayEquals(contents, dstContents);
}

From source file:de.undercouch.gradle.tasks.download.DownloadTest.java

/**
 * Tests lazy evaluation of 'src' and 'dest' properties
 * @throws Exception if anything goes wrong
 *///from   w w  w.  j  a  va2 s.  c  om
@Test
public void lazySrcAndDest() throws Exception {
    final boolean[] srcCalled = new boolean[] { false };
    final boolean[] dstCalled = new boolean[] { false };

    final File dst = folder.newFile();

    Download t = makeProjectAndTask();
    t.src(new Closure<Object>(this, this) {
        private static final long serialVersionUID = -4463658999363261400L;

        @SuppressWarnings("unused")
        public Object doCall() {
            srcCalled[0] = true;
            return makeSrc(TEST_FILE_NAME);
        }
    });

    t.dest(new Closure<Object>(this, this) {
        private static final long serialVersionUID = 932174549047352157L;

        @SuppressWarnings("unused")
        public Object doCall() {
            dstCalled[0] = true;
            return dst;
        }
    });

    t.execute();

    assertTrue(srcCalled[0]);
    assertTrue(dstCalled[0]);

    byte[] dstContents = FileUtils.readFileToByteArray(dst);
    assertArrayEquals(contents, dstContents);
}

From source file:algorithm.F5Steganography.java

@Override
public List<RestoredFile> restore(File carrier) throws IOException {
    List<RestoredFile> restoredFiles = new ArrayList<RestoredFile>();
    File tmpPayload = new File("tmp");
    tmpPayload.delete(); // F5 won't override existing files!
    restore("" + tmpPayload.toPath(), "" + carrier.toPath());
    RestoredFile copiedCarrier = new RestoredFile(RESTORED_DIRECTORY + carrier.getName());
    copiedCarrier.wasCarrier = true;/*w  w w.ja v a2 s.  c o m*/
    copiedCarrier.checksumValid = false;
    copiedCarrier.restorationNote = "The carrier can't be restored with this steganography algorithm. It still contains the embedded payload file(s).";
    FileUtils.copyFile(carrier, copiedCarrier);
    byte[] payloadSegmentBytes = FileUtils.readFileToByteArray(tmpPayload);
    PayloadSegment payloadSegment = PayloadSegment.getPayloadSegment(payloadSegmentBytes);
    RestoredFile restoredPayload = new RestoredFile(RESTORED_DIRECTORY + payloadSegment.getPayloadName());
    FileUtils.writeByteArrayToFile(restoredPayload, payloadSegment.getPayloadBytes());
    restoredPayload.validateChecksum(payloadSegment.getPayloadChecksum());
    restoredPayload.restorationNote = "Payload can be restored correctly.";
    restoredPayload.wasPayload = true;
    restoredPayload.originalFilePath = payloadSegment.getPayloadPath();
    copiedCarrier.originalFilePath = payloadSegment.getCarrierPath();
    restoredFiles.add(restoredPayload);
    FileUtils.forceDelete(tmpPayload);
    restoredFiles.add(copiedCarrier);// carrier can not be restored
    for (RestoredFile file : restoredFiles) {
        file.algorithm = this;
        for (RestoredFile relatedFile : restoredFiles) {
            if (file != relatedFile) {
                file.relatedFiles.add(relatedFile);
            }
        }
    }
    return restoredFiles;
}

From source file:com.zacwolf.commons.crypto.Crypter_Blowfish.java

/**
 * @param keyfile//from  w  ww .j  a  v  a2 s  . c o m
 * @param cipher
 * @param salter
 * @throws IOException
 */
public Crypter_Blowfish(final File keyfile, final String cipher, final SecureRandom salter) throws IOException {
    this(FileUtils.readFileToByteArray(keyfile), cipher, salter);
}