Example usage for org.apache.commons.io IOUtils toByteArray

List of usage examples for org.apache.commons.io IOUtils toByteArray

Introduction

In this page you can find the example usage for org.apache.commons.io IOUtils toByteArray.

Prototype

public static byte[] toByteArray(String input) throws IOException 

Source Link

Document

Get the contents of a String as a byte[] using the default character encoding of the platform.

Usage

From source file:com.streamsets.pipeline.stage.origin.spooldir.TestSpoolDirWithCompression.java

@BeforeClass
public static void setUpClass()
        throws IOException, InterruptedException, URISyntaxException, CompressorException {
    testDir = new File("target", UUID.randomUUID().toString()).getAbsoluteFile();
    Assert.assertTrue(testDir.mkdirs());
    Files.copy(Paths.get(Resources.getResource("logArchive.zip").toURI()),
            Paths.get(testDir.getAbsolutePath(), "logArchive1.zip"));
    Files.copy(Paths.get(Resources.getResource("logArchive.zip").toURI()),
            Paths.get(testDir.getAbsolutePath(), "logArchive2.zip"));
    Files.copy(Paths.get(Resources.getResource("logArchive.tar.gz").toURI()),
            Paths.get(testDir.getAbsolutePath(), "logArchive1.tar.gz"));
    Files.copy(Paths.get(Resources.getResource("logArchive.tar.gz").toURI()),
            Paths.get(testDir.getAbsolutePath(), "logArchive2.tar.gz"));
    Files.copy(Paths.get(Resources.getResource("testAvro.tar.gz").toURI()),
            Paths.get(testDir.getAbsolutePath(), "testAvro1.tar.gz"));
    Files.copy(Paths.get(Resources.getResource("testAvro.tar.gz").toURI()),
            Paths.get(testDir.getAbsolutePath(), "testAvro2.tar.gz"));

    File bz2File = new File(testDir, "testFile1.bz2");
    CompressorOutputStream bzip2 = new CompressorStreamFactory().createCompressorOutputStream("bzip2",
            new FileOutputStream(bz2File));
    bzip2.write(IOUtils.toByteArray(Resources.getResource("testLogFile.txt").openStream()));
    bzip2.close();//from  www. j  ava 2  s  .  c  om

    bz2File = new File(testDir, "testFile2.bz2");
    bzip2 = new CompressorStreamFactory().createCompressorOutputStream("bzip2", new FileOutputStream(bz2File));
    bzip2.write(IOUtils.toByteArray(Resources.getResource("testLogFile.txt").openStream()));
    bzip2.close();
}

From source file:com.stg.crypto.CryptoHelper.java

/**
 * This reads the stream fully to generate the MD5 checksum.
 * This may lead to OutOfMemory as the stream is fully read before generating the checksum.
 * Use {@link IODigestUtility} to read large streams and generate checksums.
 * //from w w  w .j a v  a2  s . co  m
 * @param is input steam
 * @return digest generated using MD5.
 * @throws IOException
 */
public static String generateMD5Checksum(InputStream is) throws IOException {
    byte[] bytes = IOUtils.toByteArray(is);
    return generateChecksum(new MD5Digest(), bytes);
}

From source file:com.github.brandtg.pantopod.crawler.CrawlingEventHandler.java

@Override
public Set<CrawlEvent> handle(CrawlEvent event) throws Exception {
    Set<CrawlEvent> nextEvents = new HashSet<>();

    // Get url/*w  ww  . jav  a  2 s  .  co  m*/
    URI url = URI.create(event.getUrl());
    Document dom = null;
    boolean created = false;
    if (!checkErrors || !hasError(url)) {
        HttpGet req = new HttpGet(url);
        HttpResponse res = httpClient.execute(req);

        try {
            if (res.getStatusLine().getStatusCode() == 200) {
                byte[] domBytes = IOUtils.toByteArray(res.getEntity().getContent());
                created = handleData(url, domBytes);
                dom = Jsoup.parse(new String(domBytes));
            } else {
                LOG.error("Error for {} #=> {}", url, res.getStatusLine().getStatusCode());
                markError(url, res.getStatusLine().getStatusCode());
            }
        } finally {
            if (res.getEntity() != null) {
                EntityUtils.consumeQuietly(res.getEntity());
            }
        }
    }

    // Extract links
    if ((created || traverseDuplicates) && dom != null) {
        for (Element element : dom.select("a")) {
            String href = element.attr("href");
            if (href != null) {
                URI nextUri = getNextUri(url, href, event.getChroot());
                if (shouldExplore(nextUri) && isSameDomain(url, nextUri) && isDifferentPage(url, nextUri)) {
                    CrawlEvent nextEvent = new CrawlEvent(event);
                    nextEvent.setUrl(nextUri.toString());
                    nextEvent.setParentUrl(event.getUrl());
                    nextEvent.setDepth(event.getDepth() + 1);
                    nextEvents.add(nextEvent);
                    LOG.debug("Exploring {}", nextUri);
                } else {
                    LOG.debug("Skipping {}", nextUri);
                }
            }
        }
    }

    return nextEvents;
}

From source file:ch.xxx.carrental.ui.rest.model.CrTableResource.java

@GET
@Path("/mietNr/{mietNr}/pdf")
@Produces("application/pdf")
@DisableCaching/*from w w  w  .j  a v  a  2 s .  c om*/
@ApiOperation(value = "provides the pdf files for display")
public Response getPdf(@PathParam("mietNr") final String mietNr,
        @HeaderParam("Accept-Language") final String acceptLang) {
    byte[] array = null;
    try {
        InputStream inputStream = this.service.readCrPdf(mietNr);
        if (inputStream == null) {
            throw new IOException();
        }
        array = IOUtils.toByteArray(inputStream);
    } catch (IOException e) {
        return Response.status(Status.NOT_FOUND).entity("Failed to read File.").build();
    }
    return Response.ok(array).build();
}

From source file:io.wcm.testing.mock.aem.MockRendition.java

@Override
public long getSize() {
    try {/*ww  w  . jav a 2  s . co m*/
        InputStream is = getStream();
        if (is == null) {
            return 0L;
        }
        return IOUtils.toByteArray(is).length;
    } catch (IOException ex) {
        throw new RuntimeException("Unable to read binary data: " + getPath(), ex);
    }
}

From source file:com.gameminers.mav.audio.AudioManager.java

private void loadClip(String key) {
    try {/*w  ww  .j  ava 2 s  .  co  m*/
        InputStream in = ClassLoader.getSystemResourceAsStream("resources/audio/" + key + ".wav");
        clips.put(key, IOUtils.toByteArray(in));
        in.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:de.fhg.iais.commons.stream.OutputStreamTestBase.java

protected void checkContent(byte[] content) throws FileNotFoundException, IOException {
    InputStream is = new BufferedInputStream(new FileInputStream(FILE));
    Assert.assertArrayEquals(content, IOUtils.toByteArray(is));
    IOUtils.closeQuietly(is);/*  w w  w .  j ava  2s. co  m*/
}

From source file:be.solidx.hot.web.deprecated.ScriptExecutorController.java

public String handleScriptPOST(WebRequest webRequest, String scriptName, Writer writer) {
    try {//from   w w  w .ja  v a  2s . com
        scriptName = scriptName + getScriptExtension();
        Script<COMPILED_SCRIPT> script = buildScript(IOUtils.toByteArray(loadResource(scriptName)), scriptName);
        StringWriter stringWriter = new StringWriter();
        PrintWriter printWriter = new PrintWriter(stringWriter);
        Object result = scriptExecutor.execute(script, webRequest, dbMap, printWriter);
        printWriter.flush();
        stringWriter.flush();
        if (result == null)
            throw new Exception("POST handling scripts must return a page URL to redirect to");
        return "redirect:/" + (String) result;
    } catch (Exception e) {
        printErrorPage(e, writer);
        return null;
    }
}

From source file:ddf.catalog.resource.data.ReliableResource.java

@Deprecated
@Override/*from   ww w. j a  v  a2s.c  o m*/
public byte[] getByteArray() throws IOException {
    try (InputStream product = getProduct()) {
        if (null != product) {
            return IOUtils.toByteArray(product);
        } else {
            throw new IOException("Cannot get byte array of null Product");
        }
    }
}

From source file:com.epam.ta.reportportal.job.SaveBinaryDataJob.java

@Override
public void run() {

    String thumbnailId = null;/*from   ww w.  ja  v  a  2  s.  co  m*/
    Map<String, String> metadata = new HashMap<>();
    metadata.put("project", project);

    if (isImage(binaryData)) {
        try {
            byte[] image = IOUtils.toByteArray(binaryData.getInputStream());
            byte[] thumbnailBytes = thumbnailator.createThumbnail(image);
            thumbnailId = dataStorageService
                    .saveData(
                            new BinaryData(binaryData.getContentType(), (long) thumbnailBytes.length,
                                    new ByteArrayInputStream(thumbnailBytes)),
                            "thumbnail-".concat(filename), metadata);
            binaryData = new BinaryData(binaryData.getContentType(), binaryData.getLength(),
                    new ByteArrayInputStream(image));
        } catch (IOException e) {
            // do not propogate. Thumbnail is not so critical
            LOGGER.error("Thumbnail is not created for log [{}]. Error:\n{}", log.getId(), e);
        }
    }

    /*
     * Saves binary data into storage
     */
    //String dataId = dataStorageService.saveData(binaryData, filename);
    String dataId = dataStorageService.saveData(binaryData, filename, metadata);

    /*
     * Then updates log with just created binary data id
     */
    BinaryContent content = new BinaryContent();
    content.setBinaryDataId(dataId);
    content.setContentType(binaryData.getContentType());
    if (null != thumbnailId) {
        content.setThumbnailId(thumbnailId);
    }

    /*
     * Adds thumbnail if created
     */
    log.setBinaryContent(content);
    logRepository.save(log);
}