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.linkedin.pinot.transport.common.routing.RandomRoutingTableTest.java

@Test
public void testHelixExternalViewBasedRoutingTable() throws Exception {
    String tableName = "testTable_OFFLINE";
    String fileName = RandomRoutingTableTest.class.getClassLoader().getResource("SampleExternalView.json")
            .getFile();// ww  w. j a  v  a2 s.co m
    System.out.println(fileName);
    InputStream evInputStream = new FileInputStream(fileName);
    ZNRecordSerializer znRecordSerializer = new ZNRecordSerializer();
    ZNRecord externalViewRecord = (ZNRecord) znRecordSerializer.deserialize(IOUtils.toByteArray(evInputStream));
    int totalRuns = 10000;
    RoutingTableBuilder routingStrategy = new BalancedRandomRoutingTableBuilder(10);
    HelixExternalViewBasedRouting routingTable = new HelixExternalViewBasedRouting(null, null);
    Field offlineRTBField = HelixExternalViewBasedRouting.class.getDeclaredField("_offlineRoutingTableBuilder");
    offlineRTBField.setAccessible(true);
    offlineRTBField.set(routingTable, routingStrategy);

    ExternalView externalView = new ExternalView(externalViewRecord);

    routingTable.markDataResourceOnline(tableName, externalView, getInstanceConfigs(externalView));

    double[] globalArrays = new double[9];

    for (int numRun = 0; numRun < totalRuns; ++numRun) {
        RoutingTableLookupRequest request = new RoutingTableLookupRequest(tableName);
        Map<ServerInstance, SegmentIdSet> serversMap = routingTable.findServers(request);
        TreeSet<ServerInstance> serverInstances = new TreeSet<ServerInstance>(serversMap.keySet());

        int i = 0;

        double[] arrays = new double[9];
        for (ServerInstance serverInstance : serverInstances) {
            globalArrays[i] += serversMap.get(serverInstance).getSegments().size();
            arrays[i++] = serversMap.get(serverInstance).getSegments().size();
        }
        for (int j = 0; i < arrays.length; ++j) {
            Assert.assertTrue(arrays[j] / totalRuns <= 31);
            Assert.assertTrue(arrays[j] / totalRuns >= 28);
        }
        //System.out.println(Arrays.toString(arrays) + " : " + new StandardDeviation().evaluate(arrays) + " : " + new Mean().evaluate(arrays));
    }
    for (int i = 0; i < globalArrays.length; ++i) {
        Assert.assertTrue(globalArrays[i] / totalRuns <= 31);
        Assert.assertTrue(globalArrays[i] / totalRuns >= 28);
    }
    System.out.println(Arrays.toString(globalArrays) + " : " + new StandardDeviation().evaluate(globalArrays)
            + " : " + new Mean().evaluate(globalArrays));
}

From source file:com.github.tomakehurst.wiremock.ResponseDribbleAcceptanceTest.java

@Test
public void requestIsSuccessfulButTakesLongerThanSocketTimeoutWhenDribbleIsEnabled() throws Exception {
    stubFor(get("/delayedDribble").willReturn(
            ok().withBody(BODY_BYTES).withChunkedDribbleDelay(BODY_BYTES.length, DOUBLE_THE_SOCKET_TIMEOUT)));

    long start = System.currentTimeMillis();
    HttpResponse response = httpClient//w  w w .j a va 2  s  .  com
            .execute(new HttpGet(String.format("http://localhost:%d/delayedDribble", wireMockRule.port())));
    byte[] responseBody = IOUtils.toByteArray(response.getEntity().getContent());
    int duration = (int) (System.currentTimeMillis() - start);

    assertThat(response.getStatusLine().getStatusCode(), is(200));
    assertThat(responseBody, is(BODY_BYTES));
    assertThat(duration, greaterThanOrEqualTo(SOCKET_TIMEOUT_MILLISECONDS));
    assertThat((double) duration, closeTo(DOUBLE_THE_SOCKET_TIMEOUT, 100.0));
}

From source file:com.netflix.dyno.connectionpool.impl.utils.ZipUtils.java

/**
 * Decompresses the given byte array//from ww  w .j a  v  a 2 s  . c  o m
 *
 * @param compressed byte array input
 * @return decompressed data in string format
 * @throws IOException
 */
public static String decompressStringNonBase64(byte[] compressed) throws IOException {
    ByteArrayInputStream is = new ByteArrayInputStream(compressed);
    InputStream gis = new GZIPInputStream(is);
    return new String(IOUtils.toByteArray(gis), StandardCharsets.UTF_8);
}

From source file:at.create.android.ffc.domain.Setting.java

/**
 * Builds a setting instance from the given input stream.
 * @param is Input stream/*w  ww . java  2  s  .  co  m*/
 * @return Setting instance
 * @throws IOException
 */
public static Setting load(InputStream is) throws IOException {
    SimpleXmlHttpMessageConverter xmlConverter = new SimpleXmlHttpMessageConverter();
    MockHttpInputMessage inputMessage = new MockHttpInputMessage(IOUtils.toByteArray(is));
    return (Setting) xmlConverter.read(Setting.class, inputMessage);
}

From source file:com.armorize.hackalert.extractor.msword.MSBaseParser.java

/**
 * Main for testing. Pass a ms document as argument
 *//*from  w  w w  . j a v  a  2s  .c  om*/
public static void main(String mime, MSBaseParser parser, String args[]) {
    try {
        ExtractorUniversal extractor = new ExtractorUniversal("TEST");
        File orderFile = new File("order.xml");
        SettingsHandler settingsHandler = new XMLSettingsHandler(orderFile);
        settingsHandler.initialize();
        // settingsHandler.getOrder().setAttribute(
        // new Attribute(CrawlOrder.ATTR_SETTINGS_DIRECTORY, "tmp/"));
        CrawlerSettings globalSettings = settingsHandler.getSettingsObject(null);
        MapType extractorsSettings = (MapType) settingsHandler.getOrder()
                .getAttribute(CrawlOrder.ATTR_EXTRACT_PROCESSORS);

        extractorsSettings.addElement(globalSettings, extractor);
        extractor.setAttribute(new Attribute(Processor.ATTR_ENABLED, Boolean.TRUE));
        //======================
        byte[] raw = IOUtils.toByteArray(new FileInputStream("C:\\temp\\userman.doc"));
        String text = parser.getParse(raw);
        ByteArrayInputStream in = new ByteArrayInputStream(text.getBytes("utf-8"));

        HttpRecorder recorder = HttpRecorder.wrapInputStreamWithHttpRecord(new File("tmp"),
                MSBaseParser.class.getName(), in, "utf-8");

        CrawlURI curi = new CrawlURI(UURIFactory.getInstance("http://www.armorize.com/"));
        curi.setContentSize(recorder.getRecordedInput().getSize());
        curi.setContentType("application/msword");
        curi.setFetchStatus(200);
        curi.setHttpRecorder(recorder);

        curi.putObject(CoreAttributeConstants.A_HTTP_TRANSACTION, new Object());

        extractor.process(curi);
        System.out.println(curi.getOutLinks());
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:ee.ria.xroad.common.signature.SignatureBuilderTest.java

private static byte[] fileToBytes(String fileName) throws Exception {
    try (InputStream input = new FileInputStream(getFilePath(fileName).toFile())) {
        return IOUtils.toByteArray(input);
    }/* w w w.  jav  a 2  s. c  o  m*/
}

From source file:com.thoughtworks.go.websocket.MessageEncoding.java

public static Message decodeMessage(InputStream input) {
    try {//  w w w  .j  a v a2 s. c om
        try (GZIPInputStream zipStream = new GZIPInputStream(input)) {
            String jsonStr = new String(IOUtils.toByteArray(zipStream), StandardCharsets.UTF_8);
            return gson.fromJson(jsonStr, Message.class);
        }
    } catch (IOException e) {
        throw bomb(e);
    }
}

From source file:com.esri.geoportal.harvester.sink.SinkFile.java

/**
 * Reads content./*from  w ww .  j a v  a2  s  . c om*/
 * @return content reference
 * @throws IOException if reading content fails
 * @throws URISyntaxException if file url is an invalid URI
 */
public SimpleDataReference readContent() throws IOException, URISyntaxException {
    Date lastModifiedDate = readLastModifiedDate();
    MimeType contentType = readContentType();
    try (InputStream input = attemptToOpenStream(ctx.attemptCount, ctx.attemptDelay);) {
        SimpleDataReference ref = new SimpleDataReference(broker.getBrokerUri(),
                broker.getEntityDefinition().getLabel(), file.toAbsolutePath().toString(), lastModifiedDate,
                file.toUri(), broker.td.getSource().getRef(), broker.td.getRef());
        ref.addContext(contentType, IOUtils.toByteArray(input));
        return ref;
    } finally {
        // once file is read, delete it
        attemptToDeleteFile(ctx.attemptCount, ctx.attemptDelay);
    }
}

From source file:com.acmerocket.ywiki.RootResource.java

/**
 * @param path//w  w  w. j av  a  2  s  .  c o m
 * @return
 */
private byte[] readAll(final String path) throws IOException {
    String fullPath = path;
    if (this.isDirectory(path)) {
        fullPath = path + "/" + DEFAULT_PAGE;
    }

    InputStream in = this.getClass().getResourceAsStream(fullPath);

    if (in != null) {
        return IOUtils.toByteArray(in);
    } else {
        return null;
    }
}

From source file:eu.scidipes.toolkits.pawebapp.util.zip.TestZipUtils.java

/**
 * Test method for//  w  w  w  . j ava  2s .c o  m
 * {@link eu.scidipes.toolkits.palibrary.utils.zip.ZipUtils#byteArrayZipEntriesToBase64(java.util.Set)}.
 * 
 * @throws IOException
 */
@Test
public final void testByteArrayZipEntriesToBase64() throws IOException {
    final String mainFileName = "SCIDIP-ES-Registry-Framework-Overview.pdf";
    final String metaFileName = "meta.xml";

    final InputStream mainFileStream = getClass().getResourceAsStream(mainFileName);
    final InputStream metaFileStream = getClass().getResourceAsStream(metaFileName);

    final byte[] mainFileBytes = IOUtils.toByteArray(mainFileStream);
    final byte[] metaFileBytes = IOUtils.toByteArray(metaFileStream);

    final ZipEntry zipMain = new ZipEntry(mainFileName);
    final ZipEntry zipMeta = new ZipEntry(metaFileName);

    final Set<ByteArrayZipEntry> entries = new HashSet<>();
    entries.add(new ByteArrayZipEntry(mainFileBytes, zipMain));
    entries.add(new ByteArrayZipEntry(metaFileBytes, zipMeta));

    final String zipResult = ZipUtils.byteArrayZipEntriesToBase64(entries);
    assertTrue(zipResult != null && zipResult.length() > 100);
}