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.talis.platform.testsupport.StubHttpTest.java

@Test
public void expectedOneGetReturning200WithFileEntity() 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);
    stubHttp.replay();//from ww w.  j a v a 2  s . co m

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

    stubHttp.verify();
}

From source file:com.redhat.red.offliner.ftest.SinglePOMRepoDownloadFTest.java

/**
 * In general, we should only have one test method per functional test. This allows for the best parallelism when we
 * execute the tests, especially if the setup takes some time.
 *
 * @throws Exception In case anything (anything at all) goes wrong!
 *//*  w ww  .  ja va2s  .c o m*/
@Test
public void run() throws Exception {
    // We only need one repo server.
    TestRepositoryServer server = newRepositoryServer();

    // Generate some test content
    byte[] content = contentGenerator.newBinaryContent(1024);

    Dependency dep = contentGenerator.newDependency();
    Model pom = contentGenerator.newPom();
    pom.addDependency(dep);

    // Add a repository to the pom
    Repository repo = contentGenerator.newRepository("Test Repo", server.getBaseUri());
    pom.addRepository(repo);

    String path = contentGenerator.pathOf(dep);

    // Register the generated content by writing it to the path within the repo server's dir structure.
    // This way when the path is requested it can be downloaded instead of returning a 404.
    server.registerContent(path, content);
    server.registerContent(path + Main.SHA_SUFFIX, sha1Hex(content));
    server.registerContent(path + Main.MD5_SUFFIX, md5Hex(content));

    // All deps imply an accompanying POM file when using the POM artifact list reader, so we have to register one of these too.
    Model pomDep = contentGenerator.newPomFor(dep);
    String pomPath = contentGenerator.pathOf(pomDep);
    String md5Path = pomPath + Main.MD5_SUFFIX;
    String shaPath = pomPath + Main.SHA_SUFFIX;

    String pomStr = contentGenerator.pomToString(pomDep);

    server.registerContent(pomPath, pomStr);
    server.registerContent(md5Path, md5Hex(pomStr));
    server.registerContent(shaPath, sha1Hex(pomStr));

    // Write the plaintext file we'll use as input.
    File pomFile = temporaryFolder.newFile(getClass().getSimpleName() + ".pom");

    FileUtils.write(pomFile, contentGenerator.pomToString(pom));

    Options opts = new Options();

    // Capture the downloads here so we can verify the content.
    File downloads = temporaryFolder.newFolder();

    opts.setDownloads(downloads);
    opts.setLocations(Collections.singletonList(pomFile.getAbsolutePath()));

    // run `new Main(opts).run()` and return the Main instance so we can query it for errors, etc.
    Main finishedMain = run(opts);

    assertThat(
            "Wrong number of downloads logged. Should have been 6 (declared jar + its corresponding POM + 2 checksums each).",
            finishedMain.getDownloaded(), equalTo(6));
    assertThat("Errors should be empty!", finishedMain.getErrors().isEmpty(), equalTo(true));

    File downloaded = new File(downloads, path);
    assertThat("File: " + path + " doesn't seem to be downloaded!", downloaded.exists(), equalTo(true));
    assertThat("Downloaded File: " + path + " contains wrong content!",
            FileUtils.readFileToByteArray(downloaded), equalTo(content));
}

From source file:com.qualogy.qafe.service.DocumentTest.java

private byte[] readFile(String fileName) {
    File f = new File(fileName);
    try {/*from w w w. ja va2 s  .c  o  m*/
        return FileUtils.readFileToByteArray(f);
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:algorithm.ImageInformationEmbeddingFrame.java

/**
 * Create empty image with enough capacity to embed the payload
 * //from   w  ww .j a  v  a  2s.co  m
 * @param carrier
 * @param payload
 * @return image for payload
 * @throws IOException
 */
private BufferedImage createPayloadImage(File carrier, File payload) throws IOException {
    BufferedImage carrierImage = ImageIO.read(carrier);
    byte[] payloadBytes = FileUtils.readFileToByteArray(payload);
    int neededPayloadHeight = getNeededHeight(carrierImage.getWidth(), payloadBytes.length);
    return new BufferedImage(carrierImage.getWidth(), neededPayloadHeight, BufferedImage.TYPE_INT_RGB);
}

From source file:com.streamsets.pipeline.stage.origin.remote.FTPAndSSHDUnitTest.java

private void populateFakeFileSystemFromReal(File absFile) throws Exception {
    for (File f : absFile.listFiles()) {
        if (f.isFile()) {
            addFileToFakeFileSystem(f.getAbsolutePath(), FileUtils.readFileToByteArray(f), f.lastModified());
        } else if (f.isDirectory()) {
            DirectoryEntry entry = new DirectoryEntry(f.getAbsolutePath());
            fakeFtpServer.getFileSystem().add(entry);
            populateFakeFileSystemFromReal(f);
        }/*from   w  w  w .  jav  a 2  s .c  o  m*/
    }
}

From source file:com.thoughtworks.go.server.service.ArtifactsServiceTest.java

@Test
void shouldNotSaveArtifactWhenItsAZipContainingDirectoryTraversalPath() throws URISyntaxException, IOException {
    final File logsDir = new File("logs");

    final ByteArrayInputStream stream = new ByteArrayInputStream(FileUtils
            .readFileToByteArray(new File(getClass().getResource("/archive_traversal_attack.zip").toURI())));
    String buildInstanceId = "1";
    final File destFile = new File(logsDir, buildInstanceId + File.separator + LOG_XML_NAME);
    assumeArtifactsRoot(logsDir);/*from ww  w .  ja  v  a2 s.  c  om*/
    ArtifactsService artifactsService = new ArtifactsService(resolverService, stageService, artifactsDirHolder,
            new ZipUtil(), systemService);
    boolean saved = artifactsService.saveFile(destFile, stream, true, 1);
    assertThat(saved).isFalse();
}

From source file:ch.silviowangler.dox.AbstractIntegrationTest.java

protected DocumentReference importDocument(String fileName, Map<TranslatableKey, DescriptiveIndex> indexes,
        String documentClassShortName)
        throws IOException, ValidationException, DocumentDuplicationException, DocumentClassNotFoundException {
    File singlePagePdf = loadFile(fileName);
    PhysicalDocument doc = new PhysicalDocument(new DocumentClass(documentClassShortName),
            FileUtils.readFileToByteArray(singlePagePdf), indexes, singlePagePdf.getName());
    doc.setClient("wangler");
    return documentService.importDocument(doc);
}

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

private void testTempAndMove(boolean createDst) throws Exception {
    Download t = makeProjectAndTask();//from w  w  w  .  j  a  v a2s  .c o  m
    downloadTaskDir = t.getDownloadTaskDir();
    String src = makeSrc(TEST_FILE_NAME);
    t.src(src);
    dst = folder.newFile();

    checkDstDoesNotExist = !createDst;

    if (createDst) {
        dst = folder.newFile();
        OutputStream os = new FileOutputStream(dst);
        os.close();
    } else {
        dst.delete(); //make sure dest does not exist, so we can verify correctly
    }

    t.dest(dst);
    t.tempAndMove(true);
    t.execute();

    assertTrue(dst.exists());
    assertNull(getTempFile());

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

From source file:com.falkonry.TestAddFactsStream.java

/**
 * Should create datastream and add fact data in JSON format
 * @throws Exception// ww  w  .j a v a 2  s  . c om
 */
@Test
public void createDatastreamWithJsonFacts() throws Exception {

    Datastream ds = new Datastream();
    ds.setName("Test-DS-" + Math.random());
    TimeObject time = new TimeObject();
    time.setIdentifier("time");
    time.setFormat("iso_8601");
    time.setZone("GMT");
    Signal signal = new Signal();
    signal.setTagIdentifier("tag");
    signal.setValueIdentifier("value");
    signal.setDelimiter("_");
    signal.setIsSignalPrefix(false);

    Field field = new Field();
    field.setSiganl(signal);
    field.setTime(time);
    ds.setField(field);
    Datasource dataSource = new Datasource();
    dataSource.setType("STANDALONE");
    ds.setDatasource(dataSource);

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

    List<Assessment> assessments = new ArrayList<Assessment>();
    AssessmentRequest assessmentRequest = new AssessmentRequest();
    assessmentRequest.setName("Health");
    assessmentRequest.setDatastream(datastream.getId());
    assessmentRequest.setAssessmentRate("PT1S");
    Assessment assessment = falkonry.createAssessment(assessmentRequest);
    assessments.add(assessment);
    Assert.assertEquals(assessment.getName(), assessmentRequest.getName());

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

    String data = "{\"time\" : \"2016-03-01 01:01:01\", \"tag\" : \"signal1_entity1\", \"value\" : 3.4}";
    falkonry.addInput(datastream.getId(), data, options);

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

    InputStatus response = falkonry.addFactsStream(assessment.getId(), byteArrayInputStream, null);
    Assert.assertEquals(response.getAction(), "ADD_FACT_DATA");
    Assert.assertEquals(response.getStatus(), "PENDING");
}

From source file:it.av.eatt.service.RistoranteServiceTest.java

@Test
public void testRistoranteService() throws JackWicketException, IOException {

    Ristorante a = new Ristorante();
    a.setName("RistoAlessandro");
    a.setDescriptions(getDescriptionI18ns());
    a = ristoranteService.insert(a, user);

    assertNotNull(a.getRevisions());// ww w.ja va 2  s .c om
    assertEquals(a.getRevisions().size(), 1);

    // a = ristoranteService.getByPath(a.getPath());
    a = ristoranteService.getByID(a.getId());
    assertNotNull("A is null", a);
    assertEquals("Invalid value for test", "RistoAlessandro", a.getName());
    assertNotNull(a.getDescriptions());
    assertNotNull(a.getDescriptions().get(0));
    assertTrue(a.getDescriptions().get(0).getDescription().equals("description"));

    a = ristoranteService.addRate(a, user, 1);

    // assertTrue(ristoranteService.hasUsersAlreadyRated(a, user));

    assertTrue(a.getRates().size() > 0);
    assertTrue(a.getRates().get(0).getRate() == 1);

    try {
        a = ristoranteService.addRate(a, user, 1);
        fail("Exception doesn't throw on multi rated operation");
    } catch (Exception e) {
        // expected
    }

    a = ristoranteService.update(a, user);
    assertTrue("Rates losts after update ", a.getRates().get(0).getRate() == 1);

    Collection<Ristorante> all = ristoranteService.getAll();
    assertNotNull(all);
    assertTrue(all.size() > 0);

    a.setName("newName");
    a = ristoranteService.update(a, user);

    a = ristoranteService.getByID(a.getId());
    assertNotNull("A is null", a);
    assertEquals("Invalid value for test", "newName", a.getName());

    //add a picture
    RistorantePicture img = new RistorantePicture();
    img.setPicture(
            FileUtils.readFileToByteArray(new File(this.getClass().getResource("images/test.png").getFile())));
    a.addPicture(img);
    a = ristoranteService.update(a, user);

    a = ristoranteService.getByID(a.getId());
    assertNotNull("A is null", a.getPictures());
    assertEquals("Invalid value for test", 1, a.getPictures().size());

    ristoranteService.remove(a);

}