Clean up warnings and polish tests

This commit also modifies ResourceWebHandlerTests.getResourceFromFileSystem()
so that it passes in the IDE.
This commit is contained in:
Sam Brannen 2022-08-26 15:20:16 +02:00
parent e53c7ae6f5
commit b50415062b
20 changed files with 206 additions and 214 deletions

View File

@ -506,6 +506,7 @@ public class DefaultDataBuffer implements DataBuffer {
} }
@Override @Override
@SuppressWarnings("deprecation")
public DefaultDataBuffer capacity(int newCapacity) { public DefaultDataBuffer capacity(int newCapacity) {
throw new UnsupportedOperationException("Changing the capacity of a sliced buffer is not supported"); throw new UnsupportedOperationException("Changing the capacity of a sliced buffer is not supported");
} }

View File

@ -42,8 +42,8 @@ class Netty5BufferEncoderTests extends AbstractEncoderTests<Netty5BufferEncoder>
super(new Netty5BufferEncoder()); super(new Netty5BufferEncoder());
} }
@Override
@Test @Test
@Override
public void canEncode() { public void canEncode() {
assertThat(this.encoder.canEncode(ResolvableType.forClass(Buffer.class), assertThat(this.encoder.canEncode(ResolvableType.forClass(Buffer.class),
MimeTypeUtils.TEXT_PLAIN)).isTrue(); MimeTypeUtils.TEXT_PLAIN)).isTrue();
@ -56,8 +56,9 @@ class Netty5BufferEncoderTests extends AbstractEncoderTests<Netty5BufferEncoder>
assertThat(this.encoder.canEncode(ResolvableType.NONE, null)).isFalse(); assertThat(this.encoder.canEncode(ResolvableType.NONE, null)).isFalse();
} }
@Override
@Test @Test
@Override
@SuppressWarnings("resource")
public void encode() { public void encode() {
Flux<Buffer> input = Flux.just(this.fooBytes, this.barBytes) Flux<Buffer> input = Flux.just(this.fooBytes, this.barBytes)
.map(DefaultBufferAllocators.preferredAllocator()::copyOf); .map(DefaultBufferAllocators.preferredAllocator()::copyOf);
@ -67,4 +68,5 @@ class Netty5BufferEncoderTests extends AbstractEncoderTests<Netty5BufferEncoder>
.consumeNextWith(expectBytes(this.barBytes)) .consumeNextWith(expectBytes(this.barBytes))
.verifyComplete()); .verifyComplete());
} }
} }

View File

@ -389,6 +389,7 @@ class DataBufferTests extends AbstractDataBufferAllocatingTests {
} }
@ParameterizedDataBufferAllocatingTest @ParameterizedDataBufferAllocatingTest
@SuppressWarnings("deprecation")
void increaseCapacity(DataBufferFactory bufferFactory) { void increaseCapacity(DataBufferFactory bufferFactory) {
super.bufferFactory = bufferFactory; super.bufferFactory = bufferFactory;
@ -402,6 +403,7 @@ class DataBufferTests extends AbstractDataBufferAllocatingTests {
} }
@ParameterizedDataBufferAllocatingTest @ParameterizedDataBufferAllocatingTest
@SuppressWarnings("deprecation")
void decreaseCapacityLowReadPosition(DataBufferFactory bufferFactory) { void decreaseCapacityLowReadPosition(DataBufferFactory bufferFactory) {
assumeFalse(bufferFactory instanceof Netty5DataBufferFactory, assumeFalse(bufferFactory instanceof Netty5DataBufferFactory,
"Netty 5 does not support decreasing the capacity"); "Netty 5 does not support decreasing the capacity");
@ -417,6 +419,7 @@ class DataBufferTests extends AbstractDataBufferAllocatingTests {
} }
@ParameterizedDataBufferAllocatingTest @ParameterizedDataBufferAllocatingTest
@SuppressWarnings("deprecation")
void decreaseCapacityHighReadPosition(DataBufferFactory bufferFactory) { void decreaseCapacityHighReadPosition(DataBufferFactory bufferFactory) {
assumeFalse(bufferFactory instanceof Netty5DataBufferFactory, assumeFalse(bufferFactory instanceof Netty5DataBufferFactory,
"Netty 5 does not support decreasing the capacity"); "Netty 5 does not support decreasing the capacity");
@ -433,13 +436,13 @@ class DataBufferTests extends AbstractDataBufferAllocatingTests {
} }
@ParameterizedDataBufferAllocatingTest @ParameterizedDataBufferAllocatingTest
@SuppressWarnings("deprecation")
void capacityLessThanZero(DataBufferFactory bufferFactory) { void capacityLessThanZero(DataBufferFactory bufferFactory) {
super.bufferFactory = bufferFactory; super.bufferFactory = bufferFactory;
DataBuffer buffer = createDataBuffer(1); DataBuffer buffer = createDataBuffer(1);
try { try {
assertThatIllegalArgumentException().isThrownBy(() -> assertThatIllegalArgumentException().isThrownBy(() -> buffer.capacity(-1));
buffer.capacity(-1));
} }
finally { finally {
release(buffer); release(buffer);
@ -754,6 +757,7 @@ class DataBufferTests extends AbstractDataBufferAllocatingTests {
} }
@ParameterizedDataBufferAllocatingTest @ParameterizedDataBufferAllocatingTest
@SuppressWarnings("deprecation")
void spr16351(DataBufferFactory bufferFactory) { void spr16351(DataBufferFactory bufferFactory) {
super.bufferFactory = bufferFactory; super.bufferFactory = bufferFactory;

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2019 the original author or authors. * Copyright 2002-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -32,11 +32,11 @@ class LeakAwareDataBufferFactoryTests {
@Test @Test
@SuppressWarnings("deprecation")
void leak() { void leak() {
DataBuffer dataBuffer = this.bufferFactory.allocateBuffer(); DataBuffer dataBuffer = this.bufferFactory.allocateBuffer();
try { try {
assertThatExceptionOfType(AssertionError.class).isThrownBy( assertThatExceptionOfType(AssertionError.class).isThrownBy(this.bufferFactory::checkForLeaks);
this.bufferFactory::checkForLeaks);
} }
finally { finally {
release(dataBuffer); release(dataBuffer);
@ -45,7 +45,7 @@ class LeakAwareDataBufferFactoryTests {
@Test @Test
void noLeak() { void noLeak() {
DataBuffer dataBuffer = this.bufferFactory.allocateBuffer(); DataBuffer dataBuffer = this.bufferFactory.allocateBuffer(256);
release(dataBuffer); release(dataBuffer);
this.bufferFactory.checkForLeaks(); this.bufferFactory.checkForLeaks();
} }

View File

@ -99,7 +99,7 @@ public class LeakAwareDataBufferFactory implements DataBufferFactory {
List<AssertionError> errors = this.created.stream() List<AssertionError> errors = this.created.stream()
.filter(LeakAwareDataBuffer::isAllocated) .filter(LeakAwareDataBuffer::isAllocated)
.map(LeakAwareDataBuffer::leakError) .map(LeakAwareDataBuffer::leakError)
.collect(Collectors.toList()); .toList();
errors.forEach(it -> logger.error("Leaked error: ", it)); errors.forEach(it -> logger.error("Leaked error: ", it));
throw new AssertionError(errors.size() + " buffer leaks detected (see logs above)"); throw new AssertionError(errors.size() + " buffer leaks detected (see logs above)");

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2019 the original author or authors. * Copyright 2002-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -47,12 +47,11 @@ import static org.springframework.util.MimeTypeUtils.TEXT_HTML;
import static org.springframework.util.MimeTypeUtils.TEXT_PLAIN; import static org.springframework.util.MimeTypeUtils.TEXT_PLAIN;
import static org.springframework.util.MimeTypeUtils.TEXT_XML; import static org.springframework.util.MimeTypeUtils.TEXT_XML;
/** /**
* Unit tests for {@link DefaultMetadataExtractor}. * Unit tests for {@link DefaultMetadataExtractor}.
* @author Rossen Stoyanchev * @author Rossen Stoyanchev
*/ */
public class DefaultMetadataExtractorTests { class DefaultMetadataExtractorTests {
private static MimeType COMPOSITE_METADATA = private static MimeType COMPOSITE_METADATA =
MimeTypeUtils.parseMimeType(WellKnownMimeType.MESSAGE_RSOCKET_COMPOSITE_METADATA.getString()); MimeTypeUtils.parseMimeType(WellKnownMimeType.MESSAGE_RSOCKET_COMPOSITE_METADATA.getString());
@ -64,21 +63,21 @@ public class DefaultMetadataExtractorTests {
@BeforeEach @BeforeEach
public void setUp() { void setUp() {
DataBufferFactory bufferFactory = new LeakAwareNettyDataBufferFactory(PooledByteBufAllocator.DEFAULT); DataBufferFactory bufferFactory = new LeakAwareNettyDataBufferFactory(PooledByteBufAllocator.DEFAULT);
this.strategies = RSocketStrategies.builder().dataBufferFactory(bufferFactory).build(); this.strategies = RSocketStrategies.builder().dataBufferFactory(bufferFactory).build();
this.extractor = new DefaultMetadataExtractor(StringDecoder.allMimeTypes()); this.extractor = new DefaultMetadataExtractor(StringDecoder.allMimeTypes());
} }
@AfterEach @AfterEach
public void tearDown() throws InterruptedException { void tearDown() throws InterruptedException {
DataBufferFactory bufferFactory = this.strategies.dataBufferFactory(); DataBufferFactory bufferFactory = this.strategies.dataBufferFactory();
((LeakAwareNettyDataBufferFactory) bufferFactory).checkForLeaks(Duration.ofSeconds(5)); ((LeakAwareNettyDataBufferFactory) bufferFactory).checkForLeaks(Duration.ofSeconds(5));
} }
@Test @Test
public void compositeMetadataWithDefaultSettings() { void compositeMetadataWithDefaultSettings() {
MetadataEncoder metadataEncoder = new MetadataEncoder(COMPOSITE_METADATA, this.strategies) MetadataEncoder metadataEncoder = new MetadataEncoder(COMPOSITE_METADATA, this.strategies)
.route("toA") .route("toA")
.metadata("text data", TEXT_PLAIN) .metadata("text data", TEXT_PLAIN)
@ -94,7 +93,7 @@ public class DefaultMetadataExtractorTests {
} }
@Test @Test
public void compositeMetadataWithMimeTypeRegistrations() { void compositeMetadataWithMimeTypeRegistrations() {
this.extractor.metadataToExtract(TEXT_PLAIN, String.class, "text-entry"); this.extractor.metadataToExtract(TEXT_PLAIN, String.class, "text-entry");
this.extractor.metadataToExtract(TEXT_HTML, String.class, "html-entry"); this.extractor.metadataToExtract(TEXT_HTML, String.class, "html-entry");
this.extractor.metadataToExtract(TEXT_XML, String.class, "xml-entry"); this.extractor.metadataToExtract(TEXT_XML, String.class, "xml-entry");
@ -118,7 +117,7 @@ public class DefaultMetadataExtractorTests {
} }
@Test @Test
public void route() { void route() {
MimeType metaMimeType = MimeTypeUtils.parseMimeType(WellKnownMimeType.MESSAGE_RSOCKET_ROUTING.getString()); MimeType metaMimeType = MimeTypeUtils.parseMimeType(WellKnownMimeType.MESSAGE_RSOCKET_ROUTING.getString());
MetadataEncoder metadataEncoder = new MetadataEncoder(metaMimeType, this.strategies).route("toA"); MetadataEncoder metadataEncoder = new MetadataEncoder(metaMimeType, this.strategies).route("toA");
DataBuffer metadata = metadataEncoder.encode().block(); DataBuffer metadata = metadataEncoder.encode().block();
@ -130,7 +129,7 @@ public class DefaultMetadataExtractorTests {
} }
@Test @Test
public void routeAsText() { void routeAsText() {
this.extractor.metadataToExtract(TEXT_PLAIN, String.class, ROUTE_KEY); this.extractor.metadataToExtract(TEXT_PLAIN, String.class, ROUTE_KEY);
MetadataEncoder metadataEncoder = new MetadataEncoder(TEXT_PLAIN, this.strategies).route("toA"); MetadataEncoder metadataEncoder = new MetadataEncoder(TEXT_PLAIN, this.strategies).route("toA");
@ -143,7 +142,7 @@ public class DefaultMetadataExtractorTests {
} }
@Test @Test
public void routeWithCustomFormatting() { void routeWithCustomFormatting() {
this.extractor.metadataToExtract(TEXT_PLAIN, String.class, (text, result) -> { this.extractor.metadataToExtract(TEXT_PLAIN, String.class, (text, result) -> {
String[] items = text.split(":"); String[] items = text.split(":");
Assert.isTrue(items.length == 2, "Expected two items"); Assert.isTrue(items.length == 2, "Expected two items");
@ -163,7 +162,7 @@ public class DefaultMetadataExtractorTests {
} }
@Test @Test
public void nonCompositeMetadataCanBeReadTwice() { void nonCompositeMetadataCanBeReadTwice() {
DefaultMetadataExtractor extractor = new DefaultMetadataExtractor(new TestDecoder()); DefaultMetadataExtractor extractor = new DefaultMetadataExtractor(new TestDecoder());
extractor.metadataToExtract(TEXT_PLAIN, String.class, "name"); extractor.metadataToExtract(TEXT_PLAIN, String.class, "name");
@ -181,7 +180,7 @@ public class DefaultMetadataExtractorTests {
} }
@Test @Test
public void noDecoder() { void noDecoder() {
DefaultMetadataExtractor extractor = DefaultMetadataExtractor extractor =
new DefaultMetadataExtractor(Collections.singletonList(new ByteArrayDecoder()) new DefaultMetadataExtractor(Collections.singletonList(new ByteArrayDecoder())
); );
@ -193,7 +192,7 @@ public class DefaultMetadataExtractorTests {
private Payload createPayload(DataBuffer metadata) { private Payload createPayload(DataBuffer metadata) {
return PayloadUtils.createPayload(this.strategies.dataBufferFactory().allocateBuffer(), metadata); return PayloadUtils.createPayload(this.strategies.dataBufferFactory().allocateBuffer(256), metadata);
} }
@ -203,7 +202,7 @@ public class DefaultMetadataExtractorTests {
*/ */
private static class TestDecoder extends AbstractDataBufferDecoder<String> { private static class TestDecoder extends AbstractDataBufferDecoder<String> {
public TestDecoder() { TestDecoder() {
super(TEXT_PLAIN); super(TEXT_PLAIN);
} }
@ -217,4 +216,5 @@ public class DefaultMetadataExtractorTests {
return new String(bytes, StandardCharsets.UTF_8); return new String(bytes, StandardCharsets.UTF_8);
} }
} }
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2019 the original author or authors. * Copyright 2002-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -52,8 +52,8 @@ public class LeakAwareNettyDataBufferFactory extends NettyDataBufferFactory {
while (true) { while (true) {
try { try {
this.created.forEach(info -> { this.created.forEach(info -> {
if (((PooledDataBuffer) info.getDataBuffer()).isAllocated()) { if (((PooledDataBuffer) info.dataBuffer()).isAllocated()) {
throw info.getError(); throw info.error();
} }
}); });
break; break;
@ -73,6 +73,7 @@ public class LeakAwareNettyDataBufferFactory extends NettyDataBufferFactory {
@Override @Override
@SuppressWarnings("deprecation")
public NettyDataBuffer allocateBuffer() { public NettyDataBuffer allocateBuffer() {
return (NettyDataBuffer) recordHint(super.allocateBuffer()); return (NettyDataBuffer) recordHint(super.allocateBuffer());
} }
@ -105,23 +106,7 @@ public class LeakAwareNettyDataBufferFactory extends NettyDataBufferFactory {
} }
private static class DataBufferLeakInfo { private static record DataBufferLeakInfo(DataBuffer dataBuffer, AssertionError error) {
private final DataBuffer dataBuffer;
private final AssertionError error;
DataBufferLeakInfo(DataBuffer dataBuffer, AssertionError error) {
this.dataBuffer = dataBuffer;
this.error = error;
} }
DataBuffer getDataBuffer() {
return this.dataBuffer;
}
AssertionError getError() {
return this.error;
}
}
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2020 the original author or authors. * Copyright 2002-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -42,11 +42,10 @@ import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.assertThatThrownBy;
/** /**
*
* @author Rossen Stoyanchev * @author Rossen Stoyanchev
* @since 5.2 * @since 5.2
*/ */
public class MetadataEncoderTests { class MetadataEncoderTests {
private static MimeType COMPOSITE_METADATA = private static MimeType COMPOSITE_METADATA =
MimeTypeUtils.parseMimeType(WellKnownMimeType.MESSAGE_RSOCKET_COMPOSITE_METADATA.getString()); MimeTypeUtils.parseMimeType(WellKnownMimeType.MESSAGE_RSOCKET_COMPOSITE_METADATA.getString());
@ -56,7 +55,7 @@ public class MetadataEncoderTests {
@Test @Test
public void compositeMetadata() { void compositeMetadata() {
Mono<String> asyncMeta1 = Mono.delay(Duration.ofMillis(1)).map(aLong -> "Async Metadata 1"); Mono<String> asyncMeta1 = Mono.delay(Duration.ofMillis(1)).map(aLong -> "Async Metadata 1");
Mono<String> asyncMeta2 = Mono.delay(Duration.ofMillis(1)).map(aLong -> "Async Metadata 2"); Mono<String> asyncMeta2 = Mono.delay(Duration.ofMillis(1)).map(aLong -> "Async Metadata 2");
@ -102,7 +101,7 @@ public class MetadataEncoderTests {
} }
@Test @Test
public void routeWithRoutingMimeType() { void routeWithRoutingMimeType() {
MimeType mimeType = MimeTypeUtils.parseMimeType( MimeType mimeType = MimeTypeUtils.parseMimeType(
WellKnownMimeType.MESSAGE_RSOCKET_ROUTING.getString()); WellKnownMimeType.MESSAGE_RSOCKET_ROUTING.getString());
@ -117,7 +116,7 @@ public class MetadataEncoderTests {
} }
@Test @Test
public void routeWithTextPlainMimeType() { void routeWithTextPlainMimeType() {
DataBuffer buffer = DataBuffer buffer =
new MetadataEncoder(MimeTypeUtils.TEXT_PLAIN, this.strategies) new MetadataEncoder(MimeTypeUtils.TEXT_PLAIN, this.strategies)
.route("toA") .route("toA")
@ -128,7 +127,7 @@ public class MetadataEncoderTests {
} }
@Test @Test
public void routeWithVars() { void routeWithVars() {
DataBuffer buffer = DataBuffer buffer =
new MetadataEncoder(MimeTypeUtils.TEXT_PLAIN, this.strategies) new MetadataEncoder(MimeTypeUtils.TEXT_PLAIN, this.strategies)
.route("a.{b}.{c}.d", "BBB", "C.C.C") .route("a.{b}.{c}.d", "BBB", "C.C.C")
@ -139,7 +138,7 @@ public class MetadataEncoderTests {
} }
@Test @Test
public void metadataWithTextPlainMimeType() { void metadataWithTextPlainMimeType() {
DataBuffer buffer = DataBuffer buffer =
new MetadataEncoder(MimeTypeUtils.TEXT_PLAIN, this.strategies) new MetadataEncoder(MimeTypeUtils.TEXT_PLAIN, this.strategies)
.metadata(Unpooled.wrappedBuffer("Raw data".getBytes(UTF_8)), null) .metadata(Unpooled.wrappedBuffer("Raw data".getBytes(UTF_8)), null)
@ -150,7 +149,7 @@ public class MetadataEncoderTests {
} }
@Test @Test
public void metadataWithByteBuf() { void metadataWithByteBuf() {
DataBuffer buffer = DataBuffer buffer =
new MetadataEncoder(MimeTypeUtils.TEXT_PLAIN, this.strategies) new MetadataEncoder(MimeTypeUtils.TEXT_PLAIN, this.strategies)
.metadata("toA", null) .metadata("toA", null)
@ -161,7 +160,7 @@ public class MetadataEncoderTests {
} }
@Test @Test
public void compositeRequiredForMultipleEntries() { void compositeRequiredForMultipleEntries() {
// Route, metadata // Route, metadata
MetadataEncoder encoder1 = new MetadataEncoder(MimeTypeUtils.TEXT_PLAIN, this.strategies); MetadataEncoder encoder1 = new MetadataEncoder(MimeTypeUtils.TEXT_PLAIN, this.strategies);
@ -186,7 +185,7 @@ public class MetadataEncoderTests {
} }
@Test @Test
public void mimeTypeRequiredForCompositeEntries() { void mimeTypeRequiredForCompositeEntries() {
MetadataEncoder encoder = new MetadataEncoder(COMPOSITE_METADATA, this.strategies); MetadataEncoder encoder = new MetadataEncoder(COMPOSITE_METADATA, this.strategies);
assertThatThrownBy(() -> encoder.metadata("toA", null)) assertThatThrownBy(() -> encoder.metadata("toA", null))
@ -194,7 +193,7 @@ public class MetadataEncoderTests {
} }
@Test @Test
public void mimeTypeDoesNotMatchConnectionMetadataMimeType() { void mimeTypeDoesNotMatchConnectionMetadataMimeType() {
MetadataEncoder encoder = new MetadataEncoder(MimeTypeUtils.TEXT_PLAIN, this.strategies); MetadataEncoder encoder = new MetadataEncoder(MimeTypeUtils.TEXT_PLAIN, this.strategies);
assertThatThrownBy(() -> encoder.metadata("toA", MimeTypeUtils.APPLICATION_JSON)) assertThatThrownBy(() -> encoder.metadata("toA", MimeTypeUtils.APPLICATION_JSON))
@ -203,7 +202,7 @@ public class MetadataEncoderTests {
} }
@Test @Test
public void defaultDataBufferFactory() { void defaultDataBufferFactory() {
DefaultDataBufferFactory bufferFactory = DefaultDataBufferFactory.sharedInstance; DefaultDataBufferFactory bufferFactory = DefaultDataBufferFactory.sharedInstance;
RSocketStrategies strategies = RSocketStrategies.builder().dataBufferFactory(bufferFactory).build(); RSocketStrategies strategies = RSocketStrategies.builder().dataBufferFactory(bufferFactory).build();
@ -213,7 +212,7 @@ public class MetadataEncoderTests {
.block(); .block();
ByteBuf byteBuf = new NettyDataBufferFactory(ByteBufAllocator.DEFAULT) ByteBuf byteBuf = new NettyDataBufferFactory(ByteBufAllocator.DEFAULT)
.wrap(buffer.asByteBuffer()) .wrap(buffer.toByteBuffer())
.getNativeBuffer(); .getNativeBuffer();
CompositeMetadata entries = new CompositeMetadata(byteBuf, false); CompositeMetadata entries = new CompositeMetadata(byteBuf, false);

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2020 the original author or authors. * Copyright 2002-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -37,23 +37,24 @@ import static org.assertj.core.api.Assertions.assertThat;
/** /**
* Unit tests for {@link PayloadUtils}. * Unit tests for {@link PayloadUtils}.
*
* @author Rossen Stoyanchev * @author Rossen Stoyanchev
* @since 5.2 * @since 5.2
*/ */
public class PayloadUtilsTests { class PayloadUtilsTests {
private LeakAwareNettyDataBufferFactory nettyBufferFactory = private LeakAwareNettyDataBufferFactory nettyBufferFactory =
new LeakAwareNettyDataBufferFactory(PooledByteBufAllocator.DEFAULT); new LeakAwareNettyDataBufferFactory(PooledByteBufAllocator.DEFAULT);
@AfterEach @AfterEach
public void tearDown() throws Exception { void tearDown() throws Exception {
this.nettyBufferFactory.checkForLeaks(Duration.ofSeconds(5)); this.nettyBufferFactory.checkForLeaks(Duration.ofSeconds(5));
} }
@Test @Test
public void retainAndReleaseWithNettyFactory() { void retainAndReleaseWithNettyFactory() {
Payload payload = ByteBufPayload.create("sample data"); Payload payload = ByteBufPayload.create("sample data");
DataBuffer buffer = PayloadUtils.retainDataAndReleasePayload(payload, this.nettyBufferFactory); DataBuffer buffer = PayloadUtils.retainDataAndReleasePayload(payload, this.nettyBufferFactory);
try { try {
@ -67,7 +68,7 @@ public class PayloadUtilsTests {
} }
@Test @Test
public void retainAndReleaseWithDefaultFactory() { void retainAndReleaseWithDefaultFactory() {
Payload payload = ByteBufPayload.create("sample data"); Payload payload = ByteBufPayload.create("sample data");
DataBuffer buffer = PayloadUtils.retainDataAndReleasePayload(payload, DefaultDataBufferFactory.sharedInstance); DataBuffer buffer = PayloadUtils.retainDataAndReleasePayload(payload, DefaultDataBufferFactory.sharedInstance);
@ -76,7 +77,7 @@ public class PayloadUtilsTests {
} }
@Test @Test
public void createWithNettyBuffers() { void createWithNettyBuffers() {
NettyDataBuffer data = createNettyDataBuffer("sample data"); NettyDataBuffer data = createNettyDataBuffer("sample data");
NettyDataBuffer metadata = createNettyDataBuffer("sample metadata"); NettyDataBuffer metadata = createNettyDataBuffer("sample metadata");
@ -92,7 +93,7 @@ public class PayloadUtilsTests {
} }
@Test @Test
public void createWithDefaultBuffers() { void createWithDefaultBuffers() {
DataBuffer data = createDefaultDataBuffer("sample data"); DataBuffer data = createDefaultDataBuffer("sample data");
DataBuffer metadata = createDefaultDataBuffer("sample metadata"); DataBuffer metadata = createDefaultDataBuffer("sample metadata");
Payload payload = PayloadUtils.createPayload(data, metadata); Payload payload = PayloadUtils.createPayload(data, metadata);
@ -103,7 +104,7 @@ public class PayloadUtilsTests {
} }
@Test @Test
public void createWithNettyAndDefaultBuffers() { void createWithNettyAndDefaultBuffers() {
NettyDataBuffer data = createNettyDataBuffer("sample data"); NettyDataBuffer data = createNettyDataBuffer("sample data");
DefaultDataBuffer metadata = createDefaultDataBuffer("sample metadata"); DefaultDataBuffer metadata = createDefaultDataBuffer("sample metadata");
Payload payload = PayloadUtils.createPayload(data, metadata); Payload payload = PayloadUtils.createPayload(data, metadata);
@ -118,7 +119,7 @@ public class PayloadUtilsTests {
} }
@Test @Test
public void createWithDefaultAndNettyBuffers() { void createWithDefaultAndNettyBuffers() {
DefaultDataBuffer data = createDefaultDataBuffer("sample data"); DefaultDataBuffer data = createDefaultDataBuffer("sample data");
NettyDataBuffer metadata = createNettyDataBuffer("sample metadata"); NettyDataBuffer metadata = createNettyDataBuffer("sample metadata");
Payload payload = PayloadUtils.createPayload(data, metadata); Payload payload = PayloadUtils.createPayload(data, metadata);
@ -133,7 +134,7 @@ public class PayloadUtilsTests {
} }
@Test @Test
public void createWithNettyBuffer() { void createWithNettyBuffer() {
NettyDataBuffer data = createNettyDataBuffer("sample data"); NettyDataBuffer data = createNettyDataBuffer("sample data");
Payload payload = PayloadUtils.createPayload(data); Payload payload = PayloadUtils.createPayload(data);
try { try {
@ -146,7 +147,7 @@ public class PayloadUtilsTests {
} }
@Test @Test
public void createWithDefaultBuffer() { void createWithDefaultBuffer() {
DataBuffer data = createDefaultDataBuffer("sample data"); DataBuffer data = createDefaultDataBuffer("sample data");
Payload payload = PayloadUtils.createPayload(data); Payload payload = PayloadUtils.createPayload(data);
@ -162,7 +163,7 @@ public class PayloadUtilsTests {
} }
private DefaultDataBuffer createDefaultDataBuffer(String content) { private DefaultDataBuffer createDefaultDataBuffer(String content) {
DefaultDataBuffer buffer = DefaultDataBufferFactory.sharedInstance.allocateBuffer(); DefaultDataBuffer buffer = DefaultDataBufferFactory.sharedInstance.allocateBuffer(256);
buffer.write(content, StandardCharsets.UTF_8); buffer.write(content, StandardCharsets.UTF_8);
return buffer; return buffer;
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2020 the original author or authors. * Copyright 2002-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -30,13 +30,13 @@ import org.springframework.web.server.WebFilter;
* Tests for a {@link WebFilter}. * Tests for a {@link WebFilter}.
* @author Rossen Stoyanchev * @author Rossen Stoyanchev
*/ */
public class WebFilterTests { class WebFilterTests {
@Test @Test
public void testWebFilter() throws Exception { void webFilter() {
WebFilter filter = (exchange, chain) -> { WebFilter filter = (exchange, chain) -> {
DataBuffer buffer = DefaultDataBufferFactory.sharedInstance.allocateBuffer(); DataBuffer buffer = DefaultDataBufferFactory.sharedInstance.allocateBuffer(256);
buffer.write("It works!".getBytes(StandardCharsets.UTF_8)); buffer.write("It works!".getBytes(StandardCharsets.UTF_8));
return exchange.getResponse().writeWith(Mono.just(buffer)); return exchange.getResponse().writeWith(Mono.just(buffer));
}; };

View File

@ -165,6 +165,7 @@ public class MultipartWriterSupport extends LoggingCodecSupport {
protected Mono<DataBuffer> generatePartHeaders(HttpHeaders headers, DataBufferFactory bufferFactory) { protected Mono<DataBuffer> generatePartHeaders(HttpHeaders headers, DataBufferFactory bufferFactory) {
return Mono.fromCallable(() -> { return Mono.fromCallable(() -> {
@SuppressWarnings("resource")
FastByteArrayOutputStream bos = new FastByteArrayOutputStream(); FastByteArrayOutputStream bos = new FastByteArrayOutputStream();
for (Map.Entry<String, List<String>> entry : headers.entrySet()) { for (Map.Entry<String, List<String>> entry : headers.entrySet()) {
byte[] headerName = entry.getKey().getBytes(getCharset()); byte[] headerName = entry.getKey().getBytes(getCharset());

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2019 the original author or authors. * Copyright 2002-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -65,12 +65,11 @@ public class ProtobufDecoderTests extends AbstractDecoderTests<ProtobufDecoder>
@Test @Test
public void extensionRegistryNull() { public void extensionRegistryNull() {
assertThatIllegalArgumentException().isThrownBy(() -> assertThatIllegalArgumentException().isThrownBy(() -> new ProtobufDecoder(null));
new ProtobufDecoder(null));
} }
@Override
@Test @Test
@Override
public void canDecode() { public void canDecode() {
assertThat(this.decoder.canDecode(forClass(Msg.class), null)).isTrue(); assertThat(this.decoder.canDecode(forClass(Msg.class), null)).isTrue();
assertThat(this.decoder.canDecode(forClass(Msg.class), PROTOBUF_MIME_TYPE)).isTrue(); assertThat(this.decoder.canDecode(forClass(Msg.class), PROTOBUF_MIME_TYPE)).isTrue();
@ -79,8 +78,8 @@ public class ProtobufDecoderTests extends AbstractDecoderTests<ProtobufDecoder>
assertThat(this.decoder.canDecode(forClass(Object.class), PROTOBUF_MIME_TYPE)).isFalse(); assertThat(this.decoder.canDecode(forClass(Object.class), PROTOBUF_MIME_TYPE)).isFalse();
} }
@Override
@Test @Test
@Override
public void decodeToMono() { public void decodeToMono() {
Mono<DataBuffer> input = dataBuffer(this.testMsg1); Mono<DataBuffer> input = dataBuffer(this.testMsg1);
@ -107,8 +106,9 @@ public class ProtobufDecoderTests extends AbstractDecoderTests<ProtobufDecoder>
.verifyComplete()); .verifyComplete());
} }
@Override
@Test @Test
@Override
@SuppressWarnings("deprecation")
public void decode() { public void decode() {
Flux<DataBuffer> input = Flux.just(this.testMsg1, this.testMsg2) Flux<DataBuffer> input = Flux.just(this.testMsg1, this.testMsg2)
.flatMap(msg -> Mono.defer(() -> { .flatMap(msg -> Mono.defer(() -> {
@ -130,9 +130,8 @@ public class ProtobufDecoderTests extends AbstractDecoderTests<ProtobufDecoder>
} }
@Test @Test
@SuppressWarnings("deprecation")
public void decodeSplitChunks() { public void decodeSplitChunks() {
Flux<DataBuffer> input = Flux.just(this.testMsg1, this.testMsg2) Flux<DataBuffer> input = Flux.just(this.testMsg1, this.testMsg2)
.flatMap(msg -> Mono.defer(() -> { .flatMap(msg -> Mono.defer(() -> {
DataBuffer buffer = this.bufferFactory.allocateBuffer(); DataBuffer buffer = this.bufferFactory.allocateBuffer();
@ -163,6 +162,7 @@ public class ProtobufDecoderTests extends AbstractDecoderTests<ProtobufDecoder>
} }
@Test // SPR-17429 @Test // SPR-17429
@SuppressWarnings("deprecation")
public void decodeSplitMessageSize() { public void decodeSplitMessageSize() {
this.decoder.setMaxMessageSize(100009); this.decoder.setMaxMessageSize(100009);
StringBuilder builder = new StringBuilder(); StringBuilder builder = new StringBuilder();
@ -201,6 +201,7 @@ public class ProtobufDecoderTests extends AbstractDecoderTests<ProtobufDecoder>
} }
@Test @Test
@SuppressWarnings("deprecation")
public void decodeMergedChunks() throws IOException { public void decodeMergedChunks() throws IOException {
DataBuffer buffer = this.bufferFactory.allocateBuffer(); DataBuffer buffer = this.bufferFactory.allocateBuffer();
this.testMsg1.writeDelimitedTo(buffer.asOutputStream()); this.testMsg1.writeDelimitedTo(buffer.asOutputStream());
@ -220,8 +221,7 @@ public class ProtobufDecoderTests extends AbstractDecoderTests<ProtobufDecoder>
this.decoder.setMaxMessageSize(1); this.decoder.setMaxMessageSize(1);
Mono<DataBuffer> input = dataBuffer(this.testMsg1); Mono<DataBuffer> input = dataBuffer(this.testMsg1);
testDecode(input, Msg.class, step -> step testDecode(input, Msg.class, step -> step.verifyError(DecodingException.class));
.verifyError(DecodingException.class));
} }
private Mono<DataBuffer> dataBuffer(Msg msg) { private Mono<DataBuffer> dataBuffer(Msg msg) {
@ -233,5 +233,4 @@ public class ProtobufDecoderTests extends AbstractDecoderTests<ProtobufDecoder>
}); });
} }
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2020 the original author or authors. * Copyright 2002-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -61,6 +61,7 @@ class AsyncIntegrationTests extends AbstractHttpHandlerIntegrationTests {
private class AsyncHandler implements HttpHandler { private class AsyncHandler implements HttpHandler {
@Override @Override
@SuppressWarnings("deprecation")
public Mono<Void> handle(ServerHttpRequest request, ServerHttpResponse response) { public Mono<Void> handle(ServerHttpRequest request, ServerHttpResponse response) {
return response.writeWith(Flux.just("h", "e", "l", "l", "o") return response.writeWith(Flux.just("h", "e", "l", "l", "o")
.delayElements(Duration.ofMillis(100)) .delayElements(Duration.ofMillis(100))

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2019 the original author or authors. * Copyright 2002-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -43,13 +43,13 @@ import static org.assertj.core.api.Assertions.assertThat;
* @author Rossen Stoyanchev * @author Rossen Stoyanchev
* @author Stephane Maldini * @author Stephane Maldini
*/ */
public class ChannelSendOperatorTests { class ChannelSendOperatorTests {
private final OneByOneAsyncWriter writer = new OneByOneAsyncWriter(); private final OneByOneAsyncWriter writer = new OneByOneAsyncWriter();
@Test @Test
public void errorBeforeFirstItem() throws Exception { void errorBeforeFirstItem() throws Exception {
IllegalStateException error = new IllegalStateException("boo"); IllegalStateException error = new IllegalStateException("boo");
Mono<Void> completion = Mono.<String>error(error).as(this::sendOperator); Mono<Void> completion = Mono.<String>error(error).as(this::sendOperator);
Signal<Void> signal = completion.materialize().block(); Signal<Void> signal = completion.materialize().block();
@ -59,7 +59,7 @@ public class ChannelSendOperatorTests {
} }
@Test @Test
public void completionBeforeFirstItem() throws Exception { void completionBeforeFirstItem() throws Exception {
Mono<Void> completion = Flux.<String>empty().as(this::sendOperator); Mono<Void> completion = Flux.<String>empty().as(this::sendOperator);
Signal<Void> signal = completion.materialize().block(); Signal<Void> signal = completion.materialize().block();
@ -71,7 +71,7 @@ public class ChannelSendOperatorTests {
} }
@Test @Test
public void writeOneItem() throws Exception { void writeOneItem() throws Exception {
Mono<Void> completion = Flux.just("one").as(this::sendOperator); Mono<Void> completion = Flux.just("one").as(this::sendOperator);
Signal<Void> signal = completion.materialize().block(); Signal<Void> signal = completion.materialize().block();
@ -85,7 +85,7 @@ public class ChannelSendOperatorTests {
@Test @Test
public void writeMultipleItems() { void writeMultipleItems() {
List<String> items = Arrays.asList("one", "two", "three"); List<String> items = Arrays.asList("one", "two", "three");
Mono<Void> completion = Flux.fromIterable(items).as(this::sendOperator); Mono<Void> completion = Flux.fromIterable(items).as(this::sendOperator);
Signal<Void> signal = completion.materialize().block(); Signal<Void> signal = completion.materialize().block();
@ -101,7 +101,7 @@ public class ChannelSendOperatorTests {
} }
@Test @Test
public void errorAfterMultipleItems() { void errorAfterMultipleItems() {
IllegalStateException error = new IllegalStateException("boo"); IllegalStateException error = new IllegalStateException("boo");
Flux<String> publisher = Flux.generate(() -> 0, (idx , subscriber) -> { Flux<String> publisher = Flux.generate(() -> 0, (idx , subscriber) -> {
int i = ++idx; int i = ++idx;
@ -125,12 +125,12 @@ public class ChannelSendOperatorTests {
} }
@Test // gh-22720 @Test // gh-22720
public void cancelWhileItemCached() { void cancelWhileItemCached() {
LeakAwareDataBufferFactory bufferFactory = new LeakAwareDataBufferFactory(); LeakAwareDataBufferFactory bufferFactory = new LeakAwareDataBufferFactory();
ChannelSendOperator<DataBuffer> operator = new ChannelSendOperator<>( ChannelSendOperator<DataBuffer> operator = new ChannelSendOperator<>(
Mono.fromCallable(() -> { Mono.fromCallable(() -> {
DataBuffer dataBuffer = bufferFactory.allocateBuffer(); DataBuffer dataBuffer = bufferFactory.allocateBuffer(256);
dataBuffer.write("foo", StandardCharsets.UTF_8); dataBuffer.write("foo", StandardCharsets.UTF_8);
return dataBuffer; return dataBuffer;
}), }),
@ -148,7 +148,7 @@ public class ChannelSendOperatorTests {
} }
@Test // gh-22720 @Test // gh-22720
public void errorFromWriteSourceWhileItemCached() { void errorFromWriteSourceWhileItemCached() {
// 1. First item received // 1. First item received
// 2. writeFunction applied and writeCompletionBarrier subscribed to it // 2. writeFunction applied and writeCompletionBarrier subscribed to it
@ -159,7 +159,7 @@ public class ChannelSendOperatorTests {
ChannelSendOperator<DataBuffer> operator = new ChannelSendOperator<>( ChannelSendOperator<DataBuffer> operator = new ChannelSendOperator<>(
Flux.create(sink -> { Flux.create(sink -> {
DataBuffer dataBuffer = bufferFactory.allocateBuffer(); DataBuffer dataBuffer = bufferFactory.allocateBuffer(256);
dataBuffer.write("foo", StandardCharsets.UTF_8); dataBuffer.write("foo", StandardCharsets.UTF_8);
sink.next(dataBuffer); sink.next(dataBuffer);
sink.error(new IllegalStateException("err")); sink.error(new IllegalStateException("err"));
@ -169,7 +169,6 @@ public class ChannelSendOperatorTests {
return Mono.never(); return Mono.never();
}); });
operator.subscribe(new BaseSubscriber<Void>() {}); operator.subscribe(new BaseSubscriber<Void>() {});
try { try {
writeSubscriber.signalDemand(1); // Let cached signals ("foo" and error) be published.. writeSubscriber.signalDemand(1); // Let cached signals ("foo" and error) be published..
@ -183,7 +182,7 @@ public class ChannelSendOperatorTests {
} }
@Test // gh-22720 @Test // gh-22720
public void errorFromWriteFunctionWhileItemCached() { void errorFromWriteFunctionWhileItemCached() {
// 1. First item received // 1. First item received
// 2. writeFunction applied and writeCompletionBarrier subscribed to it // 2. writeFunction applied and writeCompletionBarrier subscribed to it
@ -193,7 +192,7 @@ public class ChannelSendOperatorTests {
ChannelSendOperator<DataBuffer> operator = new ChannelSendOperator<>( ChannelSendOperator<DataBuffer> operator = new ChannelSendOperator<>(
Flux.create(sink -> { Flux.create(sink -> {
DataBuffer dataBuffer = bufferFactory.allocateBuffer(); DataBuffer dataBuffer = bufferFactory.allocateBuffer(256);
dataBuffer.write("foo", StandardCharsets.UTF_8); dataBuffer.write("foo", StandardCharsets.UTF_8);
sink.next(dataBuffer); sink.next(dataBuffer);
}), }),
@ -207,7 +206,7 @@ public class ChannelSendOperatorTests {
} }
@Test // gh-23175 @Test // gh-23175
public void errorInWriteFunction() { void errorInWriteFunction() {
StepVerifier StepVerifier
.create(new ChannelSendOperator<>(Mono.just("one"), p -> { .create(new ChannelSendOperator<>(Mono.just("one"), p -> {
@ -251,7 +250,7 @@ public class ChannelSendOperatorTests {
private final Subscriber<? super Void> subscriber; private final Subscriber<? super Void> subscriber;
public WriteSubscriber(Subscriber<? super Void> subscriber) { WriteSubscriber(Subscriber<? super Void> subscriber) {
this.subscriber = subscriber; this.subscriber = subscriber;
} }
@ -284,7 +283,6 @@ public class ChannelSendOperatorTests {
private static class ZeroDemandSubscriber extends BaseSubscriber<DataBuffer> { private static class ZeroDemandSubscriber extends BaseSubscriber<DataBuffer> {
@Override @Override
protected void hookOnSubscribe(Subscription subscription) { protected void hookOnSubscribe(Subscription subscription) {
// Just subscribe without requesting // Just subscribe without requesting

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2020 the original author or authors. * Copyright 2002-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -34,9 +34,10 @@ import static org.assertj.core.api.Assertions.assertThat;
/** /**
* Unit tests for {@link HttpHeadResponseDecorator}. * Unit tests for {@link HttpHeadResponseDecorator}.
*
* @author Rossen Stoyanchev * @author Rossen Stoyanchev
*/ */
public class HttpHeadResponseDecoratorTests { class HttpHeadResponseDecoratorTests {
private final LeakAwareDataBufferFactory bufferFactory = private final LeakAwareDataBufferFactory bufferFactory =
new LeakAwareDataBufferFactory(new NettyDataBufferFactory(PooledByteBufAllocator.DEFAULT)); new LeakAwareDataBufferFactory(new NettyDataBufferFactory(PooledByteBufAllocator.DEFAULT));
@ -46,27 +47,27 @@ public class HttpHeadResponseDecoratorTests {
@AfterEach @AfterEach
public void tearDown() { void tearDown() {
this.bufferFactory.checkForLeaks(); this.bufferFactory.checkForLeaks();
} }
@Test @Test
public void writeWithFlux() { void writeWithFlux() {
Flux<DataBuffer> body = Flux.just(toDataBuffer("data1"), toDataBuffer("data2")); Flux<DataBuffer> body = Flux.just(toDataBuffer("data1"), toDataBuffer("data2"));
this.response.writeWith(body).block(); this.response.writeWith(body).block();
assertThat(this.response.getHeaders().getContentLength()).isEqualTo(-1); assertThat(this.response.getHeaders().getContentLength()).isEqualTo(-1);
} }
@Test @Test
public void writeWithMono() { void writeWithMono() {
Mono<DataBuffer> body = Mono.just(toDataBuffer("data1,data2")); Mono<DataBuffer> body = Mono.just(toDataBuffer("data1,data2"));
this.response.writeWith(body).block(); this.response.writeWith(body).block();
assertThat(this.response.getHeaders().getContentLength()).isEqualTo(11); assertThat(this.response.getHeaders().getContentLength()).isEqualTo(11);
} }
@Test // gh-23484 @Test // gh-23484
public void writeWithGivenContentLength() { void writeWithGivenContentLength() {
int length = 15; int length = 15;
this.response.getHeaders().setContentLength(length); this.response.getHeaders().setContentLength(length);
this.response.writeWith(Flux.empty()).block(); this.response.writeWith(Flux.empty()).block();
@ -74,7 +75,7 @@ public class HttpHeadResponseDecoratorTests {
} }
@Test // gh-25908 @Test // gh-25908
public void writeWithGivenTransferEncoding() { void writeWithGivenTransferEncoding() {
Flux<DataBuffer> body = Flux.just(toDataBuffer("data1"), toDataBuffer("data2")); Flux<DataBuffer> body = Flux.just(toDataBuffer("data1"), toDataBuffer("data2"));
this.response.getHeaders().add(HttpHeaders.TRANSFER_ENCODING, "chunked"); this.response.getHeaders().add(HttpHeaders.TRANSFER_ENCODING, "chunked");
this.response.writeWith(body).block(); this.response.writeWith(body).block();
@ -82,7 +83,7 @@ public class HttpHeadResponseDecoratorTests {
} }
private DataBuffer toDataBuffer(String s) { private DataBuffer toDataBuffer(String s) {
DataBuffer buffer = this.bufferFactory.allocateBuffer(); DataBuffer buffer = this.bufferFactory.allocateBuffer(256);
buffer.write(s.getBytes(StandardCharsets.UTF_8)); buffer.write(s.getBytes(StandardCharsets.UTF_8));
return buffer; return buffer;
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2020 the original author or authors. * Copyright 2002-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -56,7 +56,7 @@ import static org.assertj.core.api.Assertions.assertThat;
* @author Sebastien Deleuze * @author Sebastien Deleuze
* @author Brian Clozel * @author Brian Clozel
*/ */
public class ServerHttpResponseTests { class ServerHttpResponseTests {
@Test @Test
void writeWith() { void writeWith() {
@ -68,9 +68,9 @@ public class ServerHttpResponseTests {
assertThat(response.cookiesWritten).isTrue(); assertThat(response.cookiesWritten).isTrue();
assertThat(response.body.size()).isEqualTo(3); assertThat(response.body.size()).isEqualTo(3);
assertThat(new String(response.body.get(0).asByteBuffer().array(), StandardCharsets.UTF_8)).isEqualTo("a"); assertThat(new String(response.body.get(0).toByteBuffer().array(), StandardCharsets.UTF_8)).isEqualTo("a");
assertThat(new String(response.body.get(1).asByteBuffer().array(), StandardCharsets.UTF_8)).isEqualTo("b"); assertThat(new String(response.body.get(1).toByteBuffer().array(), StandardCharsets.UTF_8)).isEqualTo("b");
assertThat(new String(response.body.get(2).asByteBuffer().array(), StandardCharsets.UTF_8)).isEqualTo("c"); assertThat(new String(response.body.get(2).toByteBuffer().array(), StandardCharsets.UTF_8)).isEqualTo("c");
} }
@Test // SPR-14952 @Test // SPR-14952
@ -84,7 +84,7 @@ public class ServerHttpResponseTests {
assertThat(response.cookiesWritten).isTrue(); assertThat(response.cookiesWritten).isTrue();
assertThat(response.body.size()).isEqualTo(1); assertThat(response.body.size()).isEqualTo(1);
assertThat(new String(response.body.get(0).asByteBuffer().array(), StandardCharsets.UTF_8)).isEqualTo("foo"); assertThat(new String(response.body.get(0).toByteBuffer().array(), StandardCharsets.UTF_8)).isEqualTo("foo");
} }
@Test @Test
@ -139,9 +139,9 @@ public class ServerHttpResponseTests {
assertThat(response.getCookies().getFirst("ID")).isSameAs(cookie); assertThat(response.getCookies().getFirst("ID")).isSameAs(cookie);
assertThat(response.body.size()).isEqualTo(3); assertThat(response.body.size()).isEqualTo(3);
assertThat(new String(response.body.get(0).asByteBuffer().array(), StandardCharsets.UTF_8)).isEqualTo("a"); assertThat(new String(response.body.get(0).toByteBuffer().array(), StandardCharsets.UTF_8)).isEqualTo("a");
assertThat(new String(response.body.get(1).asByteBuffer().array(), StandardCharsets.UTF_8)).isEqualTo("b"); assertThat(new String(response.body.get(1).toByteBuffer().array(), StandardCharsets.UTF_8)).isEqualTo("b");
assertThat(new String(response.body.get(2).asByteBuffer().array(), StandardCharsets.UTF_8)).isEqualTo("c"); assertThat(new String(response.body.get(2).toByteBuffer().array(), StandardCharsets.UTF_8)).isEqualTo("c");
} }
@Test @Test

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2021 the original author or authors. * Copyright 2002-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -17,16 +17,19 @@
package org.springframework.web.reactive.resource; package org.springframework.web.reactive.resource;
import java.io.IOException; import java.io.IOException;
import java.nio.file.Paths;
import java.time.Duration; import java.time.Duration;
import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Stream;
import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import reactor.core.publisher.Flux; import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono; import reactor.core.publisher.Mono;
import reactor.test.StepVerifier; import reactor.test.StepVerifier;
@ -44,6 +47,7 @@ import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType; import org.springframework.http.MediaType;
import org.springframework.http.server.PathContainer; import org.springframework.http.server.PathContainer;
import org.springframework.util.ClassUtils;
import org.springframework.util.StringUtils; import org.springframework.util.StringUtils;
import org.springframework.web.reactive.HandlerMapping; import org.springframework.web.reactive.HandlerMapping;
import org.springframework.web.server.MethodNotAllowedException; import org.springframework.web.server.MethodNotAllowedException;
@ -67,8 +71,9 @@ import static org.mockito.Mockito.mock;
* Unit tests for {@link ResourceWebHandler}. * Unit tests for {@link ResourceWebHandler}.
* *
* @author Rossen Stoyanchev * @author Rossen Stoyanchev
* @author Sam Brannen
*/ */
public class ResourceWebHandlerTests { class ResourceWebHandlerTests {
private static final Duration TIMEOUT = Duration.ofSeconds(1); private static final Duration TIMEOUT = Duration.ofSeconds(1);
@ -76,11 +81,11 @@ public class ResourceWebHandlerTests {
@BeforeEach @BeforeEach
public void setup() throws Exception { void setup() throws Exception {
List<Resource> locations = new ArrayList<>(2); List<Resource> locations = List.of(
locations.add(new ClassPathResource("test/", getClass())); new ClassPathResource("test/", getClass()),
locations.add(new ClassPathResource("testalternatepath/", getClass())); new ClassPathResource("testalternatepath/", getClass()),
locations.add(new ClassPathResource("META-INF/resources/webjars/")); new ClassPathResource("META-INF/resources/webjars/"));
this.handler = new ResourceWebHandler(); this.handler = new ResourceWebHandler();
this.handler.setLocations(locations); this.handler.setLocations(locations);
@ -90,7 +95,7 @@ public class ResourceWebHandlerTests {
@Test @Test
public void getResource() throws Exception { void getResource() throws Exception {
MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("")); MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get(""));
setPathWithinHandlerMapping(exchange, "foo.css"); setPathWithinHandlerMapping(exchange, "foo.css");
this.handler.handle(exchange).block(TIMEOUT); this.handler.handle(exchange).block(TIMEOUT);
@ -107,7 +112,7 @@ public class ResourceWebHandlerTests {
} }
@Test @Test
public void getResourceHttpHeader() throws Exception { void getResourceHttpHeader() throws Exception {
MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.head("")); MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.head(""));
setPathWithinHandlerMapping(exchange, "foo.css"); setPathWithinHandlerMapping(exchange, "foo.css");
this.handler.handle(exchange).block(TIMEOUT); this.handler.handle(exchange).block(TIMEOUT);
@ -127,7 +132,7 @@ public class ResourceWebHandlerTests {
} }
@Test @Test
public void getResourceHttpOptions() { void getResourceHttpOptions() {
MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.options("")); MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.options(""));
setPathWithinHandlerMapping(exchange, "foo.css"); setPathWithinHandlerMapping(exchange, "foo.css");
this.handler.handle(exchange).block(TIMEOUT); this.handler.handle(exchange).block(TIMEOUT);
@ -137,7 +142,7 @@ public class ResourceWebHandlerTests {
} }
@Test @Test
public void getResourceNoCache() throws Exception { void getResourceNoCache() throws Exception {
MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("")); MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get(""));
setPathWithinHandlerMapping(exchange, "foo.css"); setPathWithinHandlerMapping(exchange, "foo.css");
this.handler.setCacheControl(CacheControl.noStore()); this.handler.setCacheControl(CacheControl.noStore());
@ -152,7 +157,7 @@ public class ResourceWebHandlerTests {
} }
@Test @Test
public void getVersionedResource() throws Exception { void getVersionedResource() throws Exception {
VersionResourceResolver versionResolver = new VersionResourceResolver(); VersionResourceResolver versionResolver = new VersionResourceResolver();
versionResolver.addFixedVersionStrategy("versionString", "/**"); versionResolver.addFixedVersionStrategy("versionString", "/**");
this.handler.setResourceResolvers(Arrays.asList(versionResolver, new PathResourceResolver())); this.handler.setResourceResolvers(Arrays.asList(versionResolver, new PathResourceResolver()));
@ -168,7 +173,7 @@ public class ResourceWebHandlerTests {
} }
@Test @Test
public void getResourceWithHtmlMediaType() throws Exception { void getResourceWithHtmlMediaType() throws Exception {
MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("")); MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get(""));
setPathWithinHandlerMapping(exchange, "foo.html"); setPathWithinHandlerMapping(exchange, "foo.html");
this.handler.handle(exchange).block(TIMEOUT); this.handler.handle(exchange).block(TIMEOUT);
@ -183,7 +188,7 @@ public class ResourceWebHandlerTests {
} }
@Test @Test
public void getResourceFromAlternatePath() throws Exception { void getResourceFromAlternatePath() throws Exception {
MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("")); MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get(""));
setPathWithinHandlerMapping(exchange, "baz.css"); setPathWithinHandlerMapping(exchange, "baz.css");
this.handler.handle(exchange).block(TIMEOUT); this.handler.handle(exchange).block(TIMEOUT);
@ -200,7 +205,7 @@ public class ResourceWebHandlerTests {
} }
@Test @Test
public void getResourceFromSubDirectory() { void getResourceFromSubDirectory() {
MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("")); MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get(""));
setPathWithinHandlerMapping(exchange, "js/foo.js"); setPathWithinHandlerMapping(exchange, "js/foo.js");
this.handler.handle(exchange).block(TIMEOUT); this.handler.handle(exchange).block(TIMEOUT);
@ -210,7 +215,7 @@ public class ResourceWebHandlerTests {
} }
@Test @Test
public void getResourceFromSubDirectoryOfAlternatePath() { void getResourceFromSubDirectoryOfAlternatePath() {
MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("")); MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get(""));
setPathWithinHandlerMapping(exchange, "js/baz.js"); setPathWithinHandlerMapping(exchange, "js/baz.js");
this.handler.handle(exchange).block(TIMEOUT); this.handler.handle(exchange).block(TIMEOUT);
@ -221,11 +226,11 @@ public class ResourceWebHandlerTests {
} }
@Test @Test
public void getResourceWithRegisteredMediaType() throws Exception { void getResourceWithRegisteredMediaType() throws Exception {
MediaType mediaType = new MediaType("foo", "bar"); MediaType mediaType = new MediaType("foo", "bar");
ResourceWebHandler handler = new ResourceWebHandler(); ResourceWebHandler handler = new ResourceWebHandler();
handler.setLocations(Collections.singletonList(new ClassPathResource("test/", getClass()))); handler.setLocations(List.of(new ClassPathResource("test/", getClass())));
handler.setMediaTypes(Collections.singletonMap("bar", mediaType)); handler.setMediaTypes(Collections.singletonMap("bar", mediaType));
handler.afterPropertiesSet(); handler.afterPropertiesSet();
@ -239,12 +244,12 @@ public class ResourceWebHandlerTests {
} }
@Test @Test
public void getResourceFromFileSystem() throws Exception { void getResourceFromFileSystem() throws Exception {
String path = new ClassPathResource("", getClass()).getFile().getCanonicalPath() String packagePath = ClassUtils.classPackageAsResourcePath(getClass());
.replace('\\', '/').replace("classes/java", "resources") + "/"; String path = Paths.get("src/test/resources", packagePath).normalize() + "/";
ResourceWebHandler handler = new ResourceWebHandler(); ResourceWebHandler handler = new ResourceWebHandler();
handler.setLocations(Collections.singletonList(new FileSystemResource(path))); handler.setLocations(List.of(new FileSystemResource(path)));
handler.afterPropertiesSet(); handler.afterPropertiesSet();
MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("")); MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get(""));
@ -258,7 +263,7 @@ public class ResourceWebHandlerTests {
} }
@Test // gh-27538, gh-27624 @Test // gh-27538, gh-27624
public void filterNonExistingLocations() throws Exception { void filterNonExistingLocations() throws Exception {
List<Resource> inputLocations = Arrays.asList( List<Resource> inputLocations = Arrays.asList(
new ClassPathResource("test/", getClass()), new ClassPathResource("test/", getClass()),
new ClassPathResource("testalternatepath/", getClass()), new ClassPathResource("testalternatepath/", getClass()),
@ -276,8 +281,8 @@ public class ResourceWebHandlerTests {
} }
@Test // SPR-14577 @Test // SPR-14577
public void getMediaTypeWithFavorPathExtensionOff() throws Exception { void getMediaTypeWithFavorPathExtensionOff() throws Exception {
List<Resource> paths = Collections.singletonList(new ClassPathResource("test/", getClass())); List<Resource> paths = List.of(new ClassPathResource("test/", getClass()));
ResourceWebHandler handler = new ResourceWebHandler(); ResourceWebHandler handler = new ResourceWebHandler();
handler.setLocations(paths); handler.setLocations(paths);
handler.afterPropertiesSet(); handler.afterPropertiesSet();
@ -291,7 +296,7 @@ public class ResourceWebHandlerTests {
} }
@Test @Test
public void testInvalidPath() throws Exception { void invalidPath() throws Exception {
// Use mock ResourceResolver: i.e. we're only testing upfront validations... // Use mock ResourceResolver: i.e. we're only testing upfront validations...
@ -302,8 +307,8 @@ public class ResourceWebHandlerTests {
given(resolver.resolveResource(any(), any(), any(), any())).willReturn(Mono.just(resource)); given(resolver.resolveResource(any(), any(), any(), any())).willReturn(Mono.just(resource));
ResourceWebHandler handler = new ResourceWebHandler(); ResourceWebHandler handler = new ResourceWebHandler();
handler.setLocations(Collections.singletonList(new ClassPathResource("test/", getClass()))); handler.setLocations(List.of(new ClassPathResource("test/", getClass())));
handler.setResourceResolvers(Collections.singletonList(resolver)); handler.setResourceResolvers(List.of(resolver));
handler.afterPropertiesSet(); handler.afterPropertiesSet();
testInvalidPath("../testsecret/secret.txt", handler); testInvalidPath("../testsecret/secret.txt", handler);
@ -311,7 +316,7 @@ public class ResourceWebHandlerTests {
testInvalidPath(":/../../testsecret/secret.txt", handler); testInvalidPath(":/../../testsecret/secret.txt", handler);
Resource location = new UrlResource(getClass().getResource("./test/")); Resource location = new UrlResource(getClass().getResource("./test/"));
this.handler.setLocations(Collections.singletonList(location)); handler.setLocations(List.of(location));
Resource secretResource = new UrlResource(getClass().getResource("testsecret/secret.txt")); Resource secretResource = new UrlResource(getClass().getResource("testsecret/secret.txt"));
String secretPath = secretResource.getURL().getPath(); String secretPath = secretResource.getURL().getPath();
@ -336,34 +341,29 @@ public class ResourceWebHandlerTests {
}).verify(TIMEOUT); }).verify(TIMEOUT);
} }
@Test @ParameterizedTest
public void testResolvePathWithTraversal() throws Exception { @MethodSource("httpMethods")
for (HttpMethod method : HttpMethod.values()) { void resolvePathWithTraversal(HttpMethod method) throws Exception {
testResolvePathWithTraversal(method);
}
}
private void testResolvePathWithTraversal(HttpMethod httpMethod) throws Exception {
Resource location = new ClassPathResource("test/", getClass()); Resource location = new ClassPathResource("test/", getClass());
this.handler.setLocations(Collections.singletonList(location)); this.handler.setLocations(List.of(location));
testResolvePathWithTraversal(httpMethod, "../testsecret/secret.txt", location); testResolvePathWithTraversal(method, "../testsecret/secret.txt", location);
testResolvePathWithTraversal(httpMethod, "test/../../testsecret/secret.txt", location); testResolvePathWithTraversal(method, "test/../../testsecret/secret.txt", location);
testResolvePathWithTraversal(httpMethod, ":/../../testsecret/secret.txt", location); testResolvePathWithTraversal(method, ":/../../testsecret/secret.txt", location);
location = new UrlResource(getClass().getResource("./test/")); location = new UrlResource(getClass().getResource("./test/"));
this.handler.setLocations(Collections.singletonList(location)); this.handler.setLocations(List.of(location));
Resource secretResource = new UrlResource(getClass().getResource("testsecret/secret.txt")); Resource secretResource = new UrlResource(getClass().getResource("testsecret/secret.txt"));
String secretPath = secretResource.getURL().getPath(); String secretPath = secretResource.getURL().getPath();
testResolvePathWithTraversal(httpMethod, "file:" + secretPath, location); testResolvePathWithTraversal(method, "file:" + secretPath, location);
testResolvePathWithTraversal(httpMethod, "/file:" + secretPath, location); testResolvePathWithTraversal(method, "/file:" + secretPath, location);
testResolvePathWithTraversal(httpMethod, "url:" + secretPath, location); testResolvePathWithTraversal(method, "url:" + secretPath, location);
testResolvePathWithTraversal(httpMethod, "/url:" + secretPath, location); testResolvePathWithTraversal(method, "/url:" + secretPath, location);
testResolvePathWithTraversal(httpMethod, "////../.." + secretPath, location); testResolvePathWithTraversal(method, "////../.." + secretPath, location);
testResolvePathWithTraversal(httpMethod, "/%2E%2E/testsecret/secret.txt", location); testResolvePathWithTraversal(method, "/%2E%2E/testsecret/secret.txt", location);
testResolvePathWithTraversal(httpMethod, "%2F%2F%2E%2E%2F%2Ftestsecret/secret.txt", location); testResolvePathWithTraversal(method, "%2F%2F%2E%2E%2F%2Ftestsecret/secret.txt", location);
testResolvePathWithTraversal(httpMethod, "url:" + secretPath, location); testResolvePathWithTraversal(method, "url:" + secretPath, location);
// The following tests fail with a MalformedURLException on Windows // The following tests fail with a MalformedURLException on Windows
// testResolvePathWithTraversal(location, "/" + secretPath); // testResolvePathWithTraversal(location, "/" + secretPath);
@ -387,7 +387,7 @@ public class ResourceWebHandlerTests {
} }
@Test @Test
public void processPath() { void processPath() {
assertThat(this.handler.processPath("/foo/bar")).isSameAs("/foo/bar"); assertThat(this.handler.processPath("/foo/bar")).isSameAs("/foo/bar");
assertThat(this.handler.processPath("foo/bar")).isSameAs("foo/bar"); assertThat(this.handler.processPath("foo/bar")).isSameAs("foo/bar");
@ -416,7 +416,7 @@ public class ResourceWebHandlerTests {
} }
@Test @Test
public void initAllowedLocations() { void initAllowedLocations() {
PathResourceResolver resolver = (PathResourceResolver) this.handler.getResourceResolvers().get(0); PathResourceResolver resolver = (PathResourceResolver) this.handler.getResourceResolvers().get(0);
Resource[] locations = resolver.getAllowedLocations(); Resource[] locations = resolver.getAllowedLocations();
@ -427,7 +427,7 @@ public class ResourceWebHandlerTests {
} }
@Test @Test
public void initAllowedLocationsWithExplicitConfiguration() throws Exception { void initAllowedLocationsWithExplicitConfiguration() throws Exception {
ClassPathResource location1 = new ClassPathResource("test/", getClass()); ClassPathResource location1 = new ClassPathResource("test/", getClass());
ClassPathResource location2 = new ClassPathResource("testalternatepath/", getClass()); ClassPathResource location2 = new ClassPathResource("testalternatepath/", getClass());
@ -435,7 +435,7 @@ public class ResourceWebHandlerTests {
pathResolver.setAllowedLocations(location1); pathResolver.setAllowedLocations(location1);
ResourceWebHandler handler = new ResourceWebHandler(); ResourceWebHandler handler = new ResourceWebHandler();
handler.setResourceResolvers(Collections.singletonList(pathResolver)); handler.setResourceResolvers(List.of(pathResolver));
handler.setLocations(Arrays.asList(location1, location2)); handler.setLocations(Arrays.asList(location1, location2));
handler.afterPropertiesSet(); handler.afterPropertiesSet();
@ -445,7 +445,7 @@ public class ResourceWebHandlerTests {
} }
@Test @Test
public void notModified() throws Exception { void notModified() throws Exception {
MockServerWebExchange exchange = MockServerWebExchange.from( MockServerWebExchange exchange = MockServerWebExchange.from(
MockServerHttpRequest.get("").ifModifiedSince(resourceLastModified("test/foo.css"))); MockServerHttpRequest.get("").ifModifiedSince(resourceLastModified("test/foo.css")));
@ -455,7 +455,7 @@ public class ResourceWebHandlerTests {
} }
@Test @Test
public void modified() throws Exception { void modified() throws Exception {
long timestamp = resourceLastModified("test/foo.css") / 1000 * 1000 - 1; long timestamp = resourceLastModified("test/foo.css") / 1000 * 1000 - 1;
MockServerHttpRequest request = MockServerHttpRequest.get("").ifModifiedSince(timestamp).build(); MockServerHttpRequest request = MockServerHttpRequest.get("").ifModifiedSince(timestamp).build();
MockServerWebExchange exchange = MockServerWebExchange.from(request); MockServerWebExchange exchange = MockServerWebExchange.from(request);
@ -467,7 +467,7 @@ public class ResourceWebHandlerTests {
} }
@Test @Test
public void directory() { void directory() {
MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("")); MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get(""));
setPathWithinHandlerMapping(exchange, "js/"); setPathWithinHandlerMapping(exchange, "js/");
StepVerifier.create(this.handler.handle(exchange)) StepVerifier.create(this.handler.handle(exchange))
@ -478,7 +478,7 @@ public class ResourceWebHandlerTests {
} }
@Test @Test
public void directoryInJarFile() { void directoryInJarFile() {
MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("")); MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get(""));
setPathWithinHandlerMapping(exchange, "underscorejs/"); setPathWithinHandlerMapping(exchange, "underscorejs/");
StepVerifier.create(this.handler.handle(exchange)) StepVerifier.create(this.handler.handle(exchange))
@ -489,7 +489,7 @@ public class ResourceWebHandlerTests {
} }
@Test @Test
public void missingResourcePath() { void missingResourcePath() {
MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("")); MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get(""));
setPathWithinHandlerMapping(exchange, ""); setPathWithinHandlerMapping(exchange, "");
StepVerifier.create(this.handler.handle(exchange)) StepVerifier.create(this.handler.handle(exchange))
@ -500,29 +500,24 @@ public class ResourceWebHandlerTests {
} }
@Test @Test
public void noPathWithinHandlerMappingAttribute() { void noPathWithinHandlerMappingAttribute() {
MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("")); MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get(""));
assertThatIllegalArgumentException().isThrownBy(() -> assertThatIllegalArgumentException().isThrownBy(() ->
this.handler.handle(exchange).block(TIMEOUT)); this.handler.handle(exchange).block(TIMEOUT));
} }
@Test @Test
public void unsupportedHttpMethod() { void unsupportedHttpMethod() {
MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.post("")); MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.post(""));
setPathWithinHandlerMapping(exchange, "foo.css"); setPathWithinHandlerMapping(exchange, "foo.css");
assertThatExceptionOfType(MethodNotAllowedException.class).isThrownBy(() -> assertThatExceptionOfType(MethodNotAllowedException.class).isThrownBy(() ->
this.handler.handle(exchange).block(TIMEOUT)); this.handler.handle(exchange).block(TIMEOUT));
} }
@Test @ParameterizedTest
public void resourceNotFound() throws Exception { @MethodSource("httpMethods")
for (HttpMethod method : HttpMethod.values()) { void resourceNotFound(HttpMethod method) throws Exception {
resourceNotFound(method); MockServerHttpRequest request = MockServerHttpRequest.method(method, "").build();
}
}
private void resourceNotFound(HttpMethod httpMethod) {
MockServerHttpRequest request = MockServerHttpRequest.method(httpMethod, "").build();
MockServerWebExchange exchange = MockServerWebExchange.from(request); MockServerWebExchange exchange = MockServerWebExchange.from(request);
setPathWithinHandlerMapping(exchange, "not-there.css"); setPathWithinHandlerMapping(exchange, "not-there.css");
Mono<Void> mono = this.handler.handle(exchange); Mono<Void> mono = this.handler.handle(exchange);
@ -540,7 +535,7 @@ public class ResourceWebHandlerTests {
} }
@Test @Test
public void partialContentByteRange() { void partialContentByteRange() {
MockServerHttpRequest request = MockServerHttpRequest.get("").header("Range", "bytes=0-1").build(); MockServerHttpRequest request = MockServerHttpRequest.get("").header("Range", "bytes=0-1").build();
MockServerWebExchange exchange = MockServerWebExchange.from(request); MockServerWebExchange exchange = MockServerWebExchange.from(request);
setPathWithinHandlerMapping(exchange, "foo.txt"); setPathWithinHandlerMapping(exchange, "foo.txt");
@ -556,7 +551,7 @@ public class ResourceWebHandlerTests {
} }
@Test @Test
public void partialContentByteRangeNoEnd() { void partialContentByteRangeNoEnd() {
MockServerHttpRequest request = MockServerHttpRequest.get("").header("range", "bytes=9-").build(); MockServerHttpRequest request = MockServerHttpRequest.get("").header("range", "bytes=9-").build();
MockServerWebExchange exchange = MockServerWebExchange.from(request); MockServerWebExchange exchange = MockServerWebExchange.from(request);
setPathWithinHandlerMapping(exchange, "foo.txt"); setPathWithinHandlerMapping(exchange, "foo.txt");
@ -572,7 +567,7 @@ public class ResourceWebHandlerTests {
} }
@Test @Test
public void partialContentByteRangeLargeEnd() { void partialContentByteRangeLargeEnd() {
MockServerHttpRequest request = MockServerHttpRequest.get("").header("range", "bytes=9-10000").build(); MockServerHttpRequest request = MockServerHttpRequest.get("").header("range", "bytes=9-10000").build();
MockServerWebExchange exchange = MockServerWebExchange.from(request); MockServerWebExchange exchange = MockServerWebExchange.from(request);
setPathWithinHandlerMapping(exchange, "foo.txt"); setPathWithinHandlerMapping(exchange, "foo.txt");
@ -588,7 +583,7 @@ public class ResourceWebHandlerTests {
} }
@Test @Test
public void partialContentSuffixRange() { void partialContentSuffixRange() {
MockServerHttpRequest request = MockServerHttpRequest.get("").header("range", "bytes=-1").build(); MockServerHttpRequest request = MockServerHttpRequest.get("").header("range", "bytes=-1").build();
MockServerWebExchange exchange = MockServerWebExchange.from(request); MockServerWebExchange exchange = MockServerWebExchange.from(request);
setPathWithinHandlerMapping(exchange, "foo.txt"); setPathWithinHandlerMapping(exchange, "foo.txt");
@ -604,7 +599,7 @@ public class ResourceWebHandlerTests {
} }
@Test @Test
public void partialContentSuffixRangeLargeSuffix() { void partialContentSuffixRangeLargeSuffix() {
MockServerHttpRequest request = MockServerHttpRequest.get("").header("range", "bytes=-11").build(); MockServerHttpRequest request = MockServerHttpRequest.get("").header("range", "bytes=-11").build();
MockServerWebExchange exchange = MockServerWebExchange.from(request); MockServerWebExchange exchange = MockServerWebExchange.from(request);
setPathWithinHandlerMapping(exchange, "foo.txt"); setPathWithinHandlerMapping(exchange, "foo.txt");
@ -620,7 +615,7 @@ public class ResourceWebHandlerTests {
} }
@Test @Test
public void partialContentInvalidRangeHeader() { void partialContentInvalidRangeHeader() {
MockServerHttpRequest request = MockServerHttpRequest.get("").header("range", "bytes=foo bar").build(); MockServerHttpRequest request = MockServerHttpRequest.get("").header("range", "bytes=foo bar").build();
MockServerWebExchange exchange = MockServerWebExchange.from(request); MockServerWebExchange exchange = MockServerWebExchange.from(request);
setPathWithinHandlerMapping(exchange, "foo.txt"); setPathWithinHandlerMapping(exchange, "foo.txt");
@ -635,7 +630,7 @@ public class ResourceWebHandlerTests {
} }
@Test @Test
public void partialContentMultipleByteRanges() { void partialContentMultipleByteRanges() {
MockServerHttpRequest request = MockServerHttpRequest.get("").header("Range", "bytes=0-1, 4-5, 8-9").build(); MockServerHttpRequest request = MockServerHttpRequest.get("").header("Range", "bytes=0-1, 4-5, 8-9").build();
MockServerWebExchange exchange = MockServerWebExchange.from(request); MockServerWebExchange exchange = MockServerWebExchange.from(request);
setPathWithinHandlerMapping(exchange, "foo.txt"); setPathWithinHandlerMapping(exchange, "foo.txt");
@ -648,7 +643,7 @@ public class ResourceWebHandlerTests {
String boundary = "--" + exchange.getResponse().getHeaders().getContentType().toString().substring(30); String boundary = "--" + exchange.getResponse().getHeaders().getContentType().toString().substring(30);
Mono<DataBuffer> reduced = Flux.from(exchange.getResponse().getBody()) Mono<DataBuffer> reduced = Flux.from(exchange.getResponse().getBody())
.reduce(DefaultDataBufferFactory.sharedInstance.allocateBuffer(), (previous, current) -> { .reduce(DefaultDataBufferFactory.sharedInstance.allocateBuffer(256), (previous, current) -> {
previous.write(current); previous.write(current);
DataBufferUtils.release(current); DataBufferUtils.release(current);
return previous; return previous;
@ -679,7 +674,7 @@ public class ResourceWebHandlerTests {
} }
@Test // SPR-14005 @Test // SPR-14005
public void doOverwriteExistingCacheControlHeaders() { void doOverwriteExistingCacheControlHeaders() {
MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("")); MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get(""));
exchange.getResponse().getHeaders().setCacheControl(CacheControl.noStore().getHeaderValue()); exchange.getResponse().getHeaders().setCacheControl(CacheControl.noStore().getHeaderValue());
setPathWithinHandlerMapping(exchange, "foo.css"); setPathWithinHandlerMapping(exchange, "foo.css");
@ -723,4 +718,9 @@ public class ResourceWebHandlerTests {
.verify(); .verify();
} }
static Stream<HttpMethod> httpMethods() {
return Arrays.stream(HttpMethod.values());
}
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2020 the original author or authors. * Copyright 2002-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -67,7 +67,7 @@ class SimpleUrlHandlerMappingIntegrationTests extends AbstractHttpHandlerIntegra
@ParameterizedHttpServerTest @ParameterizedHttpServerTest
void testRequestToFooHandler(HttpServer httpServer) throws Exception { void requestToFooHandler(HttpServer httpServer) throws Exception {
startServer(httpServer); startServer(httpServer);
URI url = new URI("http://localhost:" + this.port + "/foo"); URI url = new URI("http://localhost:" + this.port + "/foo");
@ -79,7 +79,7 @@ class SimpleUrlHandlerMappingIntegrationTests extends AbstractHttpHandlerIntegra
} }
@ParameterizedHttpServerTest @ParameterizedHttpServerTest
public void testRequestToBarHandler(HttpServer httpServer) throws Exception { public void requestToBarHandler(HttpServer httpServer) throws Exception {
startServer(httpServer); startServer(httpServer);
URI url = new URI("http://localhost:" + this.port + "/bar"); URI url = new URI("http://localhost:" + this.port + "/bar");
@ -91,7 +91,7 @@ class SimpleUrlHandlerMappingIntegrationTests extends AbstractHttpHandlerIntegra
} }
@ParameterizedHttpServerTest @ParameterizedHttpServerTest
void testRequestToHeaderSettingHandler(HttpServer httpServer) throws Exception { void requestToHeaderSettingHandler(HttpServer httpServer) throws Exception {
startServer(httpServer); startServer(httpServer);
URI url = new URI("http://localhost:" + this.port + "/header"); URI url = new URI("http://localhost:" + this.port + "/header");
@ -103,7 +103,7 @@ class SimpleUrlHandlerMappingIntegrationTests extends AbstractHttpHandlerIntegra
} }
@ParameterizedHttpServerTest @ParameterizedHttpServerTest
void testHandlerNotFound(HttpServer httpServer) throws Exception { void handlerNotFound(HttpServer httpServer) throws Exception {
startServer(httpServer); startServer(httpServer);
URI url = new URI("http://localhost:" + this.port + "/oops"); URI url = new URI("http://localhost:" + this.port + "/oops");
@ -117,7 +117,7 @@ class SimpleUrlHandlerMappingIntegrationTests extends AbstractHttpHandlerIntegra
} }
private static DataBuffer asDataBuffer(String text) { private static DataBuffer asDataBuffer(String text) {
DefaultDataBuffer buffer = DefaultDataBufferFactory.sharedInstance.allocateBuffer(); DefaultDataBuffer buffer = DefaultDataBufferFactory.sharedInstance.allocateBuffer(256);
return buffer.write(text.getBytes(StandardCharsets.UTF_8)); return buffer.write(text.getBytes(StandardCharsets.UTF_8));
} }

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2020 the original author or authors. * Copyright 2002-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -487,7 +487,7 @@ public class RequestMappingMessageConversionIntegrationTests extends AbstractReq
public Publisher<ByteBuffer> getPublisher() { public Publisher<ByteBuffer> getPublisher() {
Jackson2JsonEncoder encoder = new Jackson2JsonEncoder(); Jackson2JsonEncoder encoder = new Jackson2JsonEncoder();
return encoder.encode(Mono.just(new Person("Robert")), DefaultDataBufferFactory.sharedInstance, return encoder.encode(Mono.just(new Person("Robert")), DefaultDataBufferFactory.sharedInstance,
ResolvableType.forClass(Person.class), JSON, Collections.emptyMap()).map(DataBuffer::asByteBuffer); ResolvableType.forClass(Person.class), JSON, Collections.emptyMap()).map(DataBuffer::toByteBuffer);
} }
@GetMapping("/flux") @GetMapping("/flux")

View File

@ -1,5 +1,5 @@
/* /*
* Copyright 2002-2019 the original author or authors. * Copyright 2002-2022 the original author or authors.
* *
* Licensed under the Apache License, Version 2.0 (the "License"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -79,16 +79,16 @@ public class FreeMarkerViewTests {
FreeMarkerView view = new FreeMarkerView(); FreeMarkerView view = new FreeMarkerView();
view.setApplicationContext(this.context); view.setApplicationContext(this.context);
view.setUrl("anythingButNull"); view.setUrl("anythingButNull");
assertThatExceptionOfType(ApplicationContextException.class).isThrownBy( assertThatExceptionOfType(ApplicationContextException.class)
view::afterPropertiesSet) .isThrownBy(view::afterPropertiesSet)
.withMessageContaining("Must define a single FreeMarkerConfig bean"); .withMessageContaining("Must define a single FreeMarkerConfig bean");
} }
@Test @Test
public void noTemplateName() throws Exception { public void noTemplateName() throws Exception {
FreeMarkerView freeMarkerView = new FreeMarkerView(); FreeMarkerView freeMarkerView = new FreeMarkerView();
assertThatIllegalArgumentException().isThrownBy( assertThatIllegalArgumentException()
freeMarkerView::afterPropertiesSet) .isThrownBy(freeMarkerView::afterPropertiesSet)
.withMessageContaining("Property 'url' is required"); .withMessageContaining("Property 'url' is required");
} }
@ -141,7 +141,7 @@ public class FreeMarkerViewTests {
private static String asString(DataBuffer dataBuffer) { private static String asString(DataBuffer dataBuffer) {
ByteBuffer byteBuffer = dataBuffer.asByteBuffer(); ByteBuffer byteBuffer = dataBuffer.toByteBuffer();
final byte[] bytes = new byte[byteBuffer.remaining()]; final byte[] bytes = new byte[byteBuffer.remaining()];
byteBuffer.get(bytes); byteBuffer.get(bytes);
return new String(bytes, StandardCharsets.UTF_8); return new String(bytes, StandardCharsets.UTF_8);