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:de.undercouch.gradle.tasks.download.FunctionalDownloadTest.java

/**
 * Test if a single file can be downloaded successfully
 * @throws Exception if anything went wrong
 *///from   w w w.j  av  a  2s .  c om
@Test
public void downloadSingleFile() throws Exception {
    assertTaskSuccess(download(new Parameters(singleSrc, dest, true, false)));
    assertTrue(destFile.isFile());
    assertArrayEquals(contents, FileUtils.readFileToByteArray(destFile));
}

From source file:apiserver.services.cache.model.Document.java

public void setFile(Object file) throws IOException {
    if (file instanceof File) {
        if (!((File) file).exists() || ((File) file).isDirectory()) {
            throw new IOException("Invalid File Reference");
        }/*from w ww  .j a v a  2 s .c o  m*/

        fileName = ((File) file).getName();
        this.file = file;
        this.setFileName(fileName);
        this.contentType = MimeType.getMimeType(fileName);

        byte[] bytes = FileUtils.readFileToByteArray(((File) file));
        this.setFileBytes(bytes);
        this.setSize(new Integer(bytes.length).longValue());
    } else if (file instanceof MultipartFile) {
        fileName = ((MultipartFile) file).getOriginalFilename();
        this.setContentType(MimeType.getMimeType(((MultipartFile) file).getContentType()));
        this.setFileName(((MultipartFile) file).getOriginalFilename());
        this.setFileBytes(((MultipartFile) file).getBytes());
        this.setSize(new Integer(this.getFileBytes().length).longValue());
    } else if (file instanceof BufferedImage) {
        if (fileName == null) {
            fileName = UUID.randomUUID().toString();
        }

        // Convert buffered reader to byte array
        String _mime = this.getContentType().name();

        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        ImageIO.write((BufferedImage) file, _mime, byteArrayOutputStream);
        byteArrayOutputStream.flush();
        byte[] imageBytes = byteArrayOutputStream.toByteArray();
        byteArrayOutputStream.close();
        this.setFileBytes(imageBytes);
    }
}

From source file:info.debatty.sparkpackages.maven.plugin.PublishMojo.java

@Override
public final void realexe() throws MojoFailureException {

    File zip_file = new File(getZipPath());
    byte[] zip_base64 = null;
    try {//from  w ww . ja  v  a 2 s  .co  m
        zip_base64 = Base64.encodeBase64(FileUtils.readFileToByteArray(zip_file));

    } catch (IOException ex) {
        throw new MojoFailureException("Error!", ex);
    }

    HttpEntity request = MultipartEntityBuilder.create()
            .addBinaryBody("artifact_zip", zip_base64, ContentType.APPLICATION_OCTET_STREAM, "artifact_zip")
            .addTextBody("version", getVersion()).addTextBody("license_id", getLicenseId())
            .addTextBody("git_commit_sha1", getGitCommit())
            .addTextBody("name", getOrganization() + "/" + getRepo()).build();

    HttpPost post = new HttpPost(getSparkpackagesUrl());
    post.setEntity(request);

    post.setHeader("Authorization", getAuthorizationHeader());

    getLog().info("Executing request " + post.getRequestLine());

    // .setProxy(new HttpHost("127.0.0.1", 8888))
    HttpClient httpclient = HttpClientBuilder.create().build();
    HttpResponse response = null;
    try {
        response = httpclient.execute(post);
    } catch (IOException ex) {
        throw new MojoFailureException("Failed to perform HTTP request", ex);
    }
    getLog().info("Server responded " + response.getStatusLine());

    HttpEntity response_content = response.getEntity();
    if (response_content == null) {
        throw new MojoFailureException("Server responded with an empty response");
    }

    StringBuilder sb = new StringBuilder();
    String line;
    BufferedReader br;
    try {
        br = new BufferedReader(new InputStreamReader(response_content.getContent()));

        while ((line = br.readLine()) != null) {
            sb.append(line);
        }
    } catch (IOException | UnsupportedOperationException ex) {
        throw new MojoFailureException("Could not read response...", ex);
    }
    System.out.println(sb.toString());

    try {
        System.out.println(EntityUtils.toString(response_content));
    } catch (IOException | ParseException ex) {

    }
}

From source file:com.cloudant.sync.datastore.BasicDBBodyTest.java

@Test
public void asMap_differentNumberTypes_jacksonPicksNaturalMapping() throws IOException {
    byte[] d = FileUtils.readFileToByteArray(new File("fixture/basic_bdbody_test_as_map.json"));
    DocumentBody body = new BasicDocumentBody(d);
    Assert.assertEquals("-101", body.asMap().get("StringValue"));

    Map<String, Object> m = body.asMap();

    Assert.assertTrue(m.get("LongValue") instanceof Long);
    Assert.assertTrue(m.get("LongValue").equals(2147483648l)); // Integer.MAX_VALUE + 1

    Assert.assertTrue(m.get("IntegerValue") instanceof Integer);
    Assert.assertTrue(m.get("IntegerValue").equals(2147483647)); // Integer.MAX_VALUE
}

From source file:net.nicholaswilliams.java.licensing.encryption.FilePrivateKeyDataProvider.java

/**
 * This method returns the data from the file containing the encrypted
 * private key from the public/private key pair. The contract for this
 * method can be fulfilled by storing the data in a byte array literal
 * in the source code itself.<br/>
 * <br/>/*from  www.j av a2 s.  c  om*/
 * It is <em>imperative</em> that you obfuscate the bytecode for the
 * implementation of this class. It is also imperative that the byte
 * array exist only for the life of this method (i.e., DO NOT store it as
 * an instance or class field).
 *
 * @return the encrypted file contents from the private key file.
 * @throws net.nicholaswilliams.java.licensing.exception.KeyNotFoundException if the key data could not be retrieved; an acceptable message or chained cause must be provided.
 */
@Override
public byte[] getEncryptedPrivateKeyData() throws KeyNotFoundException {
    try {
        return FileUtils.readFileToByteArray(this.privateKeyFile);
    } catch (FileNotFoundException e) {
        throw new KeyNotFoundException(
                "The private key file [" + this.privateKeyFile.getPath() + "] does not exist.");
    } catch (IOException e) {
        throw new KeyNotFoundException(
                "Could not read from the private key file [" + this.privateKeyFile.getPath() + "].", e);
    }
}

From source file:com.mavict.plugin.ueditor.DefaultMultipartFile.java

public byte[] getBytes() throws IOException {
    return fileExists() ? FileUtils.readFileToByteArray(this.dfosFile) : new byte[0];
}

From source file:gov.nih.nci.caintegrator.application.study.deployment.AffymetrixCopyNumberMappingFileHandlerTest.java

/**
 * Sets up the test./*from   w w  w . j  a  v  a2s .  c  o m*/
 * @throws Exception on error
 */
@Before
public void setUp() throws Exception {
    caArrayFacade = mock(CaArrayFacade.class);
    when(caArrayFacade.retrieveFile(any(GenomicDataSourceConfiguration.class), anyString()))
            .thenReturn(FileUtils.readFileToByteArray(TestDataFiles.HIND_COPY_NUMBER_CHP_FILE));
}

From source file:ezbake.deployer.impl.LocalFileArtifactWriter.java

@Override
public DeploymentArtifact readArtifact(DeploymentMetadata metadata) throws DeploymentException {
    File artifactFile = new File(buildFilePath(metadata));
    DeploymentArtifact artifact = new DeploymentArtifact();
    if (artifactFile.exists()) {
        TDeserializer deserializer = new TDeserializer();
        try {//from   www . j  a va  2 s .c  o  m
            byte[] fileBytes = FileUtils.readFileToByteArray(artifactFile);
            deserializer.deserialize(artifact, fileBytes);
        } catch (Exception ex) {
            log.error("Failed reading artifact", ex);
            throw new DeploymentException("Failed to read artifact file from disk." + ex.getMessage());
        }
    } else {
        log.warn("The artifact {} {} could not be loaded from disk.  Only metadata is available",
                ArtifactHelpers.getAppId(metadata), ArtifactHelpers.getServiceId(metadata));
        artifact.setMetadata(metadata);
    }
    return artifact;
}

From source file:at.ac.tuwien.infosys.jcloudscale.datastore.util.FileUtil.java

/**
 * Base64 encode the content of the given file
 *
 * @param file given file/*from ww  w  .  j  av a2s .c om*/
 * @return the base64 encoded file content
 */
private static String encodeFile(File file) {
    try {
        byte[] fileData = FileUtils.readFileToByteArray(file);
        return encodeDataBase64(fileData);
    } catch (IOException e) {
        throw new DatastoreException("Error reading file " + file.getName() + ":" + e.getMessage());
    }
}

From source file:com.cloudant.sync.replication.ChangesResultWrapperTest.java

private ChangesResult getChangeResultFromFile(File file) throws IOException {
    byte[] data = FileUtils.readFileToByteArray(file);
    return JSONUtils.deserialize(data, ChangesResult.class);
}