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

The following examples show how to use org.springframework.core.io.buffer.DataBufferUtils. 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
@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 2
Source Project: spring-analysis-note   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 3
Source Project: spring-analysis-note   Source File: Jackson2JsonEncoderTests.java    License: 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 4
Source Project: spring-analysis-note   Source File: BodyInsertersTests.java    License: 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 5
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 6
Source Project: java-technology-stack   Source File: BodyExtractors.java    License: 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 7
Source Project: java-technology-stack   Source File: AbstractEncoderTestCase.java    License: 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 8
Source Project: open-cloud   Source File: AccessLogFilter.java    License: 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 9
@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 10
Source Project: spring-analysis-note   Source File: ProtobufEncoder.java    License: 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 11
@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 12
Source Project: java-technology-stack   Source File: BodyInsertersTests.java    License: 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 13
@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 14
Source Project: spring-analysis-note   Source File: ProtobufEncoderTests.java    License: 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 Project: gateway   Source File: LogFilter.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * 输出请求体
 *
 * @param exchange ServerWebExchange
 * @param chain    GatewayFilterChain
 * @param log      日志DTO
 * @return Mono
 */
private Mono<Void> readBody(ServerWebExchange exchange, GatewayFilterChain chain, LogDto log) {
    Flux<DataBuffer> dataBufferFlux = exchange.getRequest().getBody();
    return DataBufferUtils.join(dataBufferFlux).flatMap(dataBuffer -> {
        byte[] bytes = new byte[dataBuffer.readableByteCount()];
        dataBuffer.read(bytes);
        DataBufferUtils.release(dataBuffer);

        // 重新构造请求
        ServerHttpRequest mutatedRequest = new ServerHttpRequestDecorator(exchange.getRequest()) {
            @Override
            public Flux<DataBuffer> getBody() {
                return Flux.defer(() -> {
                    DataBuffer buffer = exchange.getResponse().bufferFactory().wrap(bytes);
                    DataBufferUtils.retain(buffer);

                    return Mono.just(buffer);
                });
            }
        };

        ServerWebExchange mutatedExchange = exchange.mutate().request(mutatedRequest).build();
        return ServerRequest.create(mutatedExchange, HandlerStrategies.withDefaults().messageReaders()).bodyToMono(String.class).doOnNext(body -> {
            if (Pattern.matches("^\\[.*]$", body)) {
                List<Object> list = Json.toList(body, Object.class);
                log.setBody(list == null ? body : list);
            } else if (Pattern.matches("^\\{.*}$", body)) {
                Map obj = Json.toMap(body);
                log.setBody(obj == null ? body : obj);
            } else {
                log.setBody(body);
            }

            logger.info("请求参数:{}", log.toString());
        }).then(chain.filter(mutatedExchange));
    });
}
 
Example 16
Source Project: java-technology-stack   Source File: AbstractEncoderTestCase.java    License: MIT License 5 votes vote down vote up
/**
 * Test a {@link Encoder#encode encode} scenario where the input stream is canceled.
 * This test method will feed the first element of the {@code input} stream to the decoder,
 * followed by a cancel signal.
 * The result is expected to contain one "normal" element.
 *
 * @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}.
 */
protected void testEncodeCancel(Publisher<?> input, ResolvableType inputType,
		@Nullable MimeType mimeType, @Nullable Map<String, Object> hints) {

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

	StepVerifier.create(result)
			.consumeNextWith(DataBufferUtils::release)
			.thenCancel()
			.verify();
}
 
Example 17
Source Project: spring-analysis-note   Source File: ChannelSendOperator.java    License: MIT License 5 votes vote down vote up
private void releaseCachedItem() {
	synchronized (this) {
		Object item = this.item;
		if (item instanceof DataBuffer) {
			DataBufferUtils.release((DataBuffer) item);
		}
		this.item = null;
	}
}
 
Example 18
Source Project: java-technology-stack   Source File: HttpHeadResponseDecorator.java    License: MIT License 5 votes vote down vote up
/**
 * Apply {@link Flux#reduce(Object, BiFunction) reduce} on the body, count
 * the number of bytes produced, release data buffers without writing, and
 * set the {@literal Content-Length} header.
 */
@Override
public final Mono<Void> writeWith(Publisher<? extends DataBuffer> body) {
	return Flux.from(body)
			.reduce(0, (current, buffer) -> {
				int next = current + buffer.readableByteCount();
				DataBufferUtils.release(buffer);
				return next;
			})
			.doOnNext(count -> getHeaders().setContentLength(count))
			.then();
}
 
Example 19
private Mono<Void> writeAndFlush(Flux<DataBuffer> body, OutputStream responseBody) {
	return DataBufferUtils.write(body, responseBody).map(DataBufferUtils::release).then(Mono.create((sink) -> {
		try {
			responseBody.flush();
			sink.success();
		}
		catch (IOException ex) {
			sink.error(ex);
		}
	}));
}
 
Example 20
Source Project: java-technology-stack   Source File: ServletServerHttpResponse.java    License: MIT License 5 votes vote down vote up
@Override
protected boolean write(DataBuffer dataBuffer) throws IOException {
	if (ServletServerHttpResponse.this.flushOnNext) {
		if (rsWriteLogger.isTraceEnabled()) {
			rsWriteLogger.trace(getLogPrefix() + "Flush attempt");
		}
		flush();
	}

	boolean ready = ServletServerHttpResponse.this.isWritePossible();
	int remaining = dataBuffer.readableByteCount();
	if (ready && remaining > 0) {
		// In case of IOException, onError handling should call discardData(DataBuffer)..
		int written = writeToOutputStream(dataBuffer);
		if (logger.isTraceEnabled()) {
			logger.trace(getLogPrefix() + "Wrote " + written + " of " + remaining + " bytes");
		}
		else if (rsWriteLogger.isTraceEnabled()) {
			rsWriteLogger.trace(getLogPrefix() + "Wrote " + written + " of " + remaining + " bytes");
		}
		if (written == remaining) {
			DataBufferUtils.release(dataBuffer);
			return true;
		}
	}
	else {
		if (rsWriteLogger.isTraceEnabled()) {
			rsWriteLogger.trace(getLogPrefix() + "ready: " + ready + ", remaining: " + remaining);
		}
	}

	return false;
}
 
Example 21
Source Project: spring-analysis-note   Source File: ContentVersionStrategy.java    License: 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 22
Source Project: spring-analysis-note   Source File: DefaultWebClient.java    License: MIT License 5 votes vote down vote up
private static Mono<WebClientResponseException> createResponseException(
		ClientResponse response, HttpRequest request) {

	return DataBufferUtils.join(response.body(BodyExtractors.toDataBuffers()))
			.map(dataBuffer -> {
				byte[] bytes = new byte[dataBuffer.readableByteCount()];
				dataBuffer.read(bytes);
				DataBufferUtils.release(dataBuffer);
				return bytes;
			})
			.defaultIfEmpty(new byte[0])
			.map(bodyBytes -> {
				Charset charset = response.headers().contentType()
						.map(MimeType::getCharset)
						.orElse(StandardCharsets.ISO_8859_1);
				if (HttpStatus.resolve(response.rawStatusCode()) != null) {
					return WebClientResponseException.create(
							response.statusCode().value(),
							response.statusCode().getReasonPhrase(),
							response.headers().asHttpHeaders(),
							bodyBytes,
							charset,
							request);
				}
				else {
					return new UnknownHttpStatusCodeException(
							response.rawStatusCode(),
							response.headers().asHttpHeaders(),
							bodyBytes,
							charset,
							request);
				}
			});
}
 
Example 23
Source Project: spring-analysis-note   Source File: Jackson2JsonEncoderTests.java    License: MIT License 5 votes vote down vote up
@Test
public void encodeWithType() {
	Flux<ParentClass> input = Flux.just(new Foo(), new Bar());

	testEncode(input, ParentClass.class, step -> step
			.consumeNextWith(expectString("[{\"type\":\"foo\"},{\"type\":\"bar\"}]")
					.andThen(DataBufferUtils::release))
			.verifyComplete());
}
 
Example 24
Source Project: spring-analysis-note   Source File: BodyExtractors.java    License: MIT License 5 votes vote down vote up
private static Mono<Void> consumeAndCancel(ReactiveHttpInputMessage message) {
	return message.getBody()
			.map(buffer -> {
				DataBufferUtils.release(buffer);
				throw new ReadCancellationException();
			})
			.onErrorResume(ReadCancellationException.class, ex -> Mono.empty())
			.then();
}
 
Example 25
Source Project: java-technology-stack   Source File: ContentVersionStrategy.java    License: 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 26
Source Project: java-technology-stack   Source File: StringDecoder.java    License: MIT License 5 votes vote down vote up
/**
 * Split the given data buffer on delimiter boundaries.
 * The returned Flux contains an {@link #END_FRAME} buffer after each delimiter.
 */
private List<DataBuffer> splitOnDelimiter(DataBuffer dataBuffer, List<byte[]> delimiterBytes) {
	List<DataBuffer> frames = new ArrayList<>();
	do {
		int length = Integer.MAX_VALUE;
		byte[] matchingDelimiter = null;
		for (byte[] delimiter : delimiterBytes) {
			int index = indexOf(dataBuffer, delimiter);
			if (index >= 0 && index < length) {
				length = index;
				matchingDelimiter = delimiter;
			}
		}
		DataBuffer frame;
		int readPosition = dataBuffer.readPosition();
		if (matchingDelimiter != null) {
			if (this.stripDelimiter) {
				frame = dataBuffer.slice(readPosition, length);
			}
			else {
				frame = dataBuffer.slice(readPosition, length + matchingDelimiter.length);
			}
			dataBuffer.readPosition(readPosition + length + matchingDelimiter.length);

			frames.add(DataBufferUtils.retain(frame));
			frames.add(END_FRAME);
		}
		else {
			frame = dataBuffer.slice(readPosition, dataBuffer.readableByteCount());
			dataBuffer.readPosition(readPosition + dataBuffer.readableByteCount());
			frames.add(DataBufferUtils.retain(frame));
		}
	}
	while (dataBuffer.readableByteCount() > 0);

	DataBufferUtils.release(dataBuffer);
	return frames;
}
 
Example 27
Source Project: java-technology-stack   Source File: JettyClientHttpRequest.java    License: MIT License 5 votes vote down vote up
private ContentChunk toContentChunk(DataBuffer buffer) {
	return new ContentChunk(buffer.asByteBuffer(), new Callback() {
		@Override
		public void succeeded() {
			DataBufferUtils.release(buffer);
		}

		@Override
		public void failed(Throwable x) {
			DataBufferUtils.release(buffer);
			throw Exceptions.propagate(x);
		}
	});
}
 
Example 28
Source Project: java-technology-stack   Source File: MockClientHttpResponse.java    License: MIT License 5 votes vote down vote up
/**
 * Return the response body aggregated and converted to a String using the
 * charset of the Content-Type response or otherwise as "UTF-8".
 */
public Mono<String> getBodyAsString() {
	Charset charset = getCharset();
	return Flux.from(getBody())
			.reduce(bufferFactory.allocateBuffer(), (previous, current) -> {
				previous.write(current);
				DataBufferUtils.release(current);
				return previous;
			})
			.map(buffer -> dumpString(buffer, charset));
}
 
Example 29
Source Project: java-technology-stack   Source File: FormHttpMessageWriterTests.java    License: MIT License 5 votes vote down vote up
private Consumer<DataBuffer> stringConsumer(String expected) {
	return dataBuffer -> {
		String value =
				DataBufferTestUtils.dumpString(dataBuffer, StandardCharsets.UTF_8);
		DataBufferUtils.release(dataBuffer);
		assertEquals(expected, value);
	};
}
 
Example 30
Source Project: spring-analysis-note   Source File: ResourceRegionEncoder.java    License: MIT License 5 votes vote down vote up
private Flux<DataBuffer> writeResourceRegion(
		ResourceRegion region, DataBufferFactory bufferFactory, @Nullable Map<String, Object> hints) {

	Resource resource = region.getResource();
	long position = region.getPosition();
	long count = region.getCount();

	if (logger.isDebugEnabled() && !Hints.isLoggingSuppressed(hints)) {
		logger.debug(Hints.getLogPrefix(hints) +
				"Writing region " + position + "-" + (position + count) + " of [" + resource + "]");
	}

	Flux<DataBuffer> in = DataBufferUtils.read(resource, position, bufferFactory, this.bufferSize);
	return DataBufferUtils.takeUntilByteCount(in, count);
}