org.springframework.util.StreamUtils Java Examples

The following examples show how to use org.springframework.util.StreamUtils. 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: ClasspathResourceServlet.java    From chassis with 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 #2
Source File: SourceHttpMessageConverter.java    From spring-analysis-note with 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 #3
Source File: FormHttpMessageConverter.java    From onetwo with 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 #4
Source File: GridFsTests.java    From spring-data-examples with 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 #5
Source File: LargeFileDownloadIntegrationTest.java    From tutorials with 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 #6
Source File: SimpleStreamingAsyncClientHttpRequest.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@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 #7
Source File: CssLinkResourceTransformer.java    From java-technology-stack with 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 #8
Source File: RestTemplateTests.java    From spring-analysis-note with 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 #9
Source File: ResourceDecoderTests.java    From java-technology-stack with 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 #10
Source File: RestTemplateTests.java    From java-technology-stack with 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 #11
Source File: InterceptingClientHttpRequest.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@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 #12
Source File: ResourceDecoderTests.java    From spring-analysis-note with 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 #13
Source File: RestTemplateTests.java    From java-technology-stack with 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 #14
Source File: PackageTemplateTests.java    From spring-cloud-skipper with 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 #15
Source File: AbstractHttpRequestFactoryTestCase.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@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 #16
Source File: ResourceHttpRequestHandler.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
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 #17
Source File: SimpleStreamingAsyncClientHttpRequest.java    From java-technology-stack with MIT License 6 votes vote down vote up
@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 #18
Source File: ResourceScriptSourceTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@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 #19
Source File: ResponseCreatorsTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void unauthorized() throws Exception {
	DefaultResponseCreator responseCreator = MockRestResponseCreators.withUnauthorizedRequest();
	MockClientHttpResponse response = (MockClientHttpResponse) responseCreator.createResponse(null);

	assertEquals(HttpStatus.UNAUTHORIZED, response.getStatusCode());
	assertTrue(response.getHeaders().isEmpty());
	assertEquals(0, StreamUtils.copyToByteArray(response.getBody()).length);
}
 
Example #20
Source File: ResponseCreatorsTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void created() throws Exception {
	URI location = new URI("/foo");
	DefaultResponseCreator responseCreator = MockRestResponseCreators.withCreatedEntity(location);
	MockClientHttpResponse response = (MockClientHttpResponse) responseCreator.createResponse(null);

	assertEquals(HttpStatus.CREATED, response.getStatusCode());
	assertEquals(location, response.getHeaders().getLocation());
	assertEquals(0, StreamUtils.copyToByteArray(response.getBody()).length);
}
 
Example #21
Source File: AbstractAsyncHttpRequestFactoryTestCase.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void echo() throws Exception {
	AsyncClientHttpRequest request = this.factory.createAsyncRequest(new URI(baseUrl + "/echo"), HttpMethod.PUT);
	assertEquals("Invalid HTTP method", HttpMethod.PUT, request.getMethod());
	String headerName = "MyHeader";
	String headerValue1 = "value1";
	request.getHeaders().add(headerName, headerValue1);
	String headerValue2 = "value2";
	request.getHeaders().add(headerName, headerValue2);
	final byte[] body = "Hello World".getBytes("UTF-8");
	request.getHeaders().setContentLength(body.length);

	if (request instanceof StreamingHttpOutputMessage) {
		StreamingHttpOutputMessage streamingRequest = (StreamingHttpOutputMessage) request;
		streamingRequest.setBody(outputStream -> StreamUtils.copy(body, outputStream));
	}
	else {
		StreamUtils.copy(body, request.getBody());
	}

	Future<ClientHttpResponse> futureResponse = request.executeAsync();
	ClientHttpResponse response = futureResponse.get();
	try {
		assertEquals("Invalid status code", HttpStatus.OK, response.getStatusCode());
		assertTrue("Header not found", response.getHeaders().containsKey(headerName));
		assertEquals("Header value not found", Arrays.asList(headerValue1, headerValue2),
				response.getHeaders().get(headerName));
		byte[] result = FileCopyUtils.copyToByteArray(response.getBody());
		assertTrue("Invalid body", Arrays.equals(body, result));
	}
	finally {
		response.close();
	}
}
 
Example #22
Source File: XpathResultMatchersTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void stringEncodingDetection() throws Exception {
	String content = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n" +
			"<person><name>Jürgen</name></person>";
	byte[] bytes = content.getBytes(StandardCharsets.UTF_8);
	MockHttpServletResponse response = new MockHttpServletResponse();
	response.addHeader("Content-Type", "application/xml");
	StreamUtils.copy(bytes, response.getOutputStream());
	StubMvcResult result = new StubMvcResult(null, null, null, null, null, null, response);

	new XpathResultMatchers("/person/name", null).string("Jürgen").match(result);
}
 
Example #23
Source File: ContentVersionStrategy.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
public Mono<String> getResourceVersion(Resource resource) {
	Flux<DataBuffer> flux =
			DataBufferUtils.read(resource, dataBufferFactory, StreamUtils.BUFFER_SIZE);
	return DataBufferUtils.join(flux)
			.map(buffer -> {
				byte[] result = new byte[buffer.readableByteCount()];
				buffer.read(result);
				DataBufferUtils.release(buffer);
				return DigestUtils.md5DigestAsHex(result);
			});
}
 
Example #24
Source File: PackageService.java    From spring-cloud-skipper with Apache License 2.0 5 votes vote down vote up
private Package deserializePackageFromDatabase(PackageMetadata packageMetadata) {
	// package file was uploaded to a local DB hosted repository
	Path tmpDirPath = null;
	try {
		tmpDirPath = TempFileUtils.createTempDirectory("skipper");
		File targetPath = new File(tmpDirPath + File.separator + packageMetadata.getName());
		targetPath.mkdirs();
		File targetFile = PackageFileUtils.calculatePackageZipFile(packageMetadata, targetPath);
		try {
			StreamUtils.copy(packageMetadata.getPackageFile().getPackageBytes(), new FileOutputStream(targetFile));
		}
		catch (IOException e) {
			throw new SkipperException(
					"Could not copy package file for " + packageMetadata.getName() + "-"
							+ packageMetadata.getVersion() +
							" from database to target file " + targetFile,
					e);
		}
		ZipUtil.unpack(targetFile, targetPath);
		Package pkgToReturn = this.packageReader.read(new File(targetPath, packageMetadata.getName() + "-" +
				packageMetadata.getVersion()));
		pkgToReturn.setMetadata(packageMetadata);
		return pkgToReturn;
	}
	finally {
		if (tmpDirPath != null && !FileSystemUtils.deleteRecursively(tmpDirPath.toFile())) {
			logger.warn("Temporary directory can not be deleted: " + tmpDirPath);
		}
	}
}
 
Example #25
Source File: ResponseCreatorsTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void successWithContentWithoutContentType() throws Exception {
	DefaultResponseCreator responseCreator = MockRestResponseCreators.withSuccess("foo", null);
	MockClientHttpResponse response = (MockClientHttpResponse) responseCreator.createResponse(null);

	assertEquals(HttpStatus.OK, response.getStatusCode());
	assertNull(response.getHeaders().getContentType());
	assertArrayEquals("foo".getBytes(), StreamUtils.copyToByteArray(response.getBody()));
}
 
Example #26
Source File: ResponseCreatorsTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void successWithContent() throws Exception {
	DefaultResponseCreator responseCreator = MockRestResponseCreators.withSuccess("foo", MediaType.TEXT_PLAIN);
	MockClientHttpResponse response = (MockClientHttpResponse) responseCreator.createResponse(null);

	assertEquals(HttpStatus.OK, response.getStatusCode());
	assertEquals(MediaType.TEXT_PLAIN, response.getHeaders().getContentType());
	assertArrayEquals("foo".getBytes(), StreamUtils.copyToByteArray(response.getBody()));
}
 
Example #27
Source File: ResponseCreatorsTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void success() throws Exception {
	MockClientHttpResponse response = (MockClientHttpResponse) MockRestResponseCreators.withSuccess().createResponse(null);

	assertEquals(HttpStatus.OK, response.getStatusCode());
	assertTrue(response.getHeaders().isEmpty());
	assertEquals(0, StreamUtils.copyToByteArray(response.getBody()).length);
}
 
Example #28
Source File: SerializableObjectHttpMessageConverter.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
@Override
protected void writeInternal(final Serializable serializableObject, final HttpOutputMessage outputMessage)
  throws IOException, HttpMessageNotWritableException
{
  final byte[] messageBody = IOUtils.serializeObject(serializableObject);
  setContentLength(outputMessage, messageBody);
  StreamUtils.copy(messageBody, outputMessage.getBody());
}
 
Example #29
Source File: XmlServiceTests.java    From spring-cloud-contract with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldSuccessfullyReturnFullResponse() throws Exception {
	server.addStubMapping(StubMapping.buildFrom(StreamUtils
			.copyToString(full.getInputStream(), Charset.forName("UTF-8"))));

	ResponseEntity<XmlResponseBody> responseEntity = new RestTemplate()
			.exchange(RequestEntity
					.post(URI.create(
							"http://localhost:" + server.port() + "/xmlfraud"))
					.contentType(MediaType.valueOf("application/xml;charset=UTF-8"))
					.body(new XmlRequestBody("foo")), XmlResponseBody.class);

	BDDAssertions.then(responseEntity.getStatusCodeValue()).isEqualTo(200);
	BDDAssertions.then(responseEntity.getBody().status).isEqualTo("FULL");
}
 
Example #30
Source File: AbstractHttpRequestFactoryTestCase.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void echo() throws Exception {
	ClientHttpRequest request = factory.createRequest(new URI(baseUrl + "/echo"), HttpMethod.PUT);
	assertEquals("Invalid HTTP method", HttpMethod.PUT, request.getMethod());
	String headerName = "MyHeader";
	String headerValue1 = "value1";
	request.getHeaders().add(headerName, headerValue1);
	String headerValue2 = "value2";
	request.getHeaders().add(headerName, headerValue2);
	final byte[] body = "Hello World".getBytes("UTF-8");
	request.getHeaders().setContentLength(body.length);
	if (request instanceof StreamingHttpOutputMessage) {
		StreamingHttpOutputMessage streamingRequest =
				(StreamingHttpOutputMessage) request;
		streamingRequest.setBody(new StreamingHttpOutputMessage.Body() {
			@Override
			public void writeTo(OutputStream outputStream) throws IOException {
				StreamUtils.copy(body, outputStream);
			}
		});
	}
	else {
		StreamUtils.copy(body, request.getBody());
	}
	ClientHttpResponse response = request.execute();
	try {
		assertEquals("Invalid status code", HttpStatus.OK, response.getStatusCode());
		assertTrue("Header not found", response.getHeaders().containsKey(headerName));
		assertEquals("Header value not found", Arrays.asList(headerValue1, headerValue2),
				response.getHeaders().get(headerName));
		byte[] result = FileCopyUtils.copyToByteArray(response.getBody());
		assertTrue("Invalid body", Arrays.equals(body, result));
	}
	finally {
		response.close();
	}
}