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.streamsets.pipeline.lib.parser.protobuf.TestProtobufDataParser.java

@Test
public void testProtobuf3NonDelimited() throws Exception {
    DataParser dataParser = getDataParserFactory(
            "TestRecordProtobuf3.desc", "TestRecord", false)
                    .getParser("TestRecord",
                            new ByteArrayInputStream(FileUtils.readFileToByteArray(
                                    new File(Resources.getResource("TestProtobuf3NoDelimiter.ser").getPath()))),
                            "0");

    Record record = dataParser.parse();//from   w w w .  j a  va  2  s .c o  m
    verifyProtobuf3TestRecord(record);
}

From source file:com.sophia.charts.export.converter.ChartConverter.java

public ByteArrayOutputStream convert(String input, String globalOptions, String dataOptions, String customCode,
        MimeType mime, String constructor, String callback, Float width, Float scale)
        throws ChartConverterException, 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);
    }//  w w w.j ava2s .  com

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

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

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

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

    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 ChartConverterException("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.platform.middlewares.HTTPFileMiddleware.java

@Override
public boolean handle(String target, org.eclipse.jetty.server.Request baseRequest, HttpServletRequest request,
        HttpServletResponse response) {/*w  ww  .j  ava2  s.  c  o  m*/
    if (target.equals("/"))
        return false;
    if (target.equals("/favicon.ico")) {
        return BRHTTPHelper.handleSuccess(200, null, baseRequest, response, null);
    }

    String requestedFile = MainActivity.app.getFilesDir() + "/" + BUNDLES + "/" + extractedFolder + target;
    File temp = new File(requestedFile);
    if (!temp.exists()) {
        return false;
    }
    Log.i(TAG, "handling: " + target + " " + baseRequest.getMethod());
    boolean modified = true;
    byte[] md5 = CryptoHelper.md5(TypesConverter.long2byteArray(temp.lastModified()));
    String hexEtag = Utils.bytesToHex(md5);
    response.setHeader("ETag", hexEtag);

    // if the client sends an if-none-match header, determine if we have a newer version of the file
    String etag = request.getHeader("if-none-match");
    if (etag != null && etag.equalsIgnoreCase(hexEtag))
        modified = false;

    byte[] body = null;
    if (modified) {
        try {
            body = FileUtils.readFileToByteArray(temp);
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (body == null) {
            return BRHTTPHelper.handleError(400, "could not read the file", baseRequest, response);
        }
    } else {
        return BRHTTPHelper.handleSuccess(304, null, baseRequest, response, null);
    }
    response.setContentType(detectContentType(temp));

    String rangeString = request.getHeader("range");
    if (!Utils.isNullOrEmpty(rangeString)) {
        // Range header should match format "bytes=n-n,n-n,n-n...". If not, then return 416.
        return handlePartialRequest(baseRequest, response, temp);
    } else {
        return BRHTTPHelper.handleSuccess(200, body, baseRequest, response, null);
    }
}

From source file:eionet.webq.service.RemoteFileServiceImpl.java

/**
 * Read file content from file system. The fileUri has to start with "file://" prefix.
 *
 * @param fileUri file location in file system in form of URI.
 * @return file content as bytes.//w w  w  .  j a v  a 2  s  . c  om
 * @throws FileNotAvailableException if file is not available as local resource or fileUri is not valid URI.
 */
private byte[] readFilesystemFile(String fileUri) throws FileNotAvailableException {
    try {
        return FileUtils.readFileToByteArray(new File(new URI(fileUri)));
    } catch (IOException e) {
        throw new FileNotAvailableException("The file is not available at: " + fileUri + "." + e.toString());
    } catch (URISyntaxException e) {
        throw new FileNotAvailableException("Incorrect file URI: " + fileUri + "." + e.toString());
    } catch (Exception e) {
        throw new FileNotAvailableException("Illegal file URI argument: " + fileUri + "." + e.toString());
    }
}

From source file:apiserver.model.Document.java

public void setFile(Object file) throws IOException {
    // if byte[] write to tmp file and then cache that.
    if (file instanceof FileByteWrapper) {
        String[] nameParts = ((FileByteWrapper) file).getName().split("\\.");
        File tmpFile = File.createTempFile(nameParts[0], "." + nameParts[1]);
        //convert array of bytes into file
        FileOutputStream fs = new FileOutputStream(tmpFile);
        fs.write(((FileByteWrapper) file).getBytes());
        fs.close();//from w w w. ja v a  2s.  c  o m
        tmpFile.deleteOnExit();
        file = tmpFile;
    }

    if (file instanceof File) {
        if (!((File) file).exists() || ((File) file).isDirectory()) {
            throw new IOException("Invalid File Reference");
        }

        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:net.bpelunit.framework.control.deploy.ode.ODERequestEntityFactory.java

private void prepareDeploySOAP(File file) throws IOException, SOAPException {
    MessageFactory mFactory = MessageFactory.newInstance();
    SOAPMessage message = mFactory.createMessage();
    SOAPBody body = message.getSOAPBody();

    SOAPElement xmlDeploy = body.addChildElement(ODE_ELEMENT_DEPLOY);
    SOAPElement xmlZipFilename = xmlDeploy.addChildElement(ODE_ELEMENT_ZIPNAME);
    xmlZipFilename.setTextContent(FilenameUtils.getName(file.toString()).split("\\.")[0]);

    SOAPElement xmlZipContent = xmlDeploy.addChildElement(ODE_ELEMENT_PACKAGE);
    SOAPElement xmlBase64ZipFile = xmlZipContent.addChildElement(ODE_ELEMENT_ZIP, "dep", NS_DEPLOY_SERVICE);

    xmlBase64ZipFile.addAttribute(new QName(NS_XML_MIME, CONTENT_TYPE_STRING), ZIP_CONTENT_TYPE);

    StringBuilder content = new StringBuilder();
    byte[] arr = FileUtils.readFileToByteArray(file);
    byte[] encoded = Base64.encodeBase64Chunked(arr);
    for (int i = 0; i < encoded.length; i++) {
        content.append((char) encoded[i]);
    }//from  w w w .j  ava 2 s.co m

    xmlBase64ZipFile.setTextContent(content.toString());

    ByteArrayOutputStream b = new ByteArrayOutputStream();
    message.writeTo(b);
    fContent = b.toString();
}

From source file:com.chiorichan.updater.AutoUpdater.java

public AutoUpdater(DownloadUpdaterService service, String channel) {
    // TODO Make it so the updater can update jars and class files

    instance = this;
    this.service = service;
    this.channel = channel;

    /*//  ww w .j  a va  2 s .  com
     * This schedules the Auto Updater with the Scheduler to run every 30 minutes (by default).
     */
    TaskManager.instance().scheduleAsyncRepeatingTask(this, 0L,
            AppConfig.get().getInt("auto-updater.check-interval", 30) * Ticks.MINUTE, new Runnable() {
                @Override
                public void run() {
                    check();
                }
            });

    try {
        AppConfig.get();
        serverJarMD5 = AppConfig.getApplicationJar().exists() && AppConfig.getApplicationJar().isFile()
                ? SecureFunc.md5(FileUtils.readFileToByteArray(AppConfig.getApplicationJar()))
                : null;

        if (serverJarMD5 != null)
            ServerFileWatcher.instance().register(AppConfig.get().getDirectory(), new EventCallback() {
                @Override
                public void call(Kind<?> kind, File file, boolean isDirectory) {
                    getLogger().debug(String.format("%s: %s", kind.name(), file));

                    AppConfig.get();
                    AppConfig.get();
                    if (AppConfig.getApplicationJar().exists() && AppConfig.getApplicationJar().isFile())
                        if (file.getAbsolutePath().equals(AppConfig.getApplicationJar().getAbsolutePath())
                                && AppConfig.get().getBoolean("auto-updater.auto-restart", true))
                            if (AppLoader.isWatchdogRunning()) {
                                String newServerJarMD5 = null;
                                try {
                                    newServerJarMD5 = SecureFunc
                                            .md5(FileUtils.readFileToByteArray(AppConfig.getApplicationJar()));
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }

                                if (serverJarMD5 == null || !serverJarMD5.equals(newServerJarMD5))
                                    AppController.restartApplication(
                                            "We detected modification to the server jar, the server will now restart to apply changes.");
                            } else
                                getLogger().warning(
                                        "We detected a change to the server jar, but the Watchdog process is not running.");

                    if (file.getAbsolutePath().equals(AppConfig.get().file())) {
                        getLogger().info("We detected a change in the server configuration file, reloading!");
                        AppConfig.get().reload();
                    }
                }
            });
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.netsteadfast.greenstep.util.Pivot4JUtils.java

public static byte[] exportExcelToBytes(String mondrianUrl, String mdx, boolean showDimensionTitle,
        boolean showParentMembers) throws Exception {
    byte[] datas = null;
    File file = null;/*ww w.  j  a v a  2 s.  c  o m*/
    try {
        file = exportExcelFile(mondrianUrl, mdx, showDimensionTitle, showParentMembers);
        datas = FileUtils.readFileToByteArray(file);
    } catch (IOException e) {
        throw e;
    } finally {
        file = null;
    }
    return datas;
}

From source file:io.uploader.drive.config.ConfigTest.java

@Test
public void shouldUpdateHttpProxy() throws IOException {

    verifyProxy(Configuration.INSTANCE.getHttpProxySettings(), false, "host-http", 9000, "user-http",
            "password-http");

    byte[] initFileContents = FileUtils.readFileToByteArray(configSettingFile);

    boolean activated = true;
    String host = "host.of.the.new.proxy";
    String password = "the*new_password";
    String username = "the new user name";
    int port = 8567;
    Proxy newProxy = new Proxy.Builder("http").setActivated(activated).setHost(host).setPassword(password)
            .setUsername(username).setPort(port).build();

    Configuration.INSTANCE.updateProxy(newProxy);

    verifyProxy(Configuration.INSTANCE.getHttpProxySettings(), activated, host, port, username, password);

    byte[] updatedFileContents = FileUtils.readFileToByteArray(configSettingFile);
    assertFalse(Arrays.equals(updatedFileContents, initFileContents));
}

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

/**
 * Test if a single file can be downloaded successfully with quiet mode
 * @throws Exception if anything went wrong
 *//*from w ww  .  j av  a2  s  . co m*/
@Test
public void downloadSingleFileWithoutCompress() throws Exception {
    assertTaskSuccess(download(new Parameters(singleSrc, dest, true, false, false, false, false)));
    assertTrue(destFile.isFile());
    assertArrayEquals(contents, FileUtils.readFileToByteArray(destFile));
}