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

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

Introduction

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

Prototype

public static InputStream toInputStream(String input) 

Source Link

Document

Convert the specified string to an input stream, encoded as bytes using the default character encoding of the platform.

Usage

From source file:com.fluidops.iwb.api.OntologyManagerImpl.java

@Override
public boolean storeOntology(OWLOntology ontology, URI ontologyURI, boolean overwrite)
        throws OWLOntologyStorageException, OWLOntologyCreationException {
    OWLOntologyManager manager = OWLManager.createOWLOntologyManager();
    ReadWriteDataManager dm = null;/*w  ww . ja va 2s  .  com*/
    try {
        manager.createOntology(IRI.create(ontologyURI));
        manager.setOntologyFormat(ontology, new RDFXMLOntologyFormat());
        StringDocumentTarget target = new StringDocumentTarget();
        manager.saveOntology(ontology, target);

        dm = ReadWriteDataManagerImpl.openDataManager(Global.repository);

        dm.importRDFfromInputStream(IOUtils.toInputStream(target.toString()), ontologyURI.toString(),
                RDFFormat.RDFXML, Context.getFreshPublishedContext(Context.ContextType.USER, ontologyURI,
                        ContextLabel.ONTOLOGY_IMPORT));

    } finally {
        ReadWriteDataManagerImpl.closeQuietly(dm);
    }

    return true;
}

From source file:io.druid.segment.realtime.firehose.EventReceiverFirehoseTest.java

@Test
public void testMultipleThreads()
        throws InterruptedException, IOException, TimeoutException, ExecutionException {
    EasyMock.expect(req.getContentType()).andReturn("application/json").times(2 * NUM_EVENTS);
    EasyMock.replay(req);/*ww  w .  j  a va 2s  .  c om*/

    final ExecutorService executorService = Execs.singleThreaded("single_thread");
    final Future future = executorService.submit(new Callable<Boolean>() {
        @Override
        public Boolean call() throws Exception {
            for (int i = 0; i < NUM_EVENTS; ++i) {
                final InputStream inputStream = IOUtils.toInputStream(inputRow);
                firehose.addAll(inputStream, req);
                inputStream.close();
            }
            return true;
        }
    });

    for (int i = 0; i < NUM_EVENTS; ++i) {
        final InputStream inputStream = IOUtils.toInputStream(inputRow);
        firehose.addAll(inputStream, req);
        inputStream.close();
    }

    future.get(10, TimeUnit.SECONDS);

    EasyMock.verify(req);

    final Iterable<Map.Entry<String, EventReceiverFirehoseMetric>> metrics = register.getMetrics();
    Assert.assertEquals(1, Iterables.size(metrics));

    final Map.Entry<String, EventReceiverFirehoseMetric> entry = Iterables.getLast(metrics);

    Assert.assertEquals(SERVICE_NAME, entry.getKey());
    Assert.assertEquals(CAPACITY, entry.getValue().getCapacity());
    Assert.assertEquals(CAPACITY, firehose.getCapacity());
    Assert.assertEquals(2 * NUM_EVENTS, entry.getValue().getCurrentBufferSize());
    Assert.assertEquals(2 * NUM_EVENTS, firehose.getCurrentBufferSize());

    for (int i = 2 * NUM_EVENTS - 1; i >= 0; --i) {
        Assert.assertTrue(firehose.hasMore());
        Assert.assertNotNull(firehose.nextRow());
        Assert.assertEquals(i, firehose.getCurrentBufferSize());
    }

    Assert.assertEquals(CAPACITY, entry.getValue().getCapacity());
    Assert.assertEquals(CAPACITY, firehose.getCapacity());
    Assert.assertEquals(0, entry.getValue().getCurrentBufferSize());
    Assert.assertEquals(0, firehose.getCurrentBufferSize());

    firehose.close();
    Assert.assertFalse(firehose.hasMore());
    Assert.assertEquals(0, Iterables.size(register.getMetrics()));

    executorService.shutdownNow();
}

From source file:ddf.content.endpoint.rest.ContentEndpointCreateTest.java

/**
 * Content-Type specified by client as one of the defaults (e.g., application/octet-stream)
 * simulating what a browser might do, and should be refined by ContentEndpoint to
 * application/json;id=geojson based on the filename's extension of "json".
 *
 * @throws Exception/*from  w  w w .j  av a  2 s.  c  o m*/
 */
@Test
public void testParseAttachmentContentTypeSetToBrowserDefault() throws Exception {
    InputStream is = IOUtils.toInputStream(TEST_JSON);
    MetadataMap<String, String> headers = new MetadataMap<String, String>();
    headers.add(ContentEndpoint.CONTENT_DISPOSITION,
            "form-data; name=file; filename=C:\\DDF\\geojson_valid.json");
    headers.add(CONTENT_TYPE, "application/octet-stream");
    Attachment attachment = new Attachment(is, headers);

    ContentFramework framework = mock(ContentFramework.class);
    ContentEndpoint endpoint = new ContentEndpoint(framework, getMockMimeTypeMapper());
    CreateInfo createInfo = endpoint.parseAttachment(attachment);
    Assert.assertNotNull(createInfo);
    Assert.assertEquals("application/json;id=geojson", createInfo.getContentType());
    Assert.assertEquals("geojson_valid.json", createInfo.getFilename());
}

From source file:net.skyebook.osmgenerator.DBActions.java

private void pushBulkNodes() {
    if (bulkInsertNodeBuilder == null)
        return;/*from   ww w  .  j  av a  2  s  . c om*/
    try {
        InputStream is = IOUtils.toInputStream(bulkInsertNodeBuilder.toString());
        bulkInsertNode.execute("SET UNIQUE_CHECKS=0; ");
        bulkInsertNode.setLocalInfileInputStream(is);

        bulkInsertNode.execute("LOAD DATA LOCAL INFILE 'file.txt' INTO TABLE nodes FIELDS TERMINATED BY '"
                + BULK_DELIMITER + "' (id, latitude, longitude, tags)");

        bulkInsertNode.execute("SET UNIQUE_CHECKS=1; ");
        bulkInsertNodeBuilder = null;
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:com.agilejava.docbkx.maven.AbstractPdfMojo.java

private Configuration loadFOPConfig() throws MojoExecutionException {
    ClassLoader loader = this.getClass().getClassLoader();
    InputStream in = loader.getResourceAsStream("fonts.stg");
    Reader reader = new InputStreamReader(in);
    StringTemplateGroup group = new StringTemplateGroup(reader);
    StringTemplate template = group.getInstanceOf("config");
    template.setAttribute("fonts", fonts);
    DefaultConfigurationBuilder builder = new DefaultConfigurationBuilder();
    final String config = template.toString();
    if (getLog().isDebugEnabled()) {
        getLog().debug(config);//from  ww  w .j a va2 s.co m
    }
    try {
        return builder.build(IOUtils.toInputStream(config));
    } catch (IOException ioe) {
        throw new MojoExecutionException("Failed to load FOP config.", ioe);
    } catch (SAXException saxe) {
        throw new MojoExecutionException("Failed to parse FOP config.", saxe);
    } catch (ConfigurationException e) {
        throw new MojoExecutionException("Failed to do something Avalon requires....", e);
    }
}

From source file:com.lightbox.android.operations.CachedOperation.java

private ApiResponse<?> parseString(String stringResult) throws ParsingException, IOException, ApiException {
    if (stringResult == null) {
        return null;
    }/*w w  w.  ja v a2 s  . c o  m*/
    return getApiRequest().parseInputStream(IOUtils.toInputStream(stringResult));
}

From source file:com.norconex.committer.solr.SolrCommitterSolrIntegrationTest.java

@Test
public void testCommitQueueWith3AddCommandAnd1DeleteCommand() throws Exception {
    UpdateResponse worked = server.deleteByQuery("*:*");
    committer.commit();/*from w  w w.  j a v a2s. c o m*/

    System.out.println("deleted " + worked.toString());
    String content1 = "Document 1";
    InputStream doc1Content = IOUtils.toInputStream(content1);
    String id1 = "1";
    Properties doc1Metadata = new Properties();
    doc1Metadata.addString("id", id1);

    String content2 = "Document 2";
    String id2 = "2";
    InputStream doc2Content = IOUtils.toInputStream(content2);
    Properties doc2Metadata = new Properties();
    doc2Metadata.addString("id", "2");

    String content3 = "Document 3";
    String id3 = "3";
    InputStream doc3Content = IOUtils.toInputStream(content3);
    Properties doc3Metadata = new Properties();
    doc2Metadata.addString("id", "3");

    committer.add(id1, doc1Content, doc1Metadata);
    committer.add(id2, doc2Content, doc2Metadata);

    //TODO hacking this part of the test until a more solid fix is found in 
    //SolrCommitter
    committer.commit();

    committer.remove(id1, doc1Metadata);
    committer.add(id3, doc3Content, doc3Metadata);

    committer.commit();

    IOUtils.closeQuietly(doc1Content);
    IOUtils.closeQuietly(doc2Content);
    IOUtils.closeQuietly(doc3Content);

    //Check that there is 2 documents in Solr
    SolrDocumentList results = getAllDocs();
    System.out.println("results " + results.toString());
    assertEquals(2, results.getNumFound());
    System.out.println("Writing/Reading this => " + committer);
}

From source file:com.github.restdriver.clientdriver.unit.ClientDriverResponseTest.java

@Test
public void creatingEmptyResponseHasEmptyStringContentWhenFetchingContentAsString() {

    assertThat(new ClientDriverResponse().getContent(), is(""));
    assertThat(new ClientDriverResponse((String) null, null).getContent(), is(""));
    assertThat(new ClientDriverResponse("", null).getContent(), is(""));
    assertThat(new ClientDriverResponse((InputStream) null, null).getContent(), is(""));
    assertThat(new ClientDriverResponse(IOUtils.toInputStream(""), null).getContent(), is(""));

}

From source file:com.google.code.jerseyclients.asynchttpclient.AsyncHttpClientJerseyClientHandler.java

/**
 * @see com.sun.jersey.api.client.ClientHandler#handle(com.sun.jersey.api.client.ClientRequest)
 *//*w  w w .  ja v  a2  s . c  o m*/
public ClientResponse handle(final ClientRequest clientRequest) throws ClientHandlerException {

    final BoundRequestBuilder boundRequestBuilder = getBoundRequestBuilder(clientRequest);

    PerRequestConfig perRequestConfig = new PerRequestConfig();
    perRequestConfig.setRequestTimeoutInMs(this.jerseyHttpClientConfig.getReadTimeOut());

    if (this.jerseyHttpClientConfig.getProxyInformation() != null) {
        ProxyServer proxyServer = new ProxyServer(jerseyHttpClientConfig.getProxyInformation().getProxyHost(),
                jerseyHttpClientConfig.getProxyInformation().getProxyPort());
        perRequestConfig = new PerRequestConfig(proxyServer, this.jerseyHttpClientConfig.getReadTimeOut());
    }

    boundRequestBuilder.setPerRequestConfig(perRequestConfig);

    if (this.jerseyHttpClientConfig.getApplicationCode() != null) {
        boundRequestBuilder.addHeader(this.jerseyHttpClientConfig.getApplicationCodeHeader(),
                this.jerseyHttpClientConfig.getApplicationCode());
    }
    if (this.jerseyHttpClientConfig.getOptionnalHeaders() != null) {
        for (Entry<String, String> entry : this.jerseyHttpClientConfig.getOptionnalHeaders().entrySet()) {
            boundRequestBuilder.addHeader(entry.getKey(), entry.getValue());
        }
    }

    if (StringUtils.equalsIgnoreCase("POST", clientRequest.getMethod())) {

        if (clientRequest.getEntity() != null) {
            final RequestEntityWriter re = getRequestEntityWriter(clientRequest);

            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            try {
                re.writeRequestEntity(new CommittingOutputStream(baos) {
                    @Override
                    protected void commit() throws IOException {
                        writeOutBoundHeaders(clientRequest.getHeaders(), boundRequestBuilder);
                    }
                });
            } catch (IOException ex) {
                throw new ClientHandlerException(ex);
            }

            boundRequestBuilder.setBody(new ByteArrayInputStream(baos.toByteArray()));

        }
    } else {
        writeOutBoundHeaders(clientRequest.getHeaders(), boundRequestBuilder);
    }
    try {
        StopWatch stopWatch = new StopWatch();
        stopWatch.reset();
        stopWatch.start();
        Future<Response> futureResponse = boundRequestBuilder.execute();
        Response response = futureResponse.get();
        int httpReturnCode = response.getStatusCode();
        stopWatch.stop();
        log.info("time to call rest url " + clientRequest.getURI() + ", " + stopWatch.getTime() + " ms");
        // in case of empty content returned we returned an empty stream
        // to return a null object
        if (httpReturnCode == Status.NO_CONTENT.getStatusCode()) {
            new ClientResponse(httpReturnCode, getInBoundHeaders(response), IOUtils.toInputStream(""),
                    getMessageBodyWorkers());
        }
        return new ClientResponse(httpReturnCode, getInBoundHeaders(response),
                response.getResponseBodyAsStream() == null ? IOUtils.toInputStream("")
                        : response.getResponseBodyAsStream(),
                getMessageBodyWorkers());
    } catch (Exception e) {
        if (e.getCause() != null && (e.getCause() instanceof TimeoutException)) {
            throw new ClientHandlerException(new SocketTimeoutException());
        }
        throw new ClientHandlerException(e);
    }
}

From source file:com.msopentech.odatajclient.testservice.utils.Commons.java

public static InputStream changeFormat(final InputStream is, final Accept target) {
    final ByteArrayOutputStream bos = new ByteArrayOutputStream();

    try {//  w ww.  j  av a  2 s.  co  m
        IOUtils.copy(is, bos);
        IOUtils.closeQuietly(is);

        final ObjectMapper mapper = new ObjectMapper();
        final JsonNode node = changeFormat(
                (ObjectNode) mapper.readTree(new ByteArrayInputStream(bos.toByteArray())), target);

        return IOUtils.toInputStream(node.toString());
    } catch (Exception e) {
        LOG.error("Error changing format", e);
        return new ByteArrayInputStream(bos.toByteArray());
    } finally {
        IOUtils.closeQuietly(is);
    }
}