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.DownloadTest.java

/**
 * Do not overwrite an existing file//from   ww  w. ja v  a2  s . co  m
 * @throws Exception if anything goes wrong
 */
@Test
public void skipExisting() throws Exception {
    // write contents to destination file
    File dst = folder.newFile();
    FileUtils.writeStringToFile(dst, "Hello");

    Download t = makeProjectAndTask();
    String src = makeSrc(TEST_FILE_NAME);
    t.src(src);
    t.dest(dst);
    t.overwrite(false); // do not overwrite the file
    t.execute();

    // contents must not be changed
    byte[] dstContents = FileUtils.readFileToByteArray(dst);
    assertArrayEquals("Hello".getBytes(), dstContents);
}

From source file:com.talis.platform.testsupport.StubHttpTest.java

@Test
public void expectedOneGetReturning200WithFileEntityAndContentType() throws Exception {
    URL resource = StubHttpTest.class.getResource("/entity.txt");
    File entity = new File(resource.toURI());

    byte[] expected = FileUtils.readFileToByteArray(entity);

    stubHttp.expect("GET", "/my/path").andReturn(200, entity, "application/json");
    stubHttp.replay();/*from  ww  w.  j  ava  2  s  .  c o  m*/

    assertExpectedStatusEntityAndContentType(new String(expected), 200,
            new HttpGet(stubHttp.getBaseUrl() + "/my/path"), "application/json");

    stubHttp.verify();
}

From source file:com.silverpeas.util.FileUtil.java

/**
 * Read the content of a file in a byte array.
 *
 * @param file the file to be read.//from   w w w.  j  a v a  2s .com
 * @return the bytes array containing the content of the file.
 * @throws IOException
 */
public static byte[] readFile(final File file) throws IOException {
    return FileUtils.readFileToByteArray(file);
}

From source file:com.stacksync.desktop.util.FileUtil.java

public static byte[] readFileToByteArray(File file) throws IOException {
    return FileUtils.readFileToByteArray(file);
}

From source file:com.baidu.cc.configuration.service.impl.VersionServiceImpl.java

/**
 * ??./*from   ww  w  .j a v  a2 s.c om*/
 * 
 * @param file
 *            
 * @param versionId
 *            the version id
 * @throws IOException
 *             ?
 */
@Override
public void importFromFile(File file, Long versionId) throws IOException {
    byte[] byteArray = FileUtils.readFileToByteArray(file);

    Hex encoder = new Hex();
    try {
        byteArray = encoder.decode(byteArray);
    } catch (DecoderException e) {
        throw new IOException(e.getMessage());
    }
    String json = new String(byteArray, SysUtils.UTF_8);

    // parse from gson
    JsonParser jsonParser = new JsonParser();
    JsonElement je = jsonParser.parse(json);

    if (!je.isJsonArray()) {
        throw new RuntimeException("illegal json string. must be json array.");
    }

    JsonArray jsonArray = je.getAsJsonArray();

    int size = jsonArray.size();
    Version version = new Version();
    List<ConfigGroup> groups = new ArrayList<ConfigGroup>();
    ConfigGroup group;
    List<ConfigItem> items;
    ConfigItem item;

    for (int i = 0; i < size; i++) {
        JsonObject jo = jsonArray.get(i).getAsJsonObject();
        group = gson.fromJson(jo, ConfigGroup.class);

        // get sub configuration item
        JsonArray subItemsJson = jo.get(CONFIG_ITEMS_ELE).getAsJsonArray();

        int subSize = subItemsJson.size();
        items = new ArrayList<ConfigItem>();
        for (int j = 0; j < subSize; j++) {
            item = gson.fromJson(subItemsJson.get(j), ConfigItem.class);
            items.add(item);
        }

        group.setConfigItems(items);
        groups.add(group);
    }

    version.setConfigGroups(groups);
    configCopyService.copyConfigItemsFromVersion(version, versionId);
}

From source file:jetbrains.buildServer.torrent.TorrentTransportTest.java

public void testTeamcityIvy() throws IOException, NoSuchAlgorithmException {
    setTorrentTransportEnabled();//from ww w . j  av  a2s . c o m
    final File ivyFile = new File(myTempDir, TorrentTransportFactory.TEAMCITY_IVY);

    final String urlString = SERVER_PATH + TorrentTransportFactory.TEAMCITY_IVY;

    final File teamcityIvyFile = new File("agent/tests/resources/" + TorrentTransportFactory.TEAMCITY_IVY);
    myDownloadMap.put("/" + TorrentTransportFactory.TEAMCITY_IVY, teamcityIvyFile);

    //    assertNull(myTorrentTransport.getDigest(urlString));
    assertNotNull(myTorrentTransport.downloadUrlTo(urlString, ivyFile));
    assertTrue(ivyFile.exists());

    final String path1 = SERVER_PATH + "MyBuild.31.zip";
    final String torrentPath1 = SERVER_PATH + ".teamcity/torrents/MyBuild.31.zip.torrent";
    final String path2 = SERVER_PATH + "MyBuild.32.zip";
    final String torrentPath2 = SERVER_PATH + ".teamcity/torrents/MyBuild.32.zip.torrent";

    final File file1 = new File(myTempDir, "MyBuild.31.zip");
    final File file2 = new File(myTempDir, "MyBuild.32.zip");

    final File torrentFile = new File("agent/tests/resources/commons-io-cio2.5_40.jar.torrent");
    final byte[] torrentBytes = FileUtils.readFileToByteArray(torrentFile);
    myDownloadHacks.put(torrentPath1, torrentBytes);
    myDownloadHacks.put(torrentPath2, torrentBytes);
    setDownloadHonestly(false);

    myTorrentTransport.downloadUrlTo(path1, file1);
    myTorrentTransport.downloadUrlTo(path2, file2);

    // shouldn't try to download the second file:
    assertEquals(1, myDownloadHackAttempts.size());
    assertEquals(torrentPath1, myDownloadHackAttempts.get(0));

}

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

/**
 * Tests if a multiple files can be downloaded to a directory
 * @throws Exception if anything goes wrong
 *///w  w w  .j  a v  a2 s  . c o m
@Test
public void downloadMultipleFiles() throws Exception {
    Download t = makeProjectAndTask();
    t.src(Arrays.asList(makeSrc(TEST_FILE_NAME), makeSrc(TEST_FILE_NAME2)));

    File dst = folder.newFolder();
    t.dest(dst);
    t.execute();

    byte[] dstContents = FileUtils.readFileToByteArray(new File(dst, TEST_FILE_NAME));
    assertArrayEquals(contents, dstContents);
    byte[] dstContents2 = FileUtils.readFileToByteArray(new File(dst, TEST_FILE_NAME2));
    assertArrayEquals(contents2, dstContents2);
}

From source file:com.seleniumtests.connectors.tms.hpalm.HpAlmConnector.java

/**
 * compress and record results in ALM/*w w  w . ja v a 2s  .  c o  m*/
 */
@Override
public void recordResultFiles() {

    try {
        File resultFile = File.createTempFile("result-", ".zip");
        ZipUtil.pack(new File(SeleniumTestsContextManager.getThreadContext().getOutputDirectory()), resultFile);

        // Unirest does not allow sending result to ALM
        String boundary = "azertyuiop";
        String body = "--" + boundary + "\r\n";
        body += "Content-Disposition: form-data; name=\"filename\"\r\n";
        body += "Content-type: application/octet-stream\r\n\r\n";
        body += String.format("%s\r\n", resultFile.getName());
        body += "--" + boundary + "\r\n";
        body += String.format("Content-Disposition: form-data; name=\"file\"; filename=\"%s\"\r\n\r\n",
                resultFile.getName());

        byte[] bodyBytes = Bytes.concat(body.getBytes(), FileUtils.readFileToByteArray(resultFile),
                String.format("\r\n--%s--\r\n", boundary).getBytes());

        Unirest.post(
                serverUrl + "/rest/domains/{domain}/projects/{project}/{entityType}s/{entityId}/attachments")
                .routeParam(ENTITY_TYPE, "run").routeParam(ENTITY_ID, currentRunId)
                .routeParam(PROJECT_NAME, project).routeParam(DOMAIN_NAME, domain)
                .header("Content-Type", "multipart/form-data; boundary=" + boundary).body(bodyBytes).asString();

    } catch (UnirestException | IOException e) {
        logger.error("Result record failed", e);
    }
}

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

/**
 * Reads the file contents to byte[] can only be used as input to other function that returns a string.
 * // w w  w.  jav a2 s .  c  o  m
 * @param fileName
 * @return
 */
public byte[] getFileBytes(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 ret;
}

From source file:io.appium.java_client.ComparesImages.java

/**
 * Performs images matching by template to find possible occurrence of the partial image
 * in the full image. Read//from  w  w w . j  a v  a 2s  .  c o m
 * https://docs.opencv.org/2.4/doc/tutorials/imgproc/histograms/template_matching/template_matching.html
 * for more details on this topic.
 *
 * @param fullImage The location of the full image
 * @param partialImage The location of the partial image
 * @param options comparison options
 * @return The matching result. The configuration of fields in the result depends on comparison options.
 */
default OccurrenceMatchingResult findImageOccurrence(File fullImage, File partialImage,
        @Nullable OccurrenceMatchingOptions options) throws IOException {
    return findImageOccurrence(Base64.encodeBase64(FileUtils.readFileToByteArray(fullImage)),
            Base64.encodeBase64(FileUtils.readFileToByteArray(partialImage)), options);
}