类org.springframework.util.StreamUtils源码实例Demo

下面列出了怎么用org.springframework.util.StreamUtils的API类实例代码及写法,或者点击链接到github查看源代码。

@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);
}
 
@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());
}
 
源代码3 项目: lams   文件: InterceptingClientHttpRequest.java
@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();
	}
}
 
源代码4 项目: chassis   文件: ClasspathResourceServlet.java
@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);
		}
	}
}
 
源代码5 项目: onetwo   文件: FormHttpMessageConverter.java
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());
	}
}
 
@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);
	}
}
 
@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());
}
 
@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));
}
 
@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);
}
 
源代码10 项目: spring-analysis-note   文件: RestTemplateTests.java
@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();
}
 
@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());
}
 
源代码12 项目: spring-data-examples   文件: GridFsTests.java
@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);
}
 
@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);
}
 
@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);
						});
			});
}
 
@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());
}
 
源代码16 项目: java-technology-stack   文件: RestTemplateTests.java
@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();
}
 
源代码17 项目: java-technology-stack   文件: RestTemplateTests.java
@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();
}
 
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;
		}
	}
}
 
源代码19 项目: hsweb-framework   文件: OAuth2FileService.java
@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);
    }
}
 
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;
}
 
源代码21 项目: spring-cloud-skipper   文件: PackageWriterTests.java
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);
}
 
@Override
public InputStream getBody() throws IOException {
	if (this.body == null) {
		this.body = StreamUtils.copyToByteArray(this.response.getBody());
	}
	return new ByteArrayInputStream(this.body);
}
 
源代码23 项目: tutorials   文件: CopyStreamUnitTest.java
@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);
}
 
@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);
    }
}
 
源代码25 项目: springMvc4.x-project   文件: MyMessageConverter.java
/**
 * ③
 */

@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]);
}
 
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();
}
 
源代码27 项目: spring-cloud-task   文件: AbstractMicrometerTest.java
@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);
}
 
@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);
}
 
@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);
}
 
源代码30 项目: tensorflow   文件: ModelExtractor.java
public byte[] getModel(Resource modelResource) {

		Assert.notNull(modelResource, "Not null model resource is required!");

		try (InputStream is = modelResource.getInputStream();
			 InputStream bi = new BufferedInputStream(is)) {

			String[] archiveCompressor = detectArchiveAndCompressor(modelResource.getFilename());
			String archive = archiveCompressor[0];
			String compressor = archiveCompressor[1];
			String fragment = modelResource.getURI().getFragment();

			if (StringUtils.hasText(compressor)) {
				try (CompressorInputStream cis = new CompressorStreamFactory().createCompressorInputStream(compressor, bi)) {
					if (StringUtils.hasText(archive)) {
						try (ArchiveInputStream ais = new ArchiveStreamFactory().createArchiveInputStream(archive, cis)) {
							// Compressor with Archive
							return findInArchiveStream(fragment, ais);
						}
					}
					else { // Compressor only
						return StreamUtils.copyToByteArray(cis);
					}
				}
			}
			else if (StringUtils.hasText(archive)) { // Archive only
				try (ArchiveInputStream ais = new ArchiveStreamFactory().createArchiveInputStream(archive, bi)) {
					return findInArchiveStream(fragment, ais);
				}
			}
			else {
				// No compressor nor Archive
				return StreamUtils.copyToByteArray(bi);
			}
		}
		catch (Exception e) {
			throw new IllegalStateException("Failed to extract a model from: " + modelResource.getDescription(), e);
		}
	}
 
 类所在包
 同包方法