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:com.telefonica.euro_iaas.sdc.dao.impl.FileDaoWebDavImpl.java

/**
 * {@inheritDoc}/*  w w w .  j a  v  a 2 s  .  co  m*/
 */
@Override
public String insertFile(String webdavFileUrl, File installable) throws SardineException {

    sardine = SardineFactory.begin(propertiesProvider.getProperty(WEBDAV_USERNAME),
            propertiesProvider.getProperty(WEBDAV_PASSWD));
    byte[] data;
    try {
        data = FileUtils.readFileToByteArray(new File(installable.getAbsolutePath()));
        sardine.put(webdavFileUrl, data);
        LOGGER.log(Level.INFO, webdavFileUrl + " INSERTED ");
    } catch (IOException e) {
        // TODO Auto-generated catch block
        throw new SdcRuntimeException(e);
    }

    return installable.getAbsolutePath();
}

From source file:format.Format.java

/**
 * Fetches the file, and its byte data/*from w w w.  j a va  2s  .  c  o m*/
 */
public void getFileByteData() {

    File file = new File(this.filename);

    // get header byteData in bytes
    try {
        this.data = FileUtils.readFileToByteArray(file);
    } catch (IOException ex) {
        log.log(Level.SEVERE, String.format("File %s not found!", this.filename), ex);
    }

    // set image size
    this.size = this.data.length;

    // image is valid until proven invalid
    this.isValid = true;

    // make ArrayList of strings for file info
    this.info = new ArrayList<>();
}

From source file:fi.jumi.launcher.daemon.DirBasedStewardTest.java

@Test
public void copies_the_embedded_daemon_JAR_to_the_settings_dir() throws IOException {
    Path daemonJar = steward.getDaemonJar(jumiHome);

    assertThat(daemonJar.getFileName().toString(), is(expectedName));
    assertThat(FileUtils.readFileToByteArray(daemonJar.toFile()), is(expectedContent));
}

From source file:com.highcharts.export.converter.SVGConverter.java

public ByteArrayOutputStream convert(String input, MimeType mime, String constructor, String callback,
        Float width, Float scale)
        throws SVGConverterException, IOException, PoolException, NoSuchElementException, TimeoutException {

    ByteArrayOutputStream stream = null;

    // get filename
    String extension = mime.name().toLowerCase();
    String outFilename = createUniqueFileName("." + extension);

    Map<String, String> params = new HashMap<String, String>();
    Gson gson = new Gson();

    params.put("infile", input);
    params.put("outfile", outFilename);

    if (constructor != null && !constructor.isEmpty()) {
        params.put("constr", constructor);
    }/*from  w  w  w. ja v a 2  s  .  co m*/

    if (callback != null && !callback.isEmpty()) {
        params.put("callback", callback);
    }

    if (width != null) {
        params.put("width", String.valueOf(width));
    }

    if (scale != null) {
        params.put("scale", String.valueOf(scale));
    }

    String json = gson.toJson(params);
    String output = requestServer(json);

    // check for errors
    if (output.substring(0, 5).equalsIgnoreCase("error")) {
        logger.debug("recveived error from phantomjs: " + output);
        throw new SVGConverterException("recveived error from phantomjs:" + output);
    }

    stream = new ByteArrayOutputStream();
    if (output.equalsIgnoreCase(outFilename)) {
        // in case of pdf, phantom cannot base64 on pdf files
        stream.write(FileUtils.readFileToByteArray(new File(outFilename)));
    } else {
        // assume phantom is returning SVG or a base64 string for images
        if (extension.equals("svg")) {
            stream.write(output.getBytes());
        } else {
            stream.write(Base64.decodeBase64(output));
        }
    }
    return stream;
}

From source file:com.lbb.controller.FileUploadController.java

@RequestMapping("download.html")
public void download(String fileName, HttpServletResponse response) throws IOException {
    OutputStream os = response.getOutputStream();
    try {/*  w w  w  . jav  a  2s . c o  m*/
        response.reset();
        response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
        response.setContentType("image/jpeg; charset=utf-8");
        os.write(FileUtils.readFileToByteArray(FileUpload.getFile(fileName)));
        os.flush();
    } finally {
        if (os != null) {
            os.close();
        }
    }
}

From source file:com.adaptris.core.ftp.SftpKeyAuthentication.java

@Override
public SftpClient connect(SftpClient sftp, UserInfo ui)
        throws FileTransferException, IOException, PasswordException {
    byte[] privateKey = FileUtils.readFileToByteArray(new File(getPrivateKeyFilename()));
    String pw = ExternalResolver.resolve(getPrivateKeyPassword());
    sftp.connect(ui.getUser(), privateKey, pw != null ? Password.decode(pw).getBytes() : null);
    return sftp;/*from   ww  w .j  av  a 2  s.c  o  m*/
}

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

/**
 * Sets up the test./*from   w  ww. j  av  a2  s .  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.TCGA_LEVEL_2_DATA_FILE));
}

From source file:com.baasbox.db.async.ExportJob.java

@Override
public void run() {
    FileOutputStream dest = null;
    ZipOutputStream zip = null;//from w  ww.j av  a  2s.  c  o  m
    FileOutputStream tempJsonOS = null;
    FileInputStream in = null;
    try {
        //File f = new File(this.fileName);
        File f = File.createTempFile("export", ".temp");

        dest = new FileOutputStream(f);
        zip = new ZipOutputStream(dest);

        File tmpJson = File.createTempFile("export", ".json");
        tempJsonOS = new FileOutputStream(tmpJson);
        DbHelper.exportData(this.appcode, tempJsonOS);
        BaasBoxLogger.info(String.format("Writing %d bytes ", tmpJson.length()));
        tempJsonOS.close();

        ZipEntry entry = new ZipEntry("export.json");
        zip.putNextEntry(entry);
        in = new FileInputStream(tmpJson);
        final int BUFFER = BBConfiguration.getImportExportBufferSize();
        byte buffer[] = new byte[BUFFER];

        int length;
        while ((length = in.read(buffer)) > 0) {
            zip.write(buffer, 0, length);
        }
        zip.closeEntry();
        in.close();

        File manifest = File.createTempFile("manifest", ".txt");
        FileUtils.writeStringToFile(manifest,
                BBInternalConstants.IMPORT_MANIFEST_VERSION_PREFIX + BBConfiguration.getApiVersion());

        ZipEntry entryManifest = new ZipEntry("manifest.txt");
        zip.putNextEntry(entryManifest);
        zip.write(FileUtils.readFileToByteArray(manifest));
        zip.closeEntry();

        tmpJson.delete();
        manifest.delete();

        File finaldestination = new File(this.fileName);
        FileUtils.moveFile(f, finaldestination);

    } catch (Exception e) {
        BaasBoxLogger.error(ExceptionUtils.getMessage(e));
    } finally {
        try {
            if (zip != null)
                zip.close();
            if (dest != null)
                dest.close();
            if (tempJsonOS != null)
                tempJsonOS.close();
            if (in != null)
                in.close();

        } catch (Exception ioe) {
            BaasBoxLogger.error(ExceptionUtils.getMessage(ioe));
        }
    }
}

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

/**
 * This method returns the data from the file containing the encrypted
 * public 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 w ww. j  ava  2  s .c o  m*/
 * 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 public key file.
 * @throws KeyNotFoundException if the key data could not be retrieved; an acceptable message or chained cause must be provided.
 */
@Override
public byte[] getEncryptedPublicKeyData() throws KeyNotFoundException {
    try {
        return FileUtils.readFileToByteArray(this.publicKeyFile);
    } catch (FileNotFoundException e) {
        throw new KeyNotFoundException(
                "The public key file [" + this.publicKeyFile.getPath() + "] does not exist.");
    } catch (IOException e) {
        throw new KeyNotFoundException(
                "Could not read from the public key file [" + this.publicKeyFile.getPath() + "].", e);
    }
}

From source file:com.btmatthews.leabharlann.service.impl.FileImportSource.java

/**
 * Perform a depth first traversal of the directory tree with a root at {@code current}
 * processing each file discovered by invoking {@code callback}.
 * root is a directory a depth first traversal of the directory tree is preformed
 * processing each file discovered.//from  www  .j a v  a  2s . c o m
 *
 * @param current The root directory.
 * @param callback The callback used to process the files.
 * @throws Exception If there was an error.
 */
private void processDirectory(final File current, final ImportCallback callback) throws Exception {
    for (final File child : current.listFiles()) {
        final String path = File.separator + file.toURI().relativize(child.toURI()).getPath();
        if (child.isDirectory()) {
            callback.directory(path);
            processDirectory(child, callback);
        } else {
            final byte[] data = FileUtils.readFileToByteArray(child);
            callback.file(path, child.lastModified(), data);
        }
    }
}