Java Code Examples for org.springframework.util.StreamUtils#copyToString()

The following examples show how to use org.springframework.util.StreamUtils#copyToString() . 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 File: LogWriterService.java    From heimdall with Apache License 2.0 6 votes vote down vote up
private String getRequestBody(RequestContext context) {
    try (InputStream in = (InputStream) context.get("requestEntity")) {

        String bodyText;
        if (in == null) {
            bodyText = StreamUtils.copyToString(context.getRequest().getInputStream(), Charset.forName("UTF-8"));
        } else {
            bodyText = StreamUtils.copyToString(in, Charset.forName("UTF-8"));
        }

        return bodyText;
    } catch (Exception e) {

        return null;
    }
}
 
Example 2
Source File: ShellService.java    From cymbal with Apache License 2.0 6 votes vote down vote up
private List<String> execShellScript(final String command) {
    try {
        log.info("Starting to run command '{}'.", command);
        Process process = Runtime.getRuntime().exec(new String[]{"/bin/sh", "-c", command});
        List<String> result = StreamUtil.toList(process.getInputStream(), log);

        // If result from input stream is empty, try to read result from error stream
        int exitValue = process.waitFor();
        if (exitValue != Constant.Shell.EXIT_VALUE_OK) {
            String errorResult = StreamUtils.copyToString(process.getErrorStream(), Charset.defaultCharset());
            throw new ShellExecutionException(errorResult);
        }
        log.info("Run command '{}' finished, result is '{}'.", command, result);
        return result;
    } catch (final IOException | InterruptedException e) {
        throw new ShellExecutionException(e);
    }
}
 
Example 3
Source File: IntegrationTestMain.java    From gemini with Apache License 2.0 5 votes vote down vote up
private void eraseDatabase(Statement statement) throws SQLException, IOException {
    logger.info("Initialization: deleting schema");
    Resource resource = applicationContext.getResource("classpath:erasePublicSchema");
    String eraseDBSql = StreamUtils.copyToString(resource.getInputStream(), StandardCharsets.UTF_8);
    int i = statement.executeUpdate(eraseDBSql);
    logger.info("Initialization: deleting schema - qrs: " + i);
}
 
Example 4
Source File: JacksonEnrollmentService.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public ImportSummaries addEnrollmentsJson( InputStream inputStream, ImportOptions importOptions ) throws IOException
{
    String input = StreamUtils.copyToString( inputStream, Charset.forName( "UTF-8" ) );
    List<Enrollment> enrollments = parseJsonEnrollments( input );

    return addEnrollmentList( enrollments, updateImportOptions( importOptions ) );
}
 
Example 5
Source File: MavenBuildAssertTests.java    From initializr with Apache License 2.0 5 votes vote down vote up
private AssertProvider<MavenBuildAssert> forMavenBuild(String name) {
	try (InputStream in = new ClassPathResource("project/build/maven/" + name).getInputStream()) {
		String content = StreamUtils.copyToString(in, StandardCharsets.UTF_8);
		return () -> new MavenBuildAssert(content);
	}
	catch (IOException ex) {
		throw new IllegalStateException("No content found at " + name, ex);
	}
}
 
Example 6
Source File: DataFilter.java    From xmfcn-spring-cloud with Apache License 2.0 5 votes vote down vote up
/**
 * 修改输出数据
 */
private void modifyResponseBody() {
    try {
        RequestContext context = getCurrentContext();
        InputStream stream = context.getResponseDataStream();
        String body = StreamUtils.copyToString(stream, Charset.forName("UTF-8"));
        context.setResponseBody("Modified via setResponseBody(): " + body);
    } catch (IOException e) {
        rethrowRuntimeException(e);
    }
}
 
Example 7
Source File: CallbackRequestTest.java    From line-bot-sdk-java with Apache License 2.0 5 votes vote down vote up
private void parse(String resourceName, RequestTester callback) throws IOException {
    try (InputStream resource = getClass().getClassLoader().getResourceAsStream(resourceName)) {
        String json = StreamUtils.copyToString(resource, StandardCharsets.UTF_8);
        ObjectMapper objectMapper = TestUtil.objectMapperWithProductionConfiguration(false);
        CallbackRequest callbackRequest = objectMapper.readValue(json, CallbackRequest.class);

        callback.call(callbackRequest);
    }
}
 
Example 8
Source File: DessertMenu.java    From cook with Apache License 2.0 5 votes vote down vote up
public String fetchMenu() throws IOException {
	if (configClient == null) {
		return "none";
	}
	InputStream input = configClient.getConfigFile("cloud", "master", "dessert.json").getInputStream();
	return StreamUtils.copyToString(input, Charset.defaultCharset());
}
 
Example 9
Source File: RaptorErrorDecoder.java    From raptor with Apache License 2.0 5 votes vote down vote up
private String getResponseBodyString(Response response) {
    try {
        return StreamUtils.copyToString(response.body().asInputStream(), StandardCharsets.UTF_8);
    } catch (IOException e) {
        return "error read response body. " + e.getMessage();
    }
}
 
Example 10
Source File: JacksonEnrollmentService.java    From dhis2-core with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public List<Enrollment> getEnrollmentsJson( InputStream inputStream ) throws IOException
{
    String input = StreamUtils.copyToString( inputStream, Charset.forName( "UTF-8" ) );

    return parseJsonEnrollments( input );
}
 
Example 11
Source File: EncryptorFactoryTests.java    From spring-cloud-commons with Apache License 2.0 5 votes vote down vote up
@Test
public void testWithRsaPrivateKey() throws Exception {
	String key = StreamUtils.copyToString(
			new ClassPathResource("/example-test-rsa-private-key").getInputStream(),
			Charset.forName("ASCII"));

	TextEncryptor encryptor = new EncryptorFactory().create(key);
	String toEncrypt = "sample text to encrypt";
	String encrypted = encryptor.encrypt(toEncrypt);

	then(encryptor.decrypt(encrypted)).isEqualTo(toEncrypt);
}
 
Example 12
Source File: ProjectGenerationStatPublisherTests.java    From initializr with Apache License 2.0 5 votes vote down vote up
private static String readJson(String location) {
	try {
		try (InputStream in = new ClassPathResource(location).getInputStream()) {
			return StreamUtils.copyToString(in, StandardCharsets.UTF_8);
		}
	}
	catch (IOException ex) {
		throw new IllegalStateException("Fail to read json from " + location, ex);
	}
}
 
Example 13
Source File: AbstractTemplateTest.java    From booties with Apache License 2.0 4 votes vote down vote up
public static String resourceToString(Resource resource) throws IOException {
	return StreamUtils.copyToString(resource.getInputStream(), Charset.defaultCharset());
}
 
Example 14
Source File: GensonHttpMessageConverter.java    From SmartApplianceEnabler with GNU General Public License v2.0 4 votes vote down vote up
@Override
public Object read(Class toType, HttpInputMessage httpInputMessage) throws IOException, HttpMessageNotReadableException {
    logger.debug("Deserializing JSON to " + toType);
    String body = StreamUtils.copyToString(httpInputMessage.getBody(), Charset.defaultCharset());
    return this.genson.deserialize(body, toType);
}
 
Example 15
Source File: StubRunnerJUnit5ExtensionCustomPortTests.java    From spring-cloud-contract with Apache License 2.0 4 votes vote down vote up
private String httpGet(String url) throws Exception {
	try (InputStream stream = URI.create(url).toURL().openStream()) {
		return StreamUtils.copyToString(stream, Charset.forName("UTF-8"));
	}
}
 
Example 16
Source File: StatedRelationshipToOwlRefsetServiceTest.java    From snomed-owl-toolkit with Apache License 2.0 4 votes vote down vote up
@Test
public void convertStatedRelationshipsToOwlRefset() throws IOException, OWLOntologyCreationException, ConversionException {
	File baseRF2SnapshotZip = ZipUtil.zipDirectoryRemovingCommentsAndBlankLines("src/test/resources/SnomedCT_MiniRF2_Base_snapshot");
	File rF2DeltaZip = ZipUtil.zipDirectoryRemovingCommentsAndBlankLines("src/test/resources/SnomedCT_MiniRF2_Add_Diabetes_delta");
	ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
	service.convertStatedRelationshipsToOwlRefsetAndInactiveRelationshipsArchive(new FileInputStream(baseRF2SnapshotZip), new OptionalFileInputStream(rF2DeltaZip),
			byteArrayOutputStream, "20180931");

	// Read files from zip
	String owlRefset;
	String statedRelationships;
	try (ZipInputStream zipInputStream = new ZipInputStream(new ByteArrayInputStream(byteArrayOutputStream.toByteArray()))) {
		ZipEntry nextEntry = zipInputStream.getNextEntry();
		assertEquals("sct2_StatedRelationship_Delta_INT_20180931.txt", nextEntry.getName());
		statedRelationships = StreamUtils.copyToString(zipInputStream, Charset.forName("UTF-8"));

		nextEntry = zipInputStream.getNextEntry();
		assertEquals("sct2_sRefset_OWLAxiomDelta_INT_20180931.txt", nextEntry.getName());
		owlRefset = StreamUtils.copyToString(zipInputStream, Charset.forName("UTF-8"));
	}


	assertFalse("Output should not contain the snomed axiom prefix", owlRefset.contains("<http://snomed.info/id/"));

	// Sequential identifiers used in this test rather than random UUIDs
	assertEquals(
			"id\teffectiveTime\tactive\tmoduleId\trefsetId\treferencedComponentId\towlExpression\n" +
			"1\t\t1\t900000000000012004\t733073007\t410662002\tSubClassOf(:410662002 :900000000000441003)\n" +
			"2\t\t1\t900000000000012004\t733073007\t116680003\tSubClassOf(:116680003 :900000000000441003)\n" +
			"3\t\t1\t900000000000012004\t733073007\t723594008\tSubClassOf(:723594008 :900000000000441003)\n" +
			"4\t\t1\t900000000000012004\t733073007\t762705008\tSubClassOf(:762705008 :410662002)\n" +
			"5\t\t1\t900000000000207008\t733073007\t73211009\tSubClassOf(:73211009 :362969004)\n" +
			"6\t\t1\t900000000000012004\t733073007\t900000000000441003\tSubClassOf(:900000000000441003 :138875005)\n" +
			"7\t\t1\t900000000000207008\t733073007\t362969004\tEquivalentClasses(:362969004 ObjectIntersectionOf(:404684003 ObjectSomeValuesFrom(:609096000 ObjectSomeValuesFrom(:363698007 :113331007))))\n" +
			"8\t\t1\t900000000000012004\t733073007\t723596005\tSubClassOf(:723596005 :723594008)\n" +
			"9\t\t1\t900000000000012004\t733073007\t762706009\tSubClassOf(:762706009 :410662002)\n" +
			"10\t\t1\t900000000000207008\t733073007\t404684003\tSubClassOf(:404684003 :138875005)\n" +
			"11\t\t1\t900000000000012004\t733073007\t363698007\tSubObjectPropertyOf(:363698007 :762705008)\n" +
			"12\t\t1\t900000000000207008\t733073007\t113331007\tSubClassOf(:113331007 :138875005)\n",
			owlRefset);

	assertEquals(
			"id\teffectiveTime\tactive\tmoduleId\tsourceId\tdestinationId\trelationshipGroup\ttypeId\tcharacteristicTypeId\tmodifierId\n" +
			"100001001\t\t0\t900000000000012004\t900000000000441003\t138875005\t0\t116680003\t900000000000010007\t900000000000451002\n" +
			"100005001\t\t0\t900000000000012004\t410662002\t900000000000441003\t0\t116680003\t900000000000010007\t900000000000451002\n" +
			"100001101\t\t0\t900000000000012004\t762705008\t410662002\t0\t116680003\t900000000000010007\t900000000000451002\n" +
			"100001201\t\t0\t900000000000012004\t762706009\t410662002\t0\t116680003\t900000000000010007\t900000000000451002\n" +
			"100002001\t\t0\t900000000000012004\t116680003\t900000000000441003\t0\t116680003\t900000000000010007\t900000000000451002\n" +
			"100003001\t\t0\t900000000000012004\t723594008\t900000000000441003\t0\t116680003\t900000000000010007\t900000000000451002\n" +
			"100004001\t\t0\t900000000000012004\t723596005\t723594008\t0\t116680003\t900000000000010007\t900000000000451002\n" +
			"100006001\t\t0\t900000000000012004\t363698007\t762705008\t0\t116680003\t900000000000010007\t900000000000451002\n" +
			"100007001\t\t0\t900000000000207008\t113331007\t138875005\t0\t116680003\t900000000000010007\t900000000000451002\n" +
			"100008001\t\t0\t900000000000207008\t404684003\t138875005\t0\t116680003\t900000000000010007\t900000000000451002\n" +
			"100009001\t\t0\t900000000000207008\t362969004\t404684003\t0\t116680003\t900000000000010007\t900000000000451002\n" +
			"100010001\t\t0\t900000000000207008\t362969004\t113331007\t0\t363698007\t900000000000010007\t900000000000451002\n",
			statedRelationships);
}
 
Example 17
Source File: StringHttpMessageConverter.java    From java-technology-stack with MIT License 4 votes vote down vote up
@Override
protected String readInternal(Class<? extends String> clazz, HttpInputMessage inputMessage) throws IOException {
	Charset charset = getContentTypeCharset(inputMessage.getHeaders().getContentType());
	return StreamUtils.copyToString(inputMessage.getBody(), charset);
}
 
Example 18
Source File: DefaultStreamServiceIntegrationTests.java    From spring-cloud-dataflow with Apache License 2.0 4 votes vote down vote up
@Test
public void testUpdateStreamDslOnRollback() throws IOException {

	// Create stream
	StreamDefinition streamDefinition = new StreamDefinition("ticktock",
			"time --fixed-delay=100 | log --level=DEBUG");
	this.streamDefinitionRepository.deleteById(streamDefinition.getName());
	this.streamDefinitionRepository.save(streamDefinition);

	when(skipperClient.status(eq("ticktock"))).thenThrow(new ReleaseNotFoundException(""));

	streamService.deployStream("ticktock", createSkipperDeploymentProperties());

	// Update Stream
	StreamDefinition streamDefinitionBeforeDeploy = this.streamDefinitionRepository.findById("ticktock").get();
	assertThat(streamDefinitionBeforeDeploy.getDslText())
			.isEqualTo("time --fixed-delay=100 | log --level=DEBUG");

	String expectedReleaseManifest = StreamUtils.copyToString(
			TestResourceUtils.qualifiedResource(getClass(), "upgradeManifest.yml").getInputStream(),
			Charset.defaultCharset());
	Release release = new Release();
	Manifest manifest = new Manifest();
	manifest.setData(expectedReleaseManifest);
	release.setManifest(manifest);
	when(skipperClient.upgrade(isA(UpgradeRequest.class))).thenReturn(release);

	Map<String, String> deploymentProperties = createSkipperDeploymentProperties();
	deploymentProperties.put("version.log", "1.2.0.RELEASE");
	streamService.updateStream("ticktock",
			new UpdateStreamRequest("ticktock", new PackageIdentifier(), deploymentProperties));

	StreamDefinition streamDefinitionAfterDeploy = this.streamDefinitionRepository.findById("ticktock").get();
	assertThat(streamDefinitionAfterDeploy.getDslText())
			.isEqualTo("time --trigger.fixed-delay=200 | log --log.level=INFO");

	// Rollback Stream
	String rollbackReleaseManifest = StreamUtils.copyToString(
			TestResourceUtils.qualifiedResource(getClass(), "rollbackManifest.yml").getInputStream(),
			Charset.defaultCharset());
	Release rollbackRelease = new Release();
	Manifest rollbackManifest = new Manifest();
	rollbackManifest.setData(rollbackReleaseManifest);
	rollbackRelease.setManifest(rollbackManifest);
	when(skipperClient.rollback(isA(RollbackRequest.class))).thenReturn(rollbackRelease);

	streamService.rollbackStream("ticktock", 0);
	StreamDefinition streamDefinitionAfterRollback = this.streamDefinitionRepository.findById("ticktock").get();
	assertThat(streamDefinitionAfterRollback.getDslText())
			.isEqualTo("time --trigger.fixed-delay=100 | log --log.level=DEBUG");
}
 
Example 19
Source File: FredAnnotator.java    From gerbil with GNU Affero General Public License v3.0 4 votes vote down vote up
protected Reader replaceDenotesUri(InputStream content) throws IOException {
    String response = StreamUtils.copyToString(content, CHARSET);
    response = response.replaceAll(FRED_DENOTES_URI, ITSRDF.taIdentRef.getURI());
    return new StringReader(response);
}
 
Example 20
Source File: StringHttpMessageConverter.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
@Override
protected String readInternal(Class<? extends String> clazz, HttpInputMessage inputMessage) throws IOException {
	Charset charset = getContentTypeCharset(inputMessage.getHeaders().getContentType());
	return StreamUtils.copyToString(inputMessage.getBody(), charset);
}