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:mina.UnsyncClientSupport.java

/**
 * ????FTS//from  w  ww. java  2s.com
 * 
 * @param node
 * @param message
 * @throws CommunicationException
 * @throws InterruptedException
 * @throws InterruptedException
 * @throws IOException
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
public void send(String msg) throws InterruptedException, IOException {
    // EPS ?? CPS ??????
    byte[] message;
    List messages = new ArrayList();
    try {
        message = FileUtils.readFileToByteArray(new File("src/Eps2CpsAtmInquireReq"));
        message = Arrays.copyOf(message, message.length - 1);
        messages.add(message);

        message = FileUtils.readFileToByteArray(new File("src/Eps2CpsAuthCancelReq"));
        message = Arrays.copyOf(message, message.length - 1);
        messages.add(message);

        message = FileUtils.readFileToByteArray(new File("src/Eps2CpsAuthReq"));
        message = Arrays.copyOf(message, message.length - 1);
        messages.add(message);

        message = FileUtils.readFileToByteArray(new File("src/Eps2CpsPosInquireReq"));
        message = Arrays.copyOf(message, message.length - 1);
        messages.add(message);

        message = FileUtils.readFileToByteArray(new File("src/Eps2CpsWithdrawReq"));
        message = Arrays.copyOf(message, message.length - 1);
        messages.add(message);

        for (int i = 0; i < messages.size(); i++) {
            byte[] tmp = (byte[]) messages.get(i);
            byte[] data = CommonUtils.update(tmp, false);
            messages.set(i, data);
        }

    } catch (IOException e) {
        e.printStackTrace();
    }
    timer = new Timer();
    timer.schedule(new SendMessageTask(messages), 0, 1000);
}

From source file:de.xirp.report.ReportDescriptor.java

/**
 * Sets the file name of the report. //  ww w . j  av  a 2 s .c o m
 * Furthermore the byte data of the given file
 * is written to the data byte array.
 * 
 * @param fileName 
 *             The fileName to set.
 */
public void setFileName(String fileName) {
    this.fileName = fileName;
    try {
        setPdfData(FileUtils.readFileToByteArray(new File(Constants.REPORT_DIR, this.fileName)));
    } catch (IOException e) {
        setPdfData(new byte[] {});
        logClass.warn("Error: " + e.getMessage() //$NON-NLS-1$
                + Constants.LINE_SEPARATOR, e);
    }
}

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

@Test
public void shouldUpdateHttpsProxy() throws IOException {

    verifyProxy(Configuration.INSTANCE.getHttpsProxySettings(), false, "host-https", 9001, "user-https",
            "password-https");

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

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

    Configuration.INSTANCE.updateProxy(newProxy);

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

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

From source file:eionet.webq.converter.MultipartFileToUserFileConverterTest.java

@Test
public void whenConvertingMultipartFile_ifAttachmentFileNameExtensionIsZip_unpackAllFiles() throws Exception {
    Collection<UserFile> files = fileConverter.convert(
            new MockMultipartFile("xmlFileUpload", "file.zip", "some-other-zip-attachment-content-type",
                    FileUtils.readFileToByteArray(new File(TEST_XML_FILES_ZIP))));

    verifyContentExtractedFromTestZipFile(files);
}

From source file:com.joyent.manta.client.multipart.EncryptedMultipartManagerTest.java

public void canDoMultipartUpload() throws Exception {
    MantaMetadata metadata = new MantaMetadata();
    metadata.put("m-my-key", "my value");
    metadata.put("e-my-key-1", "my value 1");
    metadata.put("e-my-key-2", "my value 2");

    MantaHttpHeaders headers = new MantaHttpHeaders();

    String path = "/user/stor/testobject";

    EncryptedMultipartUpload<TestMultipartUpload> upload = manager.initiateUpload(path, 35L, metadata, headers);

    ArrayList<String> lines = new ArrayList<>();
    lines.add("01234567890ABCDEF|}{");
    lines.add("ZYXWVUTSRQPONMLKJIHG");
    lines.add("!@#$%^&*()_+-=[]/,.<");
    lines.add(">~`?abcdefghijklmnop");
    lines.add("qrstuvxyz");

    String expected = StringUtils.join(lines, "");

    MantaMultipartUploadPart[] parts = new MantaMultipartUploadPart[5];

    for (int i = 0; i < lines.size(); i++) {
        parts[i] = manager.uploadPart(upload, i + 1, lines.get(i));
    }//from   ww  w  . j  a v  a  2  s.c om

    Stream<MantaMultipartUploadTuple> partsStream = Stream.of(parts);

    manager.complete(upload, partsStream);

    TestMultipartUpload actualUpload = upload.getWrapped();

    MantaMetadata actualMetadata = MantaObjectMapper.INSTANCE.readValue(actualUpload.getMetadata(),
            MantaMetadata.class);

    Assert.assertEquals(actualMetadata, metadata, "Metadata wasn't stored correctly");

    MantaHttpHeaders actualHeaders = MantaObjectMapper.INSTANCE.readValue(actualUpload.getHeaders(),
            MantaHttpHeaders.class);

    Assert.assertEquals(actualHeaders, headers, "Headers were stored correctly");

    {
        Cipher cipher = cipherDetails.getCipher();
        byte[] iv = upload.getEncryptionState().getEncryptionContext().getCipher().getIV();
        cipher.init(Cipher.ENCRYPT_MODE, secretKey, cipherDetails.getEncryptionParameterSpec(iv));

        byte[] assumedCiphertext = cipher.doFinal(expected.getBytes(StandardCharsets.US_ASCII));
        byte[] contents = FileUtils.readFileToByteArray(upload.getWrapped().getContents());
        byte[] actualCiphertext = Arrays.copyOf(contents,
                contents.length - cipherDetails.getAuthenticationTagOrHmacLengthInBytes());

        try {
            AssertJUnit.assertEquals(assumedCiphertext, actualCiphertext);
        } catch (AssertionError e) {
            System.err.println("expected: " + Hex.encodeHexString(assumedCiphertext));
            System.err.println("actual  : " + Hex.encodeHexString(actualCiphertext));
            throw e;
        }
    }

    EncryptionContext encryptionContext = upload.getEncryptionState().getEncryptionContext();

    MantaHttpHeaders responseHttpHeaders = new MantaHttpHeaders();
    responseHttpHeaders.setContentLength(actualUpload.getContents().length());

    final String hmacName = SupportedHmacsLookupMap
            .hmacNameFromInstance(encryptionContext.getCipherDetails().getAuthenticationHmac());

    responseHttpHeaders.put(MantaHttpHeaders.ENCRYPTION_HMAC_TYPE, hmacName);
    responseHttpHeaders.put(MantaHttpHeaders.ENCRYPTION_IV,
            Base64.getEncoder().encodeToString(encryptionContext.getCipher().getIV()));
    responseHttpHeaders.put(MantaHttpHeaders.ENCRYPTION_KEY_ID, cipherDetails.getCipherId());

    MantaObjectResponse response = new MantaObjectResponse(path, responseHttpHeaders, metadata);

    CloseableHttpResponse httpResponse = mock(CloseableHttpResponse.class);

    try (InputStream fin = new FileInputStream(actualUpload.getContents());
            EofSensorInputStream eofIn = new EofSensorInputStream(fin, null);
            MantaObjectInputStream objIn = new MantaObjectInputStream(response, httpResponse, eofIn);
            InputStream in = new MantaEncryptedObjectInputStream(objIn, cipherDetails, secretKey, true)) {
        String actual = IOUtils.toString(in, StandardCharsets.UTF_8);

        Assert.assertEquals(actual, expected);
    }
}

From source file:com.mirth.connect.connectors.file.filesystems.test.FileConnectionTest.java

@Test
public void testWriteFile() {
    String testString = new String("This is just a test string");
    byte[] byteTest = testString.getBytes(Charset.defaultCharset());

    File testFile = new File("writeFile" + System.currentTimeMillis() + ".dat");

    try {//from www  .  j av a  2  s.co m
        fc.writeFile(testFile.getName(), someFolder.getAbsolutePath(), false,
                new ByteArrayInputStream(byteTest));
    } catch (Exception e) {
        fail("The FileConnection threw an exception, it should not have.");
    }

    File checkFile = new File(someFolder.getAbsolutePath() + File.separator + testFile.getName());

    // Now we load it back and check!
    try {
        byte[] verifyArr = FileUtils.readFileToByteArray(checkFile);
        assertArrayEquals(byteTest, verifyArr);
    } catch (Exception e) {
        fail("The JavaIO threw an exception (" + e.getClass().getName() + "): " + e.getMessage());
    }

    // Verify that appending works
    try {
        fc.writeFile(testFile.getName(), someFolder.getAbsolutePath(), true,
                new ByteArrayInputStream(byteTest));
    } catch (Exception e) {
        fail("The FileConnection threw an exception, it should not have (when appending).");
    }

    // Now we load it back and check!
    try {
        byte[] doubleCheck = new byte[byteTest.length * 2];
        System.arraycopy(byteTest, 0, doubleCheck, 0, byteTest.length);
        System.arraycopy(byteTest, 0, doubleCheck, byteTest.length, byteTest.length);

        byte[] verifyArr = FileUtils.readFileToByteArray(checkFile);
        assertArrayEquals(doubleCheck, verifyArr);
    } catch (Exception e) {
        fail("The JavaIO threw an exception (" + e.getClass().getName() + "): " + e.getMessage());
    }

}

From source file:com.emergya.persistenceGeo.service.impl.ResourceServiceImpl.java

protected AbstractResourceEntity dtoToEntity(ResourceDto dto) {
    AbstractResourceEntity entity = null;
    if (dto != null) {
        if (dto.getId() != null && dto.getId() > 0) {
            entity = (AbstractResourceEntity) resourceDao.findById(dto.getId(), false);
        } else {/*from   www.  j  a  v  a2  s.  c  o  m*/
            entity = instancer.createResourceEntity();
        }
        // Add own parameters
        entity.setName(dto.getName());
        entity.setSize(dto.getSize());
        entity.setType(dto.getType());
        entity.setAccessId(dto.getAccessId());

        //Layer data
        if (dto.getData() != null) {
            try {
                entity.setData(FileUtils.readFileToByteArray(dto.getData()));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    return entity;
}

From source file:com.googlecode.dex2jar.reader.DexFileReader.java

/**
 * read the dex file from file, if the file is a zip file, it will return the content of classes.dex in the zip
 * file.//from   ww w .  j  a  va 2 s  . c o m
 * 
 * @param file
 * @return
 * @throws IOException
 */
public static byte[] readDex(File file) throws IOException {
    return readDex(FileUtils.readFileToByteArray(file));
}

From source file:eu.planets_project.tb.impl.data.util.ImageThumbnail.java

/**
 * @param dob//w  ww .  j  ava 2s .  com
 * @param thumbWidth
 * @param thumbHeight
 * @param out
 * @throws Exception
 */
public static void createThumb(DigitalObject dob, OutputStream out) throws Exception {
    log.debug("Loading in the image...");
    File imgFile = DigitalObjectUtils.toFile(dob);
    byte[] data = FileUtils.readFileToByteArray(imgFile);
    log.debug("Writing image to stream...");
    ImageThumbnail.createThumb(data, THUMB_WIDTH, THUMB_HEIGHT, out);
    log.debug("Image has been written to stream.");
    return;
}

From source file:com.boundlessgeo.geoserver.bundle.BundleExporterTest.java

@Test
public void testZipBundle() throws Exception {
    new CatalogCreator(cat).workspace("foo");
    exporter = new BundleExporter(cat, new ExportOpts(cat.getWorkspaceByName("foo")).name("blah"));

    exporter.run();/*from w  w w . j av  a 2 s  .c om*/
    Path zip = exporter.zip();
    ZipInputStream zin = new ZipInputStream(
            new ByteArrayInputStream(FileUtils.readFileToByteArray(zip.toFile())));
    ZipEntry entry = null;

    boolean foundBundle = false;
    boolean foundWorkspace = false;

    while (((entry = zin.getNextEntry()) != null)) {
        if (entry.getName().equals("bundle.json")) {
            foundBundle = true;
        }
        if (entry.getName().endsWith("workspace.xml")) {
            foundWorkspace = true;
        }
    }

    assertTrue(foundBundle);
    assertTrue(foundWorkspace);
}