Java Code Examples for org.springframework.util.StreamUtils

The following examples show how to use org.springframework.util.StreamUtils. 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
@Override
protected OutputStream getBodyInternal(HttpHeaders headers) throws IOException {
	if (this.body == null) {
		if (this.outputStreaming) {
			long contentLength = headers.getContentLength();
			if (contentLength >= 0) {
				this.connection.setFixedLengthStreamingMode(contentLength);
			}
			else {
				this.connection.setChunkedStreamingMode(this.chunkSize);
			}
		}
		SimpleBufferingClientHttpRequest.addHeaders(this.connection, headers);
		this.connection.connect();
		this.body = this.connection.getOutputStream();
	}
	return StreamUtils.nonClosing(this.body);
}
 
Example 2
Source Project: spring-analysis-note   Source File: ResourceDecoderTests.java    License: MIT License 6 votes vote down vote up
@Override
@Test
public void decode() {
	Flux<DataBuffer> input = Flux.concat(dataBuffer(this.fooBytes), dataBuffer(this.barBytes));

	testDecodeAll(input, Resource.class, step -> step
			.consumeNextWith(resource -> {
				try {
					byte[] bytes = StreamUtils.copyToByteArray(resource.getInputStream());
					assertEquals("foobar", new String(bytes));
				}
				catch (IOException e) {
					fail(e.getMessage());
				}
			})
			.expectComplete()
			.verify());
}
 
Example 3
@Override
public ClientHttpResponse execute(HttpRequest request, byte[] body) throws IOException {
	if (this.iterator.hasNext()) {
		ClientHttpRequestInterceptor nextInterceptor = this.iterator.next();
		return nextInterceptor.intercept(request, body, this);
	}
	else {
		ClientHttpRequest delegate = requestFactory.createRequest(request.getURI(), request.getMethod());
		for (Map.Entry<String, List<String>> entry : request.getHeaders().entrySet()) {
			List<String> values = entry.getValue();
			for (String value : values) {
				delegate.getHeaders().add(entry.getKey(), value);
			}
		}
		if (body.length > 0) {
			StreamUtils.copy(body, delegate.getBody());
		}
		return delegate.execute();
	}
}
 
Example 4
Source Project: chassis   Source File: ClasspathResourceServlet.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
	// figure out the real path
	String pathInfo = StringUtils.trimToEmpty(req.getPathInfo());
	
	while (pathInfo.endsWith("/")) {
		pathInfo = StringUtils.removeEnd(pathInfo, "/");
	}
	
	while (pathInfo.startsWith("/")) {
		pathInfo = StringUtils.removeStart(pathInfo, "/");
	}

	if (StringUtils.isBlank(pathInfo)) {
		resp.sendRedirect(rootContextPath + "/" + welcomePage);
	} else {
		Resource resource = resourceLoader.getResource("classpath:" + classPathDirectory + req.getPathInfo());
		
		if (resource.exists()) {
			StreamUtils.copy(resource.getInputStream(), resp.getOutputStream());
			resp.setStatus(HttpServletResponse.SC_OK);
		} else {
			resp.setStatus(HttpServletResponse.SC_NOT_FOUND);
		}
	}
}
 
Example 5
Source Project: onetwo   Source File: FormHttpMessageConverter.java    License: Apache License 2.0 6 votes vote down vote up
private void writeForm(MultiValueMap<String, String> formData, @Nullable MediaType contentType,
		HttpOutputMessage outputMessage) throws IOException {

	contentType = getMediaType(contentType);
	outputMessage.getHeaders().setContentType(contentType);

	Charset charset = contentType.getCharset();
	Assert.notNull(charset, "No charset"); // should never occur

	final byte[] bytes = serializeForm(formData, charset).getBytes(charset);
	outputMessage.getHeaders().setContentLength(bytes.length);

	if (outputMessage instanceof StreamingHttpOutputMessage) {
		StreamingHttpOutputMessage streamingOutputMessage = (StreamingHttpOutputMessage) outputMessage;
		streamingOutputMessage.setBody(outputStream -> StreamUtils.copy(bytes, outputStream));
	}
	else {
		StreamUtils.copy(bytes, outputMessage.getBody());
	}
}
 
Example 6
Source Project: spring-analysis-note   Source File: SourceHttpMessageConverter.java    License: MIT License 6 votes vote down vote up
@SuppressWarnings("deprecation")  // on JDK 9
private SAXSource readSAXSource(InputStream body, HttpInputMessage inputMessage) throws IOException {
	try {
		XMLReader xmlReader = org.xml.sax.helpers.XMLReaderFactory.createXMLReader();
		xmlReader.setFeature("http://apache.org/xml/features/disallow-doctype-decl", !isSupportDtd());
		xmlReader.setFeature("http://xml.org/sax/features/external-general-entities", isProcessExternalEntities());
		if (!isProcessExternalEntities()) {
			xmlReader.setEntityResolver(NO_OP_ENTITY_RESOLVER);
		}
		byte[] bytes = StreamUtils.copyToByteArray(body);
		return new SAXSource(xmlReader, new InputSource(new ByteArrayInputStream(bytes)));
	}
	catch (SAXException ex) {
		throw new HttpMessageNotReadableException(
				"Could not parse document: " + ex.getMessage(), ex, inputMessage);
	}
}
 
Example 7
@Test
public void lastModifiedWorksWithResourceThatDoesNotSupportFileBasedReading() throws Exception {
	Resource resource = mock(Resource.class);
	// underlying File is asked for so that the last modified time can be checked...
	// And then mock the file changing; i.e. the File says it has been modified
	given(resource.lastModified()).willReturn(100L, 100L, 200L);
	// does not support File-based reading; delegates to InputStream-style reading...
	//resource.getFile();
	//mock.setThrowable(new FileNotFoundException());
	given(resource.getInputStream()).willReturn(StreamUtils.emptyInput());

	ResourceScriptSource scriptSource = new ResourceScriptSource(resource);
	assertTrue("ResourceScriptSource must start off in the 'isModified' state (it obviously isn't).", scriptSource.isModified());
	scriptSource.getScriptAsString();
	assertFalse("ResourceScriptSource must not report back as being modified if the underlying File resource is not reporting a changed lastModified time.", scriptSource.isModified());
	// Must now report back as having been modified
	assertTrue("ResourceScriptSource must report back as being modified if the underlying File resource is reporting a changed lastModified time.", scriptSource.isModified());
}
 
Example 8
Source Project: spring-cloud-skipper   Source File: PackageTemplateTests.java    License: Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void testMustasche() throws IOException {
	Yaml yaml = new Yaml();
	Map model = (Map) yaml.load(valuesResource.getInputStream());
	String templateAsString = StreamUtils.copyToString(nestedMapResource.getInputStream(),
			Charset.defaultCharset());
	Template mustacheTemplate = Mustache.compiler().compile(templateAsString);
	String resolvedYml = mustacheTemplate.execute(model);
	Map map = (Map) yaml.load(resolvedYml);

	logger.info("Resolved yml = " + resolvedYml);
	assertThat(map).containsKeys("apiVersion", "deployment");
	Map deploymentMap = (Map) map.get("deployment");
	assertThat(deploymentMap).contains(entry("name", "time"))
			.contains(entry("count", 10));
	Map applicationProperties = (Map) deploymentMap.get("applicationProperties");
	assertThat(applicationProperties).contains(entry("log.level", "DEBUG"), entry("server.port", 8089));
	Map deploymentProperties = (Map) deploymentMap.get("deploymentProperties");
	assertThat(deploymentProperties).contains(entry("app.time.producer.partitionKeyExpression", "payload"),
			entry("app.log.spring.cloud.stream.bindings.input.consumer.maxAttempts", 5));
}
 
Example 9
@Override
protected OutputStream getBodyInternal(HttpHeaders headers) throws IOException {
	if (this.body == null) {
		if (this.outputStreaming) {
			int contentLength = (int) headers.getContentLength();
			if (contentLength >= 0) {
				this.connection.setFixedLengthStreamingMode(contentLength);
			}
			else {
				this.connection.setChunkedStreamingMode(this.chunkSize);
			}
		}
		SimpleBufferingClientHttpRequest.addHeaders(this.connection, headers);
		this.connection.connect();
		this.body = this.connection.getOutputStream();
	}
	return StreamUtils.nonClosing(this.body);
}
 
Example 10
Source Project: spring-analysis-note   Source File: RestTemplateTests.java    License: MIT License 6 votes vote down vote up
@Test
public void postForObjectNull() throws Exception {
	mockTextPlainHttpMessageConverter();
	HttpHeaders requestHeaders = new HttpHeaders();
	mockSentRequest(POST, "https://example.com", requestHeaders);
	mockResponseStatus(HttpStatus.OK);
	HttpHeaders responseHeaders = new HttpHeaders();
	responseHeaders.setContentType(MediaType.TEXT_PLAIN);
	responseHeaders.setContentLength(10);
	given(response.getHeaders()).willReturn(responseHeaders);
	given(response.getBody()).willReturn(StreamUtils.emptyInput());
	given(converter.read(String.class, response)).willReturn(null);

	String result = template.postForObject("https://example.com", null, String.class);
	assertNull("Invalid POST result", result);
	assertEquals("Invalid content length", 0, requestHeaders.getContentLength());

	verify(response).close();
}
 
Example 11
@Test(expected = IllegalStateException.class)
public void multipleWrites() throws Exception {
	ClientHttpRequest request = factory.createRequest(new URI(baseUrl + "/echo"), HttpMethod.POST);

	final byte[] body = "Hello World".getBytes("UTF-8");
	if (request instanceof StreamingHttpOutputMessage) {
		StreamingHttpOutputMessage streamingRequest = (StreamingHttpOutputMessage) request;
		streamingRequest.setBody(outputStream -> {
			StreamUtils.copy(body, outputStream);
			outputStream.flush();
			outputStream.close();
		});
	}
	else {
		StreamUtils.copy(body, request.getBody());
	}

	request.execute();
	FileCopyUtils.copy(body, request.getBody());
}
 
Example 12
Source Project: spring-data-examples   Source File: GridFsTests.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void shouldStoreAndReadFile() throws IOException {

	byte[] bytes;
	try (InputStream is = new BufferedInputStream(new ClassPathResource("./example-file.txt").getInputStream())) {
		bytes = StreamUtils.copyToByteArray(is);
	}

	// store file
	gridFsOperations.store(new ByteArrayInputStream(bytes), "example-file.txt");

	GridFsResource resource = gridFsOperations.getResource("example-file.txt");

	byte[] loaded;
	try (InputStream is = resource.getInputStream()) {
		loaded = StreamUtils.copyToByteArray(is);
	}

	assertThat(bytes).isEqualTo(loaded);
}
 
Example 13
Source Project: tutorials   Source File: LargeFileDownloadIntegrationTest.java    License: MIT License 6 votes vote down vote up
@Test
public void givenResumableUrl_whenDownloadRange_thenExpectFileSizeEqualOrLessThanRange() {
    int range = 10;
    File file = restTemplate.execute(FILE_URL, HttpMethod.GET, clientHttpRequest -> clientHttpRequest
      .getHeaders()
      .set("Range", String.format("bytes=0-%d", range - 1)), clientHttpResponse -> {
        File ret = File.createTempFile("download", "tmp");
        StreamUtils.copy(clientHttpResponse.getBody(), new FileOutputStream(ret));
        return ret;
    });

    Assert.assertNotNull(file);
    Assertions
      .assertThat(file.length())
      .isLessThanOrEqualTo(range);
}
 
Example 14
Source Project: java-technology-stack   Source File: CssLinkResourceTransformer.java    License: MIT License 6 votes vote down vote up
@SuppressWarnings("deprecation")
@Override
public Mono<Resource> transform(ServerWebExchange exchange, Resource inputResource,
		ResourceTransformerChain transformerChain) {

	return transformerChain.transform(exchange, inputResource)
			.flatMap(outputResource -> {
				String filename = outputResource.getFilename();
				if (!"css".equals(StringUtils.getFilenameExtension(filename)) ||
						inputResource instanceof EncodedResourceResolver.EncodedResource ||
						inputResource instanceof GzipResourceResolver.GzippedResource) {
					return Mono.just(outputResource);
				}

				DataBufferFactory bufferFactory = exchange.getResponse().bufferFactory();
				Flux<DataBuffer> flux = DataBufferUtils
						.read(outputResource, bufferFactory, StreamUtils.BUFFER_SIZE);
				return DataBufferUtils.join(flux)
						.flatMap(dataBuffer -> {
							CharBuffer charBuffer = DEFAULT_CHARSET.decode(dataBuffer.asByteBuffer());
							DataBufferUtils.release(dataBuffer);
							String cssContent = charBuffer.toString();
							return transformContent(cssContent, outputResource, transformerChain, exchange);
						});
			});
}
 
Example 15
Source Project: java-technology-stack   Source File: ResourceDecoderTests.java    License: MIT License 6 votes vote down vote up
@Override
public void decodeToMono() throws Exception {
	Flux<DataBuffer> input = Flux.concat(
			dataBuffer(this.fooBytes),
			dataBuffer(this.barBytes));

	testDecodeToMonoAll(input, Resource.class, step -> step
			.consumeNextWith(resource -> {
				try {
					byte[] bytes = StreamUtils.copyToByteArray(resource.getInputStream());
					assertEquals("foobar", new String(bytes));
				}
				catch (IOException e) {
					fail(e.getMessage());
				}
			})
			.expectComplete()
			.verify());
}
 
Example 16
Source Project: java-technology-stack   Source File: RestTemplateTests.java    License: MIT License 6 votes vote down vote up
@Test
public void patchForObjectNull() throws Exception {
	mockTextPlainHttpMessageConverter();
	HttpHeaders requestHeaders = new HttpHeaders();
	mockSentRequest(PATCH, "http://example.com", requestHeaders);
	mockResponseStatus(HttpStatus.OK);
	HttpHeaders responseHeaders = new HttpHeaders();
	responseHeaders.setContentType(MediaType.TEXT_PLAIN);
	responseHeaders.setContentLength(10);
	given(response.getHeaders()).willReturn(responseHeaders);
	given(response.getBody()).willReturn(StreamUtils.emptyInput());

	String result = template.patchForObject("http://example.com", null, String.class);
	assertNull("Invalid POST result", result);
	assertEquals("Invalid content length", 0, requestHeaders.getContentLength());

	verify(response).close();
}
 
Example 17
Source Project: java-technology-stack   Source File: RestTemplateTests.java    License: MIT License 6 votes vote down vote up
@Test
public void postForObjectNull() throws Exception {
	mockTextPlainHttpMessageConverter();
	HttpHeaders requestHeaders = new HttpHeaders();
	mockSentRequest(POST, "http://example.com", requestHeaders);
	mockResponseStatus(HttpStatus.OK);
	HttpHeaders responseHeaders = new HttpHeaders();
	responseHeaders.setContentType(MediaType.TEXT_PLAIN);
	responseHeaders.setContentLength(10);
	given(response.getHeaders()).willReturn(responseHeaders);
	given(response.getBody()).willReturn(StreamUtils.emptyInput());
	given(converter.read(String.class, response)).willReturn(null);

	String result = template.postForObject("http://example.com", null, String.class);
	assertNull("Invalid POST result", result);
	assertEquals("Invalid content length", 0, requestHeaders.getContentLength());

	verify(response).close();
}
 
Example 18
private void copyRange(InputStream in, OutputStream out, long start, long end) throws IOException {
	long skipped = in.skip(start);
	if (skipped < start) {
		throw new IOException("Skipped only " + skipped + " bytes out of " + start + " required.");
	}

	long bytesToCopy = end - start + 1;
	byte buffer[] = new byte[StreamUtils.BUFFER_SIZE];
	while (bytesToCopy > 0) {
		int bytesRead = in.read(buffer);
		if (bytesRead <= bytesToCopy) {
			out.write(buffer, 0, bytesRead);
			bytesToCopy -= bytesRead;
		}
		else {
			out.write(buffer, 0, (int) bytesToCopy);
			bytesToCopy = 0;
		}
		if (bytesRead == -1) {
			break;
		}
	}
}
 
Example 19
Source Project: hsweb-framework   Source File: OAuth2FileService.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void writeFile(String fileId, OutputStream out, long skip) throws IOException {
    try (InputStream stream = createRequest("/download/" + fileId)
            .header("Range", "bytes=" + skip)
            .get().asStream()) {
        StreamUtils.copy(stream, out);
    }
}
 
Example 20
private String base64EncodeImageData(String filename) {
	String formattedImageData = null;
	ClassPathResource resource = new ClassPathResource(filename);
	try (InputStream stream = resource.getInputStream()) {
		byte[] imageBytes = StreamUtils.copyToByteArray(stream);
		String imageData = Base64Utils.encodeToString(imageBytes);
		formattedImageData = String.format(IMAGE_DATA_FORMAT, imageData);
	}
	catch (IOException e) {
		LOG.warn("Error converting image file to byte array", e);
	}
	return formattedImageData;
}
 
Example 21
Source Project: spring-cloud-skipper   Source File: PackageWriterTests.java    License: Apache License 2.0 5 votes vote down vote up
private void assertExpectedContents(InputStream zipEntryInputStream, String resourceSuffix) throws IOException {
	String zipEntryAsString = StreamUtils.copyToString(zipEntryInputStream, Charset.defaultCharset());
	String expectedYaml = StreamUtils.copyToString(
			TestResourceUtils.qualifiedResource(getClass(), resourceSuffix)
					.getInputStream(),
			Charset.defaultCharset());
	assertThat(zipEntryAsString).isEqualTo(expectedYaml);
}
 
Example 22
@Override
public InputStream getBody() throws IOException {
	if (this.body == null) {
		this.body = StreamUtils.copyToByteArray(this.response.getBody());
	}
	return new ByteArrayInputStream(this.body);
}
 
Example 23
Source Project: tutorials   Source File: CopyStreamUnitTest.java    License: MIT License 5 votes vote down vote up
@Test
public void whenCopyInputStreamToOutputStream_thenCorrect() throws IOException {
    String inputFileName = "src/test/resources/input.txt";
    String outputFileName = "src/test/resources/output.txt";
    File outputFile = new File(outputFileName);
    InputStream in = new FileInputStream(inputFileName);
    OutputStream out = new FileOutputStream(outputFileName);

    StreamUtils.copy(in, out);

    assertTrue(outputFile.exists());
    String inputFileContent = getStringFromInputStream(new FileInputStream(inputFileName));
    String outputFileContent = getStringFromInputStream(new FileInputStream(outputFileName));
    Assert.assertEquals(inputFileContent, outputFileContent);
}
 
Example 24
@Override
public byte[] fileToByteArray(File file) {
    try(InputStream is = new FileInputStream(file)) {
        return StreamUtils.copyToByteArray(is);
    } catch (IOException e) {
        throw new InitializerException("It was not possible to generate project {}", file.getName(), e);
    }
}
 
Example 25
Source Project: springMvc4.x-project   Source File: MyMessageConverter.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * ③
 */

@Override
protected DemoObj readInternal(Class<? extends DemoObj> clazz,
		HttpInputMessage inputMessage) throws IOException,
		HttpMessageNotReadableException {
	String temp = StreamUtils.copyToString(inputMessage.getBody(),

	Charset.forName("UTF-8"));
	String[] tempArr = temp.split("-");
	return new DemoObj(new Long(tempArr[0]), tempArr[1]);
}
 
Example 26
private void write(HttpExchange httpExchange, String content) throws IOException {
	if (content != null) {
		OutputStream outputStream = httpExchange.getResponseBody();
		httpExchange.sendResponseHeaders(200, content.length());
		StreamUtils.copy(URLDecoder.decode(content, "UTF-8"), forName("UTF-8"),
				outputStream);
	}
	httpExchange.close();
}
 
Example 27
Source Project: spring-cloud-task   Source File: AbstractMicrometerTest.java    License: Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static void setup() throws IOException {
	String serviceJson = StreamUtils.copyToString(new DefaultResourceLoader()
			.getResource("classpath:/micrometer/pcf-scs-info.json").getInputStream(),
			Charset.forName("UTF-8"));
	CfEnvTestUtils.mockVcapServicesFromString(serviceJson);
}
 
Example 28
@Override
protected ClientHttpResponse executeInternal(HttpHeaders headers, byte[] bufferedOutput) throws IOException {
	this.request.getHeaders().putAll(headers);
	StreamUtils.copy(bufferedOutput, this.request.getBody());
	ClientHttpResponse response = this.request.execute();
	return new BufferingClientHttpResponseWrapper(response);
}
 
Example 29
@Override
protected ClientHttpResponse executeInternal(HttpHeaders headers, byte[] bufferedOutput) throws IOException {
	this.request.getHeaders().putAll(headers);
	StreamUtils.copy(bufferedOutput, this.request.getBody());
	ClientHttpResponse response = this.request.execute();
	return new BufferingClientHttpResponseWrapper(response);
}
 
Example 30
@Override
protected Resource readInternal(Class<? extends Resource> clazz, HttpInputMessage inputMessage)
		throws IOException, HttpMessageNotReadableException {

	if (InputStreamResource.class == clazz){
		return new InputStreamResource(inputMessage.getBody());
	}
	else if (clazz.isAssignableFrom(ByteArrayResource.class)) {
		byte[] body = StreamUtils.copyToByteArray(inputMessage.getBody());
		return new ByteArrayResource(body);
	}
	else {
		throw new IllegalStateException("Unsupported resource class: " + clazz);
	}
}