org.springframework.core.io.buffer.DataBufferUtils Java Examples

The following examples show how to use org.springframework.core.io.buffer.DataBufferUtils. 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: CssLinkResourceTransformer.java    From spring-analysis-note 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 #2
Source File: BodyInsertersTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void ofResource() throws IOException {
	Resource body = new ClassPathResource("response.txt", getClass());
	BodyInserter<Resource, ReactiveHttpOutputMessage> inserter = BodyInserters.fromResource(body);

	MockServerHttpResponse response = new MockServerHttpResponse();
	Mono<Void> result = inserter.insert(response, this.context);
	StepVerifier.create(result).expectComplete().verify();

	byte[] expectedBytes = Files.readAllBytes(body.getFile().toPath());

	StepVerifier.create(response.getBody())
			.consumeNextWith(dataBuffer -> {
				byte[] resultBytes = new byte[dataBuffer.readableByteCount()];
				dataBuffer.read(resultBytes);
				DataBufferUtils.release(dataBuffer);
				assertArrayEquals(expectedBytes, resultBytes);
			})
			.expectComplete()
			.verify();
}
 
Example #3
Source File: InstancesProxyController.java    From spring-boot-admin with Apache License 2.0 6 votes vote down vote up
@ResponseBody
@RequestMapping(path = APPLICATION_MAPPED_PATH, method = { RequestMethod.GET, RequestMethod.HEAD,
		RequestMethod.POST, RequestMethod.PUT, RequestMethod.PATCH, RequestMethod.DELETE, RequestMethod.OPTIONS })
public Flux<InstanceWebProxy.InstanceResponse> endpointProxy(
		@PathVariable("applicationName") String applicationName, HttpServletRequest servletRequest) {
	ServerHttpRequest request = new ServletServerHttpRequest(servletRequest);
	String endpointLocalPath = this.getEndpointLocalPath(this.adminContextPath + APPLICATION_MAPPED_PATH,
			servletRequest);
	URI uri = UriComponentsBuilder.fromPath(endpointLocalPath).query(request.getURI().getRawQuery()).build(true)
			.toUri();

	Flux<DataBuffer> cachedBody = DataBufferUtils.readInputStream(request::getBody, this.bufferFactory, 4096)
			.cache();

	return this.instanceWebProxy.forward(this.registry.getInstances(applicationName), uri, request.getMethod(),
			this.httpHeadersFilter.filterHeaders(request.getHeaders()), BodyInserters.fromDataBuffers(cachedBody));
}
 
Example #4
Source File: ProtobufEncoder.java    From spring-analysis-note with MIT License 6 votes vote down vote up
private DataBuffer encodeValue(Message message, DataBufferFactory bufferFactory, boolean delimited) {

		DataBuffer buffer = bufferFactory.allocateBuffer();
		boolean release = true;
		try {
			if (delimited) {
				message.writeDelimitedTo(buffer.asOutputStream());
			}
			else {
				message.writeTo(buffer.asOutputStream());
			}
			release = false;
			return buffer;
		}
		catch (IOException ex) {
			throw new IllegalStateException("Unexpected I/O error while writing to data buffer", ex);
		}
		finally {
			if (release) {
				DataBufferUtils.release(buffer);
			}
		}
	}
 
Example #5
Source File: InstancesProxyController.java    From spring-boot-admin with Apache License 2.0 6 votes vote down vote up
@ResponseBody
@RequestMapping(path = APPLICATION_MAPPED_PATH, method = { RequestMethod.GET, RequestMethod.HEAD,
		RequestMethod.POST, RequestMethod.PUT, RequestMethod.PATCH, RequestMethod.DELETE, RequestMethod.OPTIONS })
public Flux<InstanceWebProxy.InstanceResponse> endpointProxy(
		@PathVariable("applicationName") String applicationName, ServerHttpRequest request) {
	String endpointLocalPath = this.getEndpointLocalPath(this.adminContextPath + APPLICATION_MAPPED_PATH, request);
	URI uri = UriComponentsBuilder.fromPath(endpointLocalPath).query(request.getURI().getRawQuery()).build(true)
			.toUri();

	Flux<DataBuffer> cachedBody = request.getBody().map((b) -> {
		int readableByteCount = b.readableByteCount();
		DataBuffer dataBuffer = this.bufferFactory.allocateBuffer(readableByteCount);
		dataBuffer.write(b.asByteBuffer());
		DataBufferUtils.release(b);
		return dataBuffer;
	}).cache();

	return this.instanceWebProxy.forward(this.registry.getInstances(applicationName), uri, request.getMethod(),
			this.httpHeadersFilter.filterHeaders(request.getHeaders()), BodyInserters.fromDataBuffers(cachedBody));
}
 
Example #6
Source File: Jackson2JsonEncoderTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test  // SPR-15727
public void encodeAsStreamWithCustomStreamingType() {
	MediaType fooMediaType = new MediaType("application", "foo");
	MediaType barMediaType = new MediaType("application", "bar");
	this.encoder.setStreamingMediaTypes(Arrays.asList(fooMediaType, barMediaType));
	Flux<Pojo> input = Flux.just(
			new Pojo("foo", "bar"),
			new Pojo("foofoo", "barbar"),
			new Pojo("foofoofoo", "barbarbar")
	);

	testEncode(input, ResolvableType.forClass(Pojo.class), step -> step
			.consumeNextWith(expectString("{\"foo\":\"foo\",\"bar\":\"bar\"}\n")
					.andThen(DataBufferUtils::release))
			.consumeNextWith(expectString("{\"foo\":\"foofoo\",\"bar\":\"barbar\"}\n")
					.andThen(DataBufferUtils::release))
			.consumeNextWith(expectString("{\"foo\":\"foofoofoo\",\"bar\":\"barbarbar\"}\n")
					.andThen(DataBufferUtils::release))
			.verifyComplete(),
			barMediaType, null);
}
 
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: BodyInsertersTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void fromFormDataWith() {
	BodyInserter<MultiValueMap<String, String>, ClientHttpRequest>
			inserter = BodyInserters.fromFormData("name 1", "value 1")
			.with("name 2", "value 2+1")
			.with("name 2", "value 2+2")
			.with("name 3", null);

	MockClientHttpRequest request = new MockClientHttpRequest(HttpMethod.GET, URI.create("http://example.com"));
	Mono<Void> result = inserter.insert(request, this.context);
	StepVerifier.create(result).expectComplete().verify();

	StepVerifier.create(request.getBody())
			.consumeNextWith(dataBuffer -> {
				byte[] resultBytes = new byte[dataBuffer.readableByteCount()];
				dataBuffer.read(resultBytes);
				DataBufferUtils.release(dataBuffer);
				assertArrayEquals("name+1=value+1&name+2=value+2%2B1&name+2=value+2%2B2&name+3".getBytes(StandardCharsets.UTF_8),
						resultBytes);
			})
			.expectComplete()
			.verify();

}
 
Example #9
Source File: AccessLogFilter.java    From open-cloud with MIT License 6 votes vote down vote up
@Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
    ServerHttpResponse response = exchange.getResponse();
    DataBufferFactory bufferFactory = response.bufferFactory();
    ServerHttpResponseDecorator decoratedResponse = new ServerHttpResponseDecorator(response) {
        @Override
        public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) {
            if (body instanceof Flux) {
                Flux<? extends DataBuffer> fluxBody = (Flux<? extends DataBuffer>) body;
                return super.writeWith(fluxBody.map(dataBuffer -> {
                    // probably should reuse buffers
                    byte[] content = new byte[dataBuffer.readableByteCount()];
                    dataBuffer.read(content);
                    //释放掉内存
                    DataBufferUtils.release(dataBuffer);
                    return bufferFactory.wrap(content);
                }));
            }
            // if body is not a flux. never got there.
            return super.writeWith(body);
        }
    };
    return chain.filter(exchange.mutate().response(decoratedResponse).build()).then(Mono.fromRunnable(()->{
        accessLogService.sendLog(exchange, null);
    }));
}
 
Example #10
Source File: AbstractEncoderTestCase.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * Test a {@link Encoder#encode encode} scenario where the input stream contains an error.
 * This test method will feed the first element of the {@code input} stream to the encoder,
 * followed by an {@link InputException}.
 * The result is expected to contain one "normal" element, followed by the error.
 *
 * @param input the input to be provided to the encoder
 * @param inputType the input type
 * @param mimeType the mime type to use for decoding. May be {@code null}.
 * @param hints the hints used for decoding. May be {@code null}.
 * @see InputException
 */
protected void testEncodeError(Publisher<?> input, ResolvableType inputType,
		@Nullable MimeType mimeType, @Nullable Map<String, Object> hints) {

	input = Flux.concat(
			Flux.from(input).take(1),
			Flux.error(new InputException()));

	Flux<DataBuffer> result = encoder().encode(input, this.bufferFactory, inputType,
			mimeType, hints);

	StepVerifier.create(result)
			.consumeNextWith(DataBufferUtils::release)
			.expectError(InputException.class)
			.verify();
}
 
Example #11
Source File: AppCacheManifestTransformer.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Override
public Mono<Resource> transform(ServerWebExchange exchange, Resource inputResource,
		ResourceTransformerChain chain) {

	return chain.transform(exchange, inputResource)
			.flatMap(outputResource -> {
				String name = outputResource.getFilename();
				if (!this.fileExtension.equals(StringUtils.getFilenameExtension(name))) {
					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 content = charBuffer.toString();
							return transform(content, outputResource, chain, exchange);
						});
			});
}
 
Example #12
Source File: BodyExtractors.java    From java-technology-stack with MIT License 6 votes vote down vote up
private static <T> Flux<T> unsupportedErrorHandler(
		ReactiveHttpInputMessage message, UnsupportedMediaTypeException ex) {

	Flux<T> result;
	if (message.getHeaders().getContentType() == null) {
		// Maybe it's okay there is no content type, if there is no content..
		result = message.getBody().map(buffer -> {
			DataBufferUtils.release(buffer);
			throw ex;
		});
	}
	else {
		result = message instanceof ClientHttpResponse ?
				consumeAndCancel(message).thenMany(Flux.error(ex)) : Flux.error(ex);
	}
	return result;
}
 
Example #13
Source File: SynchronossPartHttpMessageReaderTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void resolveParts() {
	ServerHttpRequest request = generateMultipartRequest();
	ResolvableType elementType = forClassWithGenerics(MultiValueMap.class, String.class, Part.class);
	MultiValueMap<String, Part> parts = this.reader.readMono(elementType, request, emptyMap()).block();
	assertEquals(2, parts.size());

	assertTrue(parts.containsKey("fooPart"));
	Part part = parts.getFirst("fooPart");
	assertTrue(part instanceof FilePart);
	assertEquals("fooPart", part.name());
	assertEquals("foo.txt", ((FilePart) part).filename());
	DataBuffer buffer = DataBufferUtils.join(part.content()).block();
	assertEquals(12, buffer.readableByteCount());
	byte[] byteContent = new byte[12];
	buffer.read(byteContent);
	assertEquals("Lorem Ipsum.", new String(byteContent));

	assertTrue(parts.containsKey("barPart"));
	part = parts.getFirst("barPart");
	assertTrue(part instanceof FormFieldPart);
	assertEquals("barPart", part.name());
	assertEquals("bar", ((FormFieldPart) part).value());
}
 
Example #14
Source File: ProtobufEncoderTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Override
@Test
public void encode() {
	Mono<Message> input = Mono.just(this.msg1);

	testEncodeAll(input, Msg.class, step -> step
			.consumeNextWith(dataBuffer -> {
				try {
					assertEquals(this.msg1, Msg.parseFrom(dataBuffer.asInputStream()));

				}
				catch (IOException ex) {
					throw new UncheckedIOException(ex);
				}
				finally {
					DataBufferUtils.release(dataBuffer);
				}
			})
			.verifyComplete());
}
 
Example #15
Source File: DefaultMultipartMessageReaderTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void partNoHeader() {
	MockServerHttpRequest request = createRequest(
			new ClassPathResource("part-no-header.multipart", getClass()), "boundary");

	Flux<Part> result = this.reader.read(forClass(Part.class), request, emptyMap());

	StepVerifier.create(result)
			.consumeNextWith(part -> {
				assertTrue(part.headers().isEmpty());
				part.content().subscribe(DataBufferUtils::release);
			})
			.verifyComplete();
}
 
Example #16
Source File: DataBufferDecoderTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
private Consumer<DataBuffer> expectDataBuffer(byte[] expected) {
	return actual -> {
		byte[] actualBytes = new byte[actual.readableByteCount()];
		actual.read(actualBytes);
		assertArrayEquals(expected, actualBytes);

		DataBufferUtils.release(actual);
	};
}
 
Example #17
Source File: MockClientHttpRequest.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Aggregate response data and convert to a String using the "Content-Type"
 * charset or "UTF-8" by default.
 */
public Mono<String> getBodyAsString() {

	Charset charset = Optional.ofNullable(getHeaders().getContentType()).map(MimeType::getCharset)
			.orElse(StandardCharsets.UTF_8);

	return getBody()
			.reduce(bufferFactory().allocateBuffer(), (previous, current) -> {
				previous.write(current);
				DataBufferUtils.release(current);
				return previous;
			})
			.map(buffer -> bufferToString(buffer, charset));
}
 
Example #18
Source File: WebfluxResponseUtil.java    From microservices-platform with Apache License 2.0 5 votes vote down vote up
public static Mono<Void> responseWrite(ServerWebExchange exchange, int httpStatus, Result result) {
    if (httpStatus == 0) {
        httpStatus = HttpStatus.INTERNAL_SERVER_ERROR.value();
    }
    ServerHttpResponse response = exchange.getResponse();
    response.getHeaders().setAccessControlAllowCredentials(true);
    response.getHeaders().setAccessControlAllowOrigin("*");
    response.setStatusCode(HttpStatus.valueOf(httpStatus));
    response.getHeaders().setContentType(MediaType.APPLICATION_JSON_UTF8);
    DataBufferFactory dataBufferFactory = response.bufferFactory();
    DataBuffer buffer = dataBufferFactory.wrap(JSONObject.toJSONString(result).getBytes(Charset.defaultCharset()));
    return response.writeWith(Mono.just(buffer)).doOnError((error) -> {
        DataBufferUtils.release(buffer);
    });
}
 
Example #19
Source File: BodyInsertersTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test  // SPR-16350
public void fromMultipartDataWithMultipleValues() {
	MultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
	map.put("name", Arrays.asList("value1", "value2"));
	BodyInserters.FormInserter<Object> inserter = BodyInserters.fromMultipartData(map);

	MockClientHttpRequest request = new MockClientHttpRequest(HttpMethod.GET, URI.create("http://example.com"));
	Mono<Void> result = inserter.insert(request, this.context);
	StepVerifier.create(result).expectComplete().verify();

	StepVerifier.create(DataBufferUtils.join(request.getBody()))
			.consumeNextWith(dataBuffer -> {
				byte[] resultBytes = new byte[dataBuffer.readableByteCount()];
				dataBuffer.read(resultBytes);
				DataBufferUtils.release(dataBuffer);
				String content = new String(resultBytes, StandardCharsets.UTF_8);
				assertThat(content, containsString("Content-Disposition: form-data; name=\"name\"\r\n" +
						"Content-Type: text/plain;charset=UTF-8\r\n" +
						"Content-Length: 6\r\n" +
						"\r\n" +
						"value1"));
				assertThat(content, containsString("Content-Disposition: form-data; name=\"name\"\r\n" +
						"Content-Type: text/plain;charset=UTF-8\r\n" +
						"Content-Length: 6\r\n" +
						"\r\n" +
						"value2"));
			})
			.expectComplete()
			.verify();
}
 
Example #20
Source File: AbstractJackson2Decoder.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
public Mono<Object> decodeToMono(Publisher<DataBuffer> input, ResolvableType elementType,
		@Nullable MimeType mimeType, @Nullable Map<String, Object> hints) {

	return DataBufferUtils.join(input)
			.map(dataBuffer -> decode(dataBuffer, elementType, mimeType, hints));
}
 
Example #21
Source File: DefaultMultipartMessageReader.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Finds the fist occurrence of the boundary in the given stream of data buffers, and skips
 * all data until then. Note that the first boundary of a multipart message does not contain
 * the initial \r\n, hence the need for a special boundary matcher.
 */
private static Flux<DataBuffer> skipUntilFirstBoundary(Flux<DataBuffer> dataBuffers, byte[] boundary) {
	byte[] needle = concat(FIRST_BOUNDARY_PREFIX, boundary);
	DataBufferUtils.Matcher matcher = DataBufferUtils.matcher(needle);
	AtomicBoolean found = new AtomicBoolean();

	return dataBuffers.concatMap(dataBuffer -> {
		if (found.get()) {
			return Mono.just(dataBuffer);
		}
		else {
			int endIdx = matcher.match(dataBuffer);
			if (endIdx != -1) {
				found.set(true);
				int length = dataBuffer.writePosition() - 1 - endIdx;
				DataBuffer slice = dataBuffer.retainedSlice(endIdx + 1, length);
				DataBufferUtils.release(dataBuffer);
				if (logger.isTraceEnabled()) {
					logger.trace("Found first boundary at " + endIdx + " in " + toString(dataBuffer));
				}
				return Mono.just(slice);
			}
			else {
				DataBufferUtils.release(dataBuffer);
				return Mono.empty();
			}
		}
	});
}
 
Example #22
Source File: ReactiveFileReader.java    From Hands-On-Reactive-Programming-in-Spring-5 with MIT License 5 votes vote down vote up
public Flux<DataBuffer> backpressuredShakespeare() {
    return DataBufferUtils
        .read(
            new DefaultResourceLoader().getResource("hamlet.txt"),
            new DefaultDataBufferFactory(),
            1024
        )
        .log();
}
 
Example #23
Source File: ResourceRegionEncoderTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
protected Consumer<DataBuffer> stringConsumer(String expected) {
	return dataBuffer -> {
		String value =
				DataBufferTestUtils.dumpString(dataBuffer, UTF_8);
		DataBufferUtils.release(dataBuffer);
		assertEquals(expected, value);
	};
}
 
Example #24
Source File: InstancesProxyController.java    From Moss with Apache License 2.0 5 votes vote down vote up
/**
 * 所以端点的请求代理入口:/instances/{instanceId}/actuator/**
 * @author xujin
 * @param instanceId
 * @param servletRequest
 * @param servletResponse
 * @return
 * @throws IOException
 */
@ResponseBody
@RequestMapping(path = REQUEST_MAPPING_PATH, method = {RequestMethod.GET, RequestMethod.HEAD, RequestMethod.POST, RequestMethod.PUT, RequestMethod.PATCH, RequestMethod.DELETE, RequestMethod.OPTIONS})
public Mono<Void> endpointProxy(@PathVariable("instanceId") String instanceId,
                                HttpServletRequest servletRequest,
                                HttpServletResponse servletResponse) throws IOException {
    ServerHttpRequest request = new ServletServerHttpRequest(servletRequest);

    String pathWithinApplication = UriComponentsBuilder.fromPath(servletRequest.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE)
                                                                               .toString()).toUriString();
    String endpointLocalPath = getEndpointLocalPath(pathWithinApplication);

    URI uri = UriComponentsBuilder.fromPath(endpointLocalPath)
                                  .query(request.getURI().getRawQuery())
                                  .build(true)
                                  .toUri();

    //We need to explicitly block until the headers are recieved and write them before the async dispatch.
    //otherwise the FrameworkServlet will add wrong Allow header for OPTIONS request
    ClientResponse clientResponse = super.forward(instanceId,
        uri,
        request.getMethod(),
        request.getHeaders(),
        () -> BodyInserters.fromDataBuffers(DataBufferUtils.readInputStream(request::getBody,
            this.bufferFactory,
            4096
        ))
    ).block();

    ServerHttpResponse response = new ServletServerHttpResponse(servletResponse);
    response.setStatusCode(clientResponse.statusCode());
    response.getHeaders().addAll(filterHeaders(clientResponse.headers().asHttpHeaders()));
    OutputStream responseBody = response.getBody();
    response.flush();

    return clientResponse.body(BodyExtractors.toDataBuffers())
                         .window(1)
                         .concatMap(body -> writeAndFlush(body, responseBody))
                         .then();
}
 
Example #25
Source File: UndertowServerHttpRequest.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
public boolean release() {
	int refCount = this.refCount.decrementAndGet();
	if (refCount == 0) {
		try {
			return DataBufferUtils.release(this.dataBuffer);
		}
		finally {
			this.pooledByteBuffer.close();
		}
	}
	return false;
}
 
Example #26
Source File: StringDecoder.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
public Flux<String> decode(Publisher<DataBuffer> inputStream, ResolvableType elementType,
		@Nullable MimeType mimeType, @Nullable Map<String, Object> hints) {

	List<byte[]> delimiterBytes = getDelimiterBytes(mimeType);

	Flux<DataBuffer> inputFlux = Flux.from(inputStream)
			.flatMapIterable(dataBuffer -> splitOnDelimiter(dataBuffer, delimiterBytes))
			.bufferUntil(StringDecoder::isEndFrame)
			.map(StringDecoder::joinUntilEndFrame)
			.doOnDiscard(PooledDataBuffer.class, DataBufferUtils::release);

	return super.decode(inputFlux, elementType, mimeType, hints);
}
 
Example #27
Source File: ProtobufDecoderTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void decodeSplitChunks() {


	Flux<DataBuffer> input = Flux.just(this.testMsg1, this.testMsg2)
			.flatMap(msg -> Mono.defer(() -> {
				DataBuffer buffer = this.bufferFactory.allocateBuffer();
				try {
					msg.writeDelimitedTo(buffer.asOutputStream());
					return Mono.just(buffer);
				}
				catch (IOException e) {
					release(buffer);
					return Mono.error(e);
				}
			}))
			.flatMap(buffer -> {
				int len = buffer.readableByteCount() / 2;
				Flux<DataBuffer> result = Flux.just(
						DataBufferUtils.retain(buffer.slice(0, len)),
						DataBufferUtils
								.retain(buffer.slice(len, buffer.readableByteCount() - len))
				);
				release(buffer);
				return result;
			});

	testDecode(input, Msg.class, step -> step
			.expectNext(this.testMsg1)
			.expectNext(this.testMsg2)
			.verifyComplete());
}
 
Example #28
Source File: StringDecoder.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Override
protected String decodeDataBuffer(DataBuffer dataBuffer, ResolvableType elementType,
		@Nullable MimeType mimeType, @Nullable Map<String, Object> hints) {

	Charset charset = getCharset(mimeType);
	CharBuffer charBuffer = charset.decode(dataBuffer.asByteBuffer());
	DataBufferUtils.release(dataBuffer);
	String value = charBuffer.toString();
	LogFormatUtils.traceDebug(logger, traceOn -> {
		String formatted = LogFormatUtils.formatValue(value, !traceOn);
		return Hints.getLogPrefix(hints) + "Decoded " + formatted;
	});
	return value;
}
 
Example #29
Source File: MockClientHttpRequest.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/**
 * Aggregate response data and convert to a String using the "Content-Type"
 * charset or "UTF-8" by default.
 */
public Mono<String> getBodyAsString() {

	Charset charset = Optional.ofNullable(getHeaders().getContentType()).map(MimeType::getCharset)
			.orElse(StandardCharsets.UTF_8);

	return getBody()
			.reduce(bufferFactory().allocateBuffer(), (previous, current) -> {
				previous.write(current);
				DataBufferUtils.release(current);
				return previous;
			})
			.map(buffer -> bufferToString(buffer, charset));
}
 
Example #30
Source File: ProtobufDecoderTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test  // SPR-17429
public void decodeSplitMessageSize() {
	this.decoder.setMaxMessageSize(100009);
	StringBuilder builder = new StringBuilder();
	for (int i = 0; i < 10000; i++) {
		builder.append("azertyuiop");
	}
	Msg bigMessage = Msg.newBuilder().setFoo(builder.toString()).setBlah(secondMsg2).build();

	Flux<DataBuffer> input = Flux.just(bigMessage, bigMessage)
			.flatMap(msg -> Mono.defer(() -> {
				DataBuffer buffer = this.bufferFactory.allocateBuffer();
				try {
					msg.writeDelimitedTo(buffer.asOutputStream());
					return Mono.just(buffer);
				}
				catch (IOException e) {
					release(buffer);
					return Mono.error(e);
				}
			}))
			.flatMap(buffer -> {
				int len = 2;
				Flux<DataBuffer> result = Flux.just(
						DataBufferUtils.retain(buffer.slice(0, len)),
						DataBufferUtils
								.retain(buffer.slice(len, buffer.readableByteCount() - len))
				);
				release(buffer);
				return result;
			});

	testDecode(input, Msg.class, step -> step
			.expectNext(bigMessage)
			.expectNext(bigMessage)
			.verifyComplete());
}