Java Code Examples for org.apache.commons.io.IOUtils#toString()

The following examples show how to use org.apache.commons.io.IOUtils#toString() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: data-prep   File: SuggestionTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void integerColumnSuggest() throws Exception {
    // given
    final String columnMetadata =
            IOUtils.toString(Application.class.getResourceAsStream("suggestions/integer_column.json"), UTF_8);
    final String expectedSuggestions = IOUtils
            .toString(Application.class.getResourceAsStream("suggestions/integer_column_suggestions.json"), UTF_8);

    // when
    final String response = given() //
            .contentType(JSON) //
            .body(columnMetadata) //
            .when() //
            .post("/suggest/column?limit=9") //
            .asString();

    // then
    assertEquals(expectedSuggestions, response, false);
}
 
Example 2
Source Project: knox   File: JsonFilterReaderTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testNamesWithDots() throws IOException {
  InputStream stream = TestUtils.getResourceStream( this.getClass(), "dotted-field-name.json" );
  String input = IOUtils.toString( stream, StandardCharsets.UTF_8 );

  UrlRewriteRulesDescriptor rulesConfig = UrlRewriteRulesDescriptorFactory.create();
  UrlRewriteFilterDescriptor filterConfig = rulesConfig.addFilter( "test-filter" );
  UrlRewriteFilterContentDescriptor contentConfig = filterConfig.addContent( "application/json" );
  //NOTE: The field names are rewritten first so the values rules need to match the rewritten name.
  contentConfig.addApply( "$.name<testField>", "test-rule" );
  contentConfig.addApply( "$.name<test_field>", "test-rule" );
  contentConfig.addApply( "$.name<test-field>", "test-rule" );
  contentConfig.addApply( "$['name<test.field>']", "test-rule" );

  JsonFilterReader filter = new TestJsonFilterReader( new StringReader( input ), contentConfig );
  String output = IOUtils.toString( filter );

  JsonAssert.with( output ).assertThat( "$['name<testField>']", is( "value:test-rule<testField value>" ) );
  JsonAssert.with( output ).assertThat( "$['name<test_field>']", is( "value:test-rule<test_field value>" ) );
  JsonAssert.with( output ).assertThat( "$['name<test-field>']", is( "value:test-rule<test-field value>" ) );
  JsonAssert.with( output ).assertThat( "$['name<test.field>']", is( "value:test-rule<test.field value>" ) );
}
 
Example 3
/**
 * Call the conduit API of Phabricator
 *
 * @param action Name of the API call
 * @param params The data to send to Harbormaster
 * @return The result as a JSONObject
 * @throws IOException If there was a problem reading the response
 * @throws ConduitAPIException If there was an error calling conduit
 */
public JSONObject perform(String action, JSONObject params) throws IOException, ConduitAPIException {
    CloseableHttpClient client = HttpClientBuilder.create().build();
    HttpUriRequest request = createRequest(action, params);

    HttpResponse response;
    try {
        response = client.execute(request);
    } catch (ClientProtocolException e) {
        throw new ConduitAPIException(e.getMessage());
    }

    InputStream responseBody = response.getEntity().getContent();

    if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
        throw new ConduitAPIException(IOUtils.toString(responseBody, Charset.defaultCharset()), response.getStatusLine().getStatusCode());
    }

    JsonSlurper jsonParser = new JsonSlurper();
    return (JSONObject) jsonParser.parse(responseBody);
}
 
Example 4
@Test
public void multipleValuesInAcceptHeaderWithIncorrectParam() throws Exception {
  URL url = new URL(SERVICE_URI + "ESAllPrim");

  HttpURLConnection connection = (HttpURLConnection) url.openConnection();
  connection.setRequestMethod(HttpMethod.GET.name());
  connection.setRequestProperty(HttpHeader.ACCEPT, "application/json,"
      + "application/json;q=0.1,application/json;q=<1");
  connection.connect();

  assertEquals(HttpStatusCode.BAD_REQUEST.getStatusCode(), connection.getResponseCode());

  final String content = IOUtils.toString(connection.getErrorStream());
  assertTrue(content.contains("The content-type range 'application/json;q=<1' is not "
      + "supported as value of the Accept header."));
}
 
Example 5
public FormatterPreview(Composite parent, String resFileName, XdsSourceType xdsSourceType) {
    super(parent, SWT.MULTI | SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL | SWT.READ_ONLY);
    this.xdsSourceType = xdsSourceType;
    this.styledText = this.getTextWidget();
    
    String resPath = RESOURCE_FOLDER_LOCATION + resFileName; 
    try(InputStream resourceStream = ResourceUtils.getPluginResourceAsStream(ResourceUtils.getXdsResourcesPluginBundle(), resPath)) {
    	this.initialText = IOUtils.toString(resourceStream);
    } 
    catch (Exception e) {
        this.initialText = "** Internal error: can't read " + resPath + "\n** Preview not available"; //$NON-NLS-1$ //$NON-NLS-2$
    }

    Font font= JFaceResources.getTextFont();
    styledText.setFont(font);
    defBackgroundColor = getEditorBackgroundColor(EditorsPlugin.getDefault().getPreferenceStore());
    styledText.setBackground(defBackgroundColor);
    
    styledText.setText(initialText);
    colorIt();
}
 
Example 6
Source Project: registry   File: DbFileStorageTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testUpdate() throws Exception {
    try {
        transactionManager.beginTransaction(TransactionIsolation.SERIALIZABLE);
        String input = IOUtils.toString(this.getClass().getClassLoader().getResourceAsStream(FILE_NAME), "UTF-8");
        dbFileStorage.upload(IOUtils.toInputStream(input, "UTF-8"), FILE_NAME);
        String update = input + " new text";
        dbFileStorage.upload(IOUtils.toInputStream(update, "UTF-8"), FILE_NAME);
        InputStream is = dbFileStorage.download(FILE_NAME);
        String output = IOUtils.toString(is, "UTF-8");
        Assert.assertEquals(update, output);
        transactionManager.commitTransaction();
    } catch (Exception e) {
        transactionManager.rollbackTransaction();
        throw e;
    }
}
 
Example 7
@Test
public void preferHeaderMinimal_PostMediaEntity() throws Exception {
  URL url = new URL(SERVICE_URI + "ESMedia");

  HttpURLConnection connection = (HttpURLConnection) url.openConnection();
  connection.setRequestMethod(HttpMethod.POST.name());
  connection.setRequestProperty(HttpHeader.PREFER, "return=minimal");
  connection.setRequestProperty(HttpHeader.CONTENT_TYPE, "application/json");
  connection.setRequestProperty(HttpHeader.ACCEPT, "application/json");
  connection.connect();

  assertEquals(HttpStatusCode.BAD_REQUEST.getStatusCode(), connection.getResponseCode());
  final String content = IOUtils.toString(connection.getErrorStream());
  assertTrue(content.contains("The Prefer header 'return=minimal' is not supported for this HTTP Method."));
  
}
 
Example 8
Source Project: data-prep   File: TransformAPITest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testSuggestActionParams_should_return_dynamic_params_with_preparation_head() throws Exception {
    // given
    final String preparationId = testClient.createPreparationFromFile("transformation/cluster_dataset.csv",
            "testClustering", home.getId());
    final String expectedClusterParameters = IOUtils.toString(
            this.getClass().getResourceAsStream("transformation/expected_cluster_params_double_metaphone.json"),
            UTF_8);

    // update cache preparation
    testClient.getPreparation(preparationId);

    // when
    final String actualClusterParameters = given()
            .formParam("preparationId", preparationId)
            .formParam("columnId", "0001")
            .when()
            .get("/api/transform/suggest/textclustering/params")
            .asString();

    // then
    assertThat(actualClusterParameters, sameJSONAs(expectedClusterParameters).allowingAnyArrayOrdering());
}
 
Example 9
Source Project: herd   File: JobServiceTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testGetJobIntermediateTimer() throws Exception
{
    jobDefinitionServiceTestHelper.createJobDefinition(ACTIVITI_XML_HERD_INTERMEDIATE_TIMER_WITH_CLASSPATH);

    Job job = jobService.createAndStartJob(jobServiceTestHelper.createJobCreateRequest(TEST_ACTIVITI_NAMESPACE_CD, TEST_ACTIVITI_JOB_NAME));

    String activitiXml = IOUtils.toString(resourceLoader.getResource(ACTIVITI_XML_HERD_INTERMEDIATE_TIMER_WITH_CLASSPATH).getInputStream());
    // Job should be waiting at User task.

    // Get job status
    Job jobGet = jobService.getJob(job.getId(), true);
    assertEquals(JobStatusEnum.RUNNING, jobGet.getStatus());
    assertNotNull(jobGet.getActivitiJobXml());
    assertEquals(activitiXml, jobGet.getActivitiJobXml());
    assertTrue(jobGet.getCompletedWorkflowSteps().size() > 0);
    // Current workflow step will be null
    assertNull(jobGet.getCurrentWorkflowStep());

    org.activiti.engine.runtime.Job timer = activitiManagementService.createJobQuery().processInstanceId(job.getId()).timers().singleResult();
    if (timer != null)
    {
        activitiManagementService.executeJob(timer.getId());
    }

    // Get the job status again. job should have completed now.
    jobGet = jobService.getJob(job.getId(), false);
    assertEquals(JobStatusEnum.COMPLETED, jobGet.getStatus());
    assertNull(jobGet.getCurrentWorkflowStep());
}
 
Example 10
Source Project: product-ei   File: FTPClientWrapper.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Function to read a file in an FTP server
 *
 * @param filePath absolute file path
 * @return String value of the file content
 * @throws IOException if retrieving file stream fails
 */
public String readFile(String filePath) throws IOException {
    String fileContent;
    try (InputStream inputStream = ftpClient.retrieveFileStream(filePath)){
        fileContent = IOUtils.toString(inputStream, "UTF-8");
    } catch (IOException ex) {
        throw new IOException("Error occurred while retrieving file stream " + filePath, ex);
    }
    return fileContent;
}
 
Example 11
Source Project: incubator-pinot   File: S3PinotFSTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testOpenFile()
    throws Exception {
  String fileName = "sample.txt";
  String fileContent = "Hello, World";

  _s3Client.putObject(S3TestUtils.getPutObjectRequest(BUCKET, fileName), RequestBody.fromString(fileContent));

  InputStream is = _s3PinotFS.open(URI.create(String.format(FILE_FORMAT, SCHEME, BUCKET, fileName)));
  String actualContents = IOUtils.toString(is, StandardCharsets.UTF_8);
  Assert.assertEquals(actualContents, fileContent);
}
 
Example 12
Source Project: james-project   File: ListMessageAssert.java    License: Apache License 2.0 5 votes vote down vote up
private InnerMessage getInnerMessage(MailboxMessage message) {
    try {
        return new InnerMessage(message.getMessageId(), message.getUid(), message.getMailboxId(), message.getInternalDate(), message.getBodyOctets(),
                message.getFullContentOctets(), message.getMediaType(), message.getSubType(), IOUtils.toString(message.getFullContent(), StandardCharsets.UTF_8));
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example 13
@Test
public void preferHeaderRepresentation_PutMediaEntity() throws Exception {
  URL url = new URL(SERVICE_URI + "ESMedia(1)");

  HttpURLConnection connection = (HttpURLConnection) url.openConnection();
  connection.setRequestMethod(HttpMethod.PUT.name());
  connection.setRequestProperty(HttpHeader.PREFER, "return=representation");
  connection.connect();

  assertEquals(HttpStatusCode.BAD_REQUEST.getStatusCode(), connection.getResponseCode());
  final String content = IOUtils.toString(connection.getErrorStream());
  assertTrue(content.contains("The Prefer header 'return=representation' is not supported for this HTTP Method."));
  
}
 
Example 14
@Test
public void shouldEscapeBadXmlCharacters() throws Exception {
    StringReader reader = new StringReader(String.format(PATTERN, "\u0014", "\u0011", "\u0018"));
    String escaped = IOUtils.toString(new BadXmlCharacterFilterReader(reader));

    assertEquals(escaped, String.format(PATTERN, " ", " ", " "));
}
 
Example 15
@Override
public MonetaryAmount readFrom(Class<MonetaryAmount> type,
		Type genericType, Annotation[] annotations, MediaType mediaType,
		MultivaluedMap<String, String> httpHeaders, InputStream entityStream)
		throws IOException, WebApplicationException {

	String text = IOUtils.toString(entityStream);
	return Money.parse(text);
}
 
Example 16
Source Project: cuba   File: CompositeDescriptorLoader.java    License: Apache License 2.0 5 votes vote down vote up
protected String loadDescriptor(String resourcePath) {
    try (InputStream stream = resources.getResourceAsStream(resourcePath)) {
        if (stream == null) {
            throw new DevelopmentException("Composite component descriptor not found " + resourcePath, "Path", resourcePath);
        }
        return IOUtils.toString(stream, StandardCharsets.UTF_8);
    } catch (IOException e) {
        throw new RuntimeException("Unable to read composite component descriptor");
    }
}
 
Example 17
/**
 * Parse response from java.io.Reader.
 */
@Test
public void testReaderResponse() throws Exception {
  NoOpResponseParser parser = new NoOpResponseParser();
  try (final InputStream is = getResponse()) {
    assertNotNull(is);
    Reader in = new InputStreamReader(is, StandardCharsets.UTF_8);
    NamedList<Object> response = parser.processResponse(in);
    assertNotNull(response.get("response"));
    String expectedResponse = IOUtils.toString(getResponse(), "UTF-8");
    assertEquals(expectedResponse, response.get("response"));
  }

}
 
Example 18
Source Project: weixin-sdk   File: QyXmlMessagesTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testXmlToClickEvent() throws IOException {
    String xml = IOUtils.toString(this.getClass().getClassLoader().getResourceAsStream("message/event/click.xml"));

    XmlMessageHeader xmlRequest = QyXmlMessages.fromXml(xml);

    Assert.assertNotNull(xmlRequest);
    Assert.assertTrue(xmlRequest instanceof QyClickEvent);

    Assert.assertEquals("EVENTKEY", ((QyClickEvent) xmlRequest).getEventKey());
}
 
Example 19
@Test
public void web_page_contents_apache() throws IOException,
		URISyntaxException {

	URL url = new URL("http://www.example.com/");
	String pageContents = IOUtils.toString(url, Charsets.UTF_8);

	logger.info(pageContents);

	assertNotNull(pageContents);

	// or

	URI uri = new URI("http://www.example.com/");
	String siteContents = IOUtils.toString(uri, Charsets.UTF_8);

	logger.info(siteContents);

	assertNotNull(siteContents);
}
 
Example 20
Source Project: drools-workshop   File: PhreakInspector.java    License: Apache License 2.0 3 votes vote down vote up
private InputStream generateGraphViz(Map<Integer, Node> nodes) throws IOException {

        String template = IOUtils.toString(PhreakInspector.class
                .getResourceAsStream("/templates/viz.template"));
        ST st = new ST(template, '$', '$');
        st.add("items", nodes.values());

        Map<String, List<Node>> itemsByGroup = nodes.values().stream().collect(Collectors.groupingBy(n -> n.getType().getGroup()));
        st.add("itemsByGroup", itemsByGroup);

        return new ByteArrayInputStream(st.render().getBytes());

    }