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:it.smartcommunitylab.parking.management.web.manager.MarkerIconStorage.java

public byte[] getMarkerIcon(String basePath, String company, String entity, String color) throws IOException {
    if (color == null) {
        return getTemplateMarker(basePath, company, entity);
    }//from   w  w  w. ja v a 2  s. co m
    if (!new File(
            getIconFolder(basePath, ICON_FOLDER_CACHE) + company + "-" + entity + "-" + color + ICON_EXTENSION)
                    .exists()) {
        // load template icon
        generateColoredMarker(basePath, company, entity, color);
    }
    return FileUtils.readFileToByteArray(new File(getIconFolder(basePath, ICON_FOLDER_CACHE) + company + "-"
            + entity + "-" + color + ICON_EXTENSION));
}

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

/**
 * Tests if a file is downloaded to the project directory when specifying
 * a relative path/*from   w  w w.  j  a  v a2s .c  o  m*/
 * @throws Exception if anything goes wrong
 */
@Test
public void downloadSingleFileToRelativePath() throws Exception {
    Download t = makeProjectAndTask();
    t.src(makeSrc(TEST_FILE_NAME));
    t.dest(TEST_FILE_NAME);
    t.execute();

    byte[] dstContents = FileUtils.readFileToByteArray(new File(projectDir, TEST_FILE_NAME));
    assertArrayEquals(contents, dstContents);
}

From source file:net.ripe.rpki.validator.output.ValidatedObjectWriterTest.java

@Test
public void shouldCopyValidatedObjectToTargetDirectory() throws IOException {
    subject.afterFetchSuccess(TEST_OBJECT_URI, certificate, result);

    assertTrue("file created", TEST_OBJECT_FILE.exists());
    assertArrayEquals("contents match", certificate.getEncoded(),
            FileUtils.readFileToByteArray(TEST_OBJECT_FILE));
}

From source file:fi.jumi.launcher.daemon.DirBasedStewardTest.java

@Test
public void overwrites_an_existing_daemon_JAR_that_has_difference_file_size() throws IOException {
    overwriteWithFileOfSize(expectedContent.length + 1, steward.getDaemonJar(jumiHome));

    Path daemonJar = steward.getDaemonJar(jumiHome);

    assertThat(FileUtils.readFileToByteArray(daemonJar.toFile()), is(expectedContent));
}

From source file:com.dream.messaging.sender.SimulatorMessageSender.java

/**
 * Send./*from  w ww. ja  va 2  s .  c  o  m*/
 * 
 * @param obj1 the obj1
 * @param msgReq the msg req
 * 
 * @return the message
 * @throws MessagingException 
 * 
 * @throws Exception the base exception
 */
public Message send(Object obj, Message msgReq) throws ConnectionException, MessagingException {
    String dir = properties.get(DIRECTORY);
    if (dir == null) {
        logger.error("Please set directory!!!!!!");
        return null;
    }
    String encoding = properties.get(ENCODING);
    if (encoding == null) {
        logger.error("Please set encoding,now use UTF-8!!!!!!");
        encoding = "UTF-8";
    }
    String tranCode = msgReq.getMessageId();
    if (tranCode == null) {
        logger.error("Please set transaction code!!!!!!!");
        return null;
    }

    String path = dir + File.separator + tranCode + SURFIX;
    logger.info("The response message path is:" + path);
    File file = new File(path);

    Object content = null;
    if (msgReq instanceof ByteArrayMessage) {
        logger.info("The response message read with bytes.");
        try {
            content = FileUtils.readFileToByteArray(file);
        } catch (IOException e) {
            logger.error("ERROR.", e);
            return null;
        }
    }

    if (msgReq instanceof StringMessage) {
        logger.info("The response message read with string.");
        try {
            content = FileUtils.readFileToString(file, encoding);
        } catch (IOException e) {
            logger.error("ERROR.", e);
            return null;
        }
    }

    Class cls = msgReq.getClass();

    Message response = null;
    try {
        response = (Message) cls.newInstance();
    } catch (InstantiationException e) {
        logger.error("ERROR.", e);
        return null;
    } catch (IllegalAccessException e) {
        logger.error("ERROR.", e);
        return null;
    }

    try {
        response.setContent(content);
    } catch (IOException e) {
        logger.error("ERROR.", e);
        return null;
    }

    return response;
}

From source file:com.igormaznitsa.zxpspritecorrector.files.HOBETAPlugin.java

@Override
public ReadResult readFrom(final File file, final int index) throws IOException {
    final byte[] wholeFile = FileUtils.readFileToByteArray(file);
    final Hobeta parsed = HOBETA_FILE_PARSER.parse(wholeFile).mapTo(Hobeta.class);
    return new ReadResult(
            new ZXPolyData(new Info(parsed.name, (char) (parsed.type & 0xFF), parsed.start, parsed.length, 0),
                    this, parsed.data),
            null);//from   w  w w  .  ja v a 2s  . c om
}

From source file:com.fh.controller.upload.FileUploadController.java

/**
 * //from   w ww.  j  a va 2s  .  c om
 * 
 * @param response
 * @param request
 * @param realName
 * @param name
 */
@RequestMapping("/download/{realName}/{name}")
public void download(HttpServletResponse response, HttpServletRequest request, @PathVariable String realName,
        @PathVariable String name) {
    OutputStream os = null;
    response.reset();
    realName = request.getSession().getServletContext().getRealPath("/") + "upload" + File.separator + realName;
    response.setHeader("Content-Disposition", "attachment; filename=" + name);
    response.setContentType("application/octet-stream; charset=utf-8");
    try {
        os = response.getOutputStream();
        os.write(FileUtils.readFileToByteArray(new File(realName)));
        os.flush();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (os != null) {
            try {
                os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

From source file:com.weaverplatform.nifi.XmiImporterTest.java

@Test
public void testOnTrigger() {

    try {/* w w  w.  ja va  2s .  c o  m*/

        // Random info and simulate flowfile (with attributes) passed through to this processor in early state
        String file = "xmi.xml";
        byte[] contents = FileUtils
                .readFileToByteArray(new File(getClass().getClassLoader().getResource(file).getFile()));
        InputStream in = new ByteArrayInputStream(contents);
        InputStream cont = new ByteArrayInputStream(IOUtils.toByteArray(in));
        ProcessSession session = testRunner.getProcessSessionFactory().createSession();
        FlowFile f = session.create();
        f = session.importFrom(cont, f);

        // Add the flowfile to the runner
        testRunner.enqueue(f);

        // Run the enqueued content, it also takes an int = number of contents queued
        testRunner.run();

    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:ezbake.frack.submitter.SubmitterClient.java

private void run(CmdLineParser parser)
        throws TException, IOException, CmdLineException, EzConfigurationLoaderException {
    if (!(submit || shutdown || ping)) {
        throw new CmdLineException(parser, "Must provide either -u or -d option to client");
    }/*from   ww w.j  a  va2 s .c o m*/
    Properties props = new EzConfiguration().getProperties();
    props.setProperty(EzBakePropertyConstants.EZBAKE_SECURITY_ID, securityId);
    ThriftClientPool pool = new ThriftClientPool(props);
    Submitter.Client client = pool.getClient(submitterConstants.SERVICE_NAME, Submitter.Client.class);
    try {
        if (submit) {
            if (Strings.isNullOrEmpty(pipelineId)) {
                throw new CmdLineException(parser, "Pipeline ID required for submission");
            }
            File zipFile = new File(pathToTarGz);
            byte[] fileBytes = FileUtils.readFileToByteArray(zipFile);
            SubmitResult result = client.submit(ByteBuffer.wrap(fileBytes), pipelineId);
            System.out.println(result.getMessage());
        } else if (shutdown) {
            if (Strings.isNullOrEmpty(pipelineId)) {
                throw new CmdLineException(parser, "Pipeline ID required for shutdown");
            }
            client.shutdown(pipelineId);
        } else {
            boolean healthy = client.ping();
            System.out.println(healthy ? "The service is healthy!" : "The service is unhealthy!");
        }
    } finally {
        if (client != null) {
            pool.returnToPool(client);
            pool.close();
        }
    }
}

From source file:it.anyplace.sync.core.cache.FileBlockCache.java

private @Nullable byte[] pullFile(String code, boolean shouldCheck) {

    final File file = new File(dir, code);
    if (file.exists()) {
        try {/*from  ww  w .java  2 s .  c  o m*/
            byte[] data = FileUtils.readFileToByteArray(file);
            if (shouldCheck) {
                String cachedDataCode = BaseEncoding.base16()
                        .encode(Hashing.sha256().hashBytes(data).asBytes());
                checkArgument(equal(code, cachedDataCode), "cached data code %s does not match code %s",
                        cachedDataCode, code);
            }
            writerThread.submit(new Runnable() {
                @Override
                public void run() {
                    try {
                        FileUtils.touch(file);
                    } catch (IOException ex) {
                        logger.warn("unable to 'touch' file {}", file);
                        logger.warn("unable to 'touch' file", ex);
                    }
                }

            });
            logger.debug("read block {} from cache file {}", code, file);
            return data;
        } catch (Exception ex) {
            logger.warn("error reading block from cache", ex);
            FileUtils.deleteQuietly(file);
        }
    }
    return null;
}