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.smartitengineering.cms.ws.common.ContentDeSerializationTest.java

public void testDeserializationWithReserialization() throws Exception {
    StringWriter writer = new StringWriter();
    mapper.writeValue(writer, mapper.readValue(IOUtils.toInputStream(CONTENT), ContentImpl.class));
    logger.info("Expected string:\n" + CONTENT);
    logger.info("Output string:\n" + writer.toString());
    JsonNode enode = mapper.readTree(CONTENT);
    JsonNode onode = mapper.readTree(writer.toString());
    assertEquals(enode, onode);/*from   www  .j  av a  2 s .c o m*/
}

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

@Test
public void creatingResponseWithInputStreamReturnsCorrectByteArrayWhenFetchingContent() {
    ClientDriverResponse response = new ClientDriverResponse(IOUtils.toInputStream("some text"),
            "application/octet-stream");

    assertThat(response.getContentAsBytes(), is(("some text").getBytes()));
}

From source file:com.bitplan.w3ccheck.W3CValidator.java

/**
 * create a W3CValidator result for the given url with the given html
 * /* ww w .j av a  2s  .  c om*/
 * @param url - the url of the validator e.g. "http://validator.w3.org/check"
 * @param html - the html code to be checked
 * @return - a W3CValidator response according to the SOAP response format or null if the
 * http response status of the Validation service is other than 200
 * explained at response http://validator.w3.org/docs/api.html#requestformat 
 * @throws JAXBException if there is something wrong with the response message so that it
 * can not be unmarshalled
 */
public static W3CValidator check(String url, String html) throws JAXBException {
    // initialize the return value
    W3CValidator result = null;

    // create a WebResource to access the given url
    WebResource resource = Client.create().resource(url);

    // prepare form data for posting
    FormDataMultiPart form = new FormDataMultiPart();

    // set the output format to soap12
    // triggers the various outputs formats of the validator. If unset, the usual Web format will be sent. 
    // If set to soap12, 
    // the SOAP1.2 interface will be triggered. See the SOAP 1.2 response format description at
    //  http://validator.w3.org/docs/api.html#requestformat
    form.field("output", "soap12");

    // make sure Unicode 0x0 chars are removed from html (if any)
    // see https://github.com/WolfgangFahl/w3cValidator/issues/1
    Pattern pattern = Pattern.compile("[\\000]*");
    Matcher matcher = pattern.matcher(html);
    if (matcher.find()) {
        html = matcher.replaceAll("");
    }

    // The document to validate, POSTed as multipart/form-data
    FormDataBodyPart fdp = new FormDataBodyPart("uploaded_file", IOUtils.toInputStream(html),
            // new FileInputStream(tmpHtml),
            MediaType.APPLICATION_OCTET_STREAM_TYPE);

    // attach the inputstream as upload info to the form
    form.bodyPart(fdp);

    // now post the form via the Internet/Intranet
    ClientResponse response = resource.type(MediaType.MULTIPART_FORM_DATA).post(ClientResponse.class, form);
    // in debug mode show the response status
    if (debug)
        LOGGER.log(Level.INFO, "response status for '" + url + "'=" + response.getStatus());
    // if the http Status is ok
    if (response.getStatus() == 200) {
        // get the XML encoded SOAP 1.2 response format
        String responseXml = response.getEntity(String.class);
        // in debug mode show the full xml 
        if (debug)
            LOGGER.log(Level.INFO, responseXml);
        // unmarshal the xml message to the format to a W3CValidator Java object
        JAXBContext context = JAXBContext.newInstance(W3CValidator.class);
        Unmarshaller u = context.createUnmarshaller();
        StringReader xmlReader = new StringReader(responseXml);
        // this step will convert from xml text to Java Object
        result = (W3CValidator) u.unmarshal(xmlReader);
    }
    // return the result which might be null if the response status was other than 200
    return result;

}

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

private void pushBulkWays() {
    if (bulkInsertWayBuilder == null)
        return;//  w ww . java 2  s  .c  om
    try {
        InputStream is = IOUtils.toInputStream(bulkInsertWayBuilder.toString());
        bulkInsertWay.execute("SET UNIQUE_CHECKS=0; ");
        bulkInsertWay.setLocalInfileInputStream(is);

        bulkInsertWay.execute("LOAD DATA LOCAL INFILE 'file.txt' INTO TABLE ways FIELDS TERMINATED BY '"
                + BULK_DELIMITER + "' (id, tags)");

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

From source file:com.norconex.committer.elasticsearch.ElasticsearchCommitterTest.java

@Test
public void testSetSourceReferenceField() throws Exception {

    String content = "hello world!";
    InputStream is = IOUtils.toInputStream(content);

    // Force to use a reference field instead of the default
    // reference ID.
    String sourceReferenceField = "customId";
    committer.setSourceReferenceField(sourceReferenceField);
    Properties metadata = new Properties();
    String customIdValue = "ABC";
    metadata.setString(sourceReferenceField, customIdValue);

    // Add new doc to ES with a difference id than the one we
    // assigned in source reference field
    committer.add("1", is, metadata);
    committer.commit();//from  w ww .  j  a v a  2  s  . com

    IOUtils.closeQuietly(is);

    // Check that it's in ES using the custom ID
    GetResponse response = client.prepareGet(indexName, typeName, customIdValue).execute().actionGet();
    assertTrue(response.isExists());

    // Check content
    Map<String, Object> responseMap = response.getSource();
    assertEquals(content, responseMap.get(ElasticsearchCommitter.DEFAULT_ES_CONTENT_FIELD));

    // Check custom id field is removed (default behavior)
    assertFalse(response.getSource().containsKey(sourceReferenceField));
}

From source file:gov.nasa.ensemble.resources.TestProjectProperties.java

@Test
public void deleteResourceDeletesProperties() throws CoreException, InterruptedException {
    final String key = "key", val = "val";
    projProps(file).set(key, val);
    file.delete(true, null);//from ww w.  j a  v  a2  s . com
    file.create(IOUtils.toInputStream(""), true, null);
    assertTrue("File retained its project properties across deletion and recreation",
            projProps(file).get(key).isNone());
    Thread.sleep(1000);
    assertFalse(ProjectProperties.propsFolder(file).exists());
}

From source file:com.elasticbox.jenkins.k8s.services.TestSlaveProvisioning.java

@Test
public void testSlaveProvisioningWithoutLabel() throws Exception {

    final KubernetesCloud mockKubernetesCloud = Mockito.mock(KubernetesCloud.class);
    when(mockKubernetesCloud.getInstanceCap()).thenReturn(10);
    when(mockKubernetesCloud.getName()).thenReturn("FakeName");
    when(mockKubernetesCloud.getNamespace()).thenReturn("FakeNamespace");

    final String podYamlDefault = getPodYamlDefault();
    final PodSlaveConfig fakePodSlaveConfig = getFakePodSlaveConfig(podYamlDefault);

    List<PodSlaveConfig> podSlaveConfigurations = new ArrayList<>();
    podSlaveConfigurations.add(fakePodSlaveConfig);

    final Pod pod = new DefaultKubernetesClient().pods().inNamespace(mockKubernetesCloud.getNamespace())
            .load(IOUtils.toInputStream(fakePodSlaveConfig.getPodYaml())).get();

    pod.setStatus(new PodStatus(null, null, null, null, "Running", null, null, null));

    final PodRepository podRepository = injector.getInstance(PodRepository.class);
    when(podRepository.getPod(anyString(), anyString(), anyString())).thenReturn(pod);
    when(podRepository.pod(anyString(), anyString(), anyString())).thenReturn(pod);
    doNothing().when(podRepository).create(anyString(), anyString(), any(Pod.class));

    final List<PodSlaveConfigurationParams> podSlaveConfigurationParams = new ArrayList<>();
    for (PodSlaveConfig config : podSlaveConfigurations) {
        podSlaveConfigurationParams.add(config.getPodSlaveConfigurationParams());
    }/*ww w.ja va  2s  .  c om*/

    final SlaveProvisioningService slaveProvisioningService = injector
            .getInstance(SlaveProvisioningService.class);
    KubernetesSlave kubernetesSlave = slaveProvisioningService.slaveProvision(mockKubernetesCloud,
            podSlaveConfigurationParams, null);

    Assert.assertNotNull("Slave is null.", kubernetesSlave);
    Assert.assertEquals("Node not added to Jenkins.", jenkins.getInstance().getNodes().size(), 1);
}

From source file:com.msopentech.odatajclient.testservice.AbstractServices.java

@PATCH
@Path("/{entitySetName}({entityId})")
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_ATOM_XML, MediaType.APPLICATION_JSON })
@Consumes({ MediaType.APPLICATION_ATOM_XML, MediaType.APPLICATION_JSON })
public Response patchEntity(@HeaderParam("Accept") @DefaultValue(StringUtils.EMPTY) String accept,
        @HeaderParam("Prefer") @DefaultValue(StringUtils.EMPTY) String prefer,
        @HeaderParam("If-Match") @DefaultValue(StringUtils.EMPTY) String ifMatch,
        @PathParam("entitySetName") String entitySetName, @PathParam("entityId") String entityId,
        final String changes) {

    try {//from  w  w w  . ja  v a2s  .  c  o m
        final Accept acceptType = Accept.parse(accept, getVersion());

        if (acceptType == Accept.XML || acceptType == Accept.TEXT) {
            throw new UnsupportedMediaTypeException("Unsupported media type");
        }

        final AbstractUtilities util = acceptType == Accept.ATOM ? xml : json;
        InputStream res = util.patchEntity(entitySetName, entityId, IOUtils.toInputStream(changes), acceptType,
                ifMatch);

        final Response response;
        if ("return-content".equalsIgnoreCase(prefer)) {
            response = xml.createResponse(res, null, acceptType, Response.Status.OK);
        } else {
            res.close();
            response = xml.createResponse(null, null, acceptType, Response.Status.NO_CONTENT);
        }

        if (StringUtils.isNotBlank(prefer)) {
            response.getHeaders().put("Preference-Applied", Collections.<Object>singletonList(prefer));
        }

        return response;
    } catch (Exception e) {
        return xml.createFaultResponse(accept, e);
    }
}

From source file:ee.ria.xroad.opmonitordaemon.QueryRequestHandlerTest.java

/**
 * Ensure that an health data response data is filtered and body is
 * constructed correctly.// w  w  w  .  j  a  v  a  2 s .co  m
 */
@Test
public void handleHealthDataRequest() throws Exception {
    InputStream is = new FileInputStream(HEALTH_DATA_REQUEST);
    SoapParser parser = new SoapParserImpl();
    SoapMessageImpl request = (SoapMessageImpl) parser.parse(MimeTypes.TEXT_XML_UTF8, is);

    QueryRequestHandler handler = new HealthDataRequestHandler(new TestMetricsRegistry());

    OutputStream out = new ByteArrayOutputStream();

    handler.handle(request, out, ct -> testContentType = ct);

    String baseContentType = MimeUtils.getBaseContentType(testContentType);
    assertEquals(MimeTypes.TEXT_XML, baseContentType);

    SoapMessageImpl response = (SoapMessageImpl) parser.parse(MimeTypes.TEXT_XML,
            IOUtils.toInputStream(out.toString()));

    GetSecurityServerHealthDataResponseType responseData = JaxbUtils
            .createUnmarshaller(GetSecurityServerHealthDataResponseType.class)
            .unmarshal(SoapUtils.getFirstChild(response.getSoap().getSOAPBody()),
                    GetSecurityServerHealthDataResponseType.class)
            .getValue();

    assertEquals(TEST_TIMESTAMP, responseData.getMonitoringStartupTimestamp());
    assertEquals(2, responseData.getServicesEvents().getServiceEvents().size());
    assertEquals(ServiceId.create("XTEE-CI-XM", "GOV", "00000001", "System1", "xroad/GetRandom", "v2"),
            responseData.getServicesEvents().getServiceEvents().get(0).getService());
    assertEquals(5, responseData.getServicesEvents().getServiceEvents().get(0).getLastPeriodStatistics()
            .getSuccessfulRequestCount());
    assertEquals(5, responseData.getServicesEvents().getServiceEvents().get(0).getLastPeriodStatistics()
            .getUnsuccessfulRequestCount());
}

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

/**
 * No filename specified by client, so ContentEndpoint generates default filename.
 *
 * @throws Exception//  w  ww.  j  ava2  s. co  m
 */
@Test
public void testParseAttachmentNoFilenameSpecified() 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");
    headers.add(CONTENT_TYPE, "application/json;id=geojson");
    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(ContentEndpoint.DEFAULT_FILE_NAME + "." + ContentEndpoint.DEFAULT_FILE_EXTENSION,
            createInfo.getFilename());
}