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.ocs.dynamo.importer.impl.BaseCsvImporterTest.java

private byte[] readFile(String fileName) throws IOException {
    return FileUtils.readFileToByteArray(new File("src/test/resources/" + fileName));
}

From source file:com.screenslicer.webapp.WebAppConfig.java

public WebAppConfig(boolean isClient) throws IOException {
    Collection<String> mimeTypeList = new HashSet<String>();
    mimeTypeList.add(MediaType.APPLICATION_FORM_URLENCODED);
    mimeTypeList.add(MediaType.APPLICATION_JSON);
    mimeTypeList.add(MediaType.APPLICATION_OCTET_STREAM);
    mimeTypeList.add(MediaType.APPLICATION_SVG_XML);
    mimeTypeList.add(MediaType.APPLICATION_XHTML_XML);
    mimeTypeList.add(MediaType.APPLICATION_XML);
    mimeTypeList.add(MediaType.MULTIPART_FORM_DATA);
    mimeTypeList.add(MediaType.TEXT_HTML);
    mimeTypeList.add(MediaType.TEXT_PLAIN);
    mimeTypeList.add(MediaType.TEXT_XML);
    if (new File("./htdocs").exists()) {
        Collection<File> files = FileUtils.listFiles(new File("./htdocs"), null, true);
        for (File file : files) {
            final byte[] contents = FileUtils.readFileToByteArray(file);
            Resource.Builder resourceBuilder = Resource.builder();
            resourceBuilder.path(file.getAbsolutePath().split("/htdocs/")[1]);
            final ResourceMethod.Builder methodBuilder = resourceBuilder.addMethod("GET");
            String mimeType = MimeTypeFinder.probeContentType(Paths.get(file.toURI()));
            if (!mimeTypeList.contains(mimeType) && !file.getName().toLowerCase().endsWith(".jpg")
                    && !file.getName().toLowerCase().endsWith(".jpeg")
                    && !file.getName().toLowerCase().endsWith(".png")
                    && !file.getName().toLowerCase().endsWith(".gif")
                    && !file.getName().toLowerCase().endsWith(".ico")) {
                mimeTypeList.add(mimeType);
            }//  w w  w  . j a  v  a2 s . c o m
            final File myFile = file;
            methodBuilder.produces(mimeType).handledBy(new Inflector<ContainerRequestContext, byte[]>() {
                @Override
                public byte[] apply(ContainerRequestContext req) {
                    if (!WebApp.DEV) {
                        return contents;
                    }
                    try {
                        return FileUtils.readFileToByteArray(myFile);
                    } catch (IOException e) {
                        return contents;
                    }
                }
            });
            registerResources(resourceBuilder.build());
        }
    }
    register(MultiPartFeature.class);
    Reflections reflections = new Reflections(
            new ConfigurationBuilder().setUrls(ClasspathHelper.forJavaClassPath())
                    .filterInputsBy(new FilterBuilder().include(FilterBuilder.prefix("com.screenslicer"))));
    Set<Class<? extends WebResource>> webResourceClasses = reflections.getSubTypesOf(WebResource.class);
    if (!isClient) {
        for (Class<? extends WebResource> webpageClass : webResourceClasses) {
            registerResources(Resource.builder(webpageClass).build());
        }
    }
    if (isClient) {
        Set<Class<? extends ClientWebResource>> customWebAppClasses = reflections
                .getSubTypesOf(ClientWebResource.class);
        for (Class<? extends ClientWebResource> customWebAppClass : customWebAppClasses) {
            registerResources(Resource.builder(customWebAppClass).build());
        }
    }
    register(ExceptionHandler.class);
    mimeTypes = mimeTypeList.toArray(new String[0]);
}

From source file:com.streamsets.pipeline.lib.parser.protobuf.TestProtobufDataParser.java

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

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

From source file:Highcharts.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  ww  . j  a  v a  2  s. c  o 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:io.appium.java_client.android.PushesFiles.java

/**
 * Saves the given file to the remote mobile device.
 * The application under test should be//from   w  w  w.jav  a2 s .  c  om
 * built with debugMode flag enabled in order to get access to its container
 * on the internal file system.
 *
 * @see <a href="https://developer.android.com/studio/debug/">'Debug Your App' developer article</a>
 *
 * @param remotePath Path to file to write data to on remote device.
 *                   If the path starts with <em>@applicationId/</em> prefix, then the file
 *                   will be pushed to the root of the corresponding application container.
 * @param file is a file to write to remote device
 * @throws IOException when there are problems with a file or current file system
 */
default void pushFile(String remotePath, File file) throws IOException {
    checkNotNull(file, "A reference to file should not be NULL");
    if (!file.exists()) {
        throw new IOException("The given file " + file.getAbsolutePath() + " doesn't exist");
    }
    pushFile(remotePath, Base64.encodeBase64(FileUtils.readFileToByteArray(file)));
}

From source file:algorithm.TextInformationFrame.java

@Override
public List<RestoredFile> restore(File encapsulatedData) throws IOException {
    List<RestoredFile> restoredFiles = new ArrayList<RestoredFile>();
    String restoredCarrierName = getRestoredCarrierName(encapsulatedData);
    byte[] encapsulatedBytes = FileUtils.readFileToByteArray(encapsulatedData);
    String carrierChecksum = "";
    String carrierPath = "";
    while (true) {
        PayloadSegment payloadSegment = PayloadSegment.getPayloadSegment(encapsulatedBytes);
        if (payloadSegment == null) {
            RestoredFile carrier = new RestoredFile(restoredCarrierName);
            FileUtils.writeByteArrayToFile(carrier, encapsulatedBytes);
            carrier.validateChecksum(carrierChecksum);
            carrier.wasCarrier = true;//from   w  ww .  j ava2  s .  c o m
            carrier.algorithm = this;
            carrier.relatedFiles.addAll(restoredFiles);
            carrier.originalFilePath = carrierPath;
            for (RestoredFile file : restoredFiles) {
                file.relatedFiles.add(carrier);
                file.algorithm = this;
            }
            restoredFiles.add(carrier);
            return restoredFiles;
        } else {
            RestoredFile payload = new RestoredFile(RESTORED_DIRECTORY + payloadSegment.getPayloadName());
            FileUtils.writeByteArrayToFile(payload, payloadSegment.getPayloadBytes());
            payload.validateChecksum(payloadSegment.getPayloadChecksum());
            payload.wasPayload = true;
            payload.originalFilePath = payloadSegment.getPayloadPath();
            payload.relatedFiles.addAll(restoredFiles);
            for (RestoredFile file : restoredFiles) {
                file.relatedFiles.add(payload);
            }
            restoredFiles.add(payload);
            encapsulatedBytes = PayloadSegment.removeLeastPayloadSegment(encapsulatedBytes);
            carrierChecksum = payloadSegment.getCarrierChecksum();
            carrierPath = payloadSegment.getCarrierPath();
        }
    }
}

From source file:edu.umn.msi.tropix.common.test.FileDisposableResourceFactoryTest.java

@SuppressWarnings("unchecked")
@Test(groups = "unit", timeOut = 1000)
public void fromByteWithTempFileSupplier() throws IOException {
    final Supplier<File> mockSupplier = EasyMock.createMock(Supplier.class);
    final File file = File.createTempFile("tpxtest", "");
    EasyMock.expect(mockSupplier.get()).andReturn(file);
    EasyMock.replay(mockSupplier);/*from ww w  .  j a v a  2s .  co m*/
    final byte[] bytes = new byte[10];
    RANDOM.nextBytes(bytes);
    final DisposableResource resource = FileDisposableResourceFactory.getByteFunction(mockSupplier)
            .apply(bytes);
    EasyMock.verify(mockSupplier);
    assert resource.getFile().equals(file);
    assert file.exists();
    assert Arrays.equals(bytes, FileUtils.readFileToByteArray(file));
    resource.dispose();
    assert !file.exists();
}

From source file:edu.unc.lib.dl.update.AtomPubMetadataUIPTest.java

@Test
public void prexistingData() throws Exception {
    InputStream entryPart = new FileInputStream(
            new File("src/test/resources/atompub/metadataUpdateMultipleDS.xml"));
    Abdera abdera = new Abdera();
    Parser parser = abdera.getParser();
    Document<Entry> entryDoc = parser.parse(entryPart);
    Entry entry = entryDoc.getRoot();//from  w w  w .  jav a 2 s .c o  m

    PID pid = new PID("uuid:test");

    AccessClient accessClient = mock(AccessClient.class);
    MIMETypedStream modsStream = new MIMETypedStream();
    File raf = new File("src/test/resources/testmods.xml");
    byte[] bytes = FileUtils.readFileToByteArray(raf);
    modsStream.setStream(bytes);
    modsStream.setMIMEType("text/xml");
    when(accessClient.getDatastreamDissemination(any(PID.class),
            eq(ContentModelHelper.Datastream.MD_DESCRIPTIVE.getName()), anyString())).thenReturn(modsStream);
    when(accessClient.getDatastreamDissemination(any(PID.class),
            eq(ContentModelHelper.Datastream.RELS_EXT.getName()), anyString())).thenReturn(null);

    AtomPubMetadataUIP uip = new AtomPubMetadataUIP(pid, "testuser", UpdateOperation.ADD, entry);
    assertEquals(0, uip.getOriginalData().size());
    uip.storeOriginalDatastreams(accessClient);

    assertTrue(uip.getPID().getPid().equals(pid.getPid()));
    assertTrue(uip.getMessage().equals("Creating collection"));

    assertEquals(1, uip.getOriginalData().size());
    assertEquals(3, uip.getIncomingData().size());
    assertEquals(0, uip.getModifiedData().size());
}

From source file:com.ettrema.zsync.UploadReaderTests.java

@Test
public void testMoveBlocksFileInput() throws IOException {

    createTestFiles();/*from   w ww. ja v a  2 s  .com*/

    int blocksize = 5;
    List<RelocateRange> relocs = new ArrayList<RelocateRange>();
    relocs.add(new RelocateRange(new Range(4, 6), 4));

    Enumeration<RelocateRange> relocEnum = new Upload.IteratorEnum<RelocateRange>(relocs);
    UploadReader.moveBlocks(servercopy, relocEnum, blocksize, updatedcopy);

    byte[] updatedbytes = FileUtils.readFileToByteArray(updatedcopy);

    String expResult = "XXXXMOVEBLOCKSXXXXXXXXXXXXXXXXXXXXXXXXXX";
    String actResult = new String(updatedbytes, "US-ASCII");

    Assert.assertEquals(expResult, actResult);

}

From source file:com.redsqirl.auth.UsageRecordUploadJob.java

private String convertFileToString(File file) throws IOException {
    byte[] bytes = FileUtils.readFileToByteArray(file);
    return new String(Base64.encode(bytes));
}