DataBufferUtils.java 10.6 KB
Newer Older
A
Arjen Poutsma 已提交
1
/*
2
 * Copyright 2002-2017 the original author or authors.
A
Arjen Poutsma 已提交
3 4 5 6 7 8 9 10 11 12 13 14 15 16
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

17
package org.springframework.core.io.buffer;
A
Arjen Poutsma 已提交
18

A
Arjen Poutsma 已提交
19
import java.io.IOException;
A
Arjen Poutsma 已提交
20
import java.io.InputStream;
A
Arjen Poutsma 已提交
21
import java.nio.ByteBuffer;
22 23
import java.nio.channels.AsynchronousFileChannel;
import java.nio.channels.Channel;
A
Arjen Poutsma 已提交
24
import java.nio.channels.Channels;
25
import java.nio.channels.CompletionHandler;
A
Arjen Poutsma 已提交
26 27
import java.nio.channels.ReadableByteChannel;
import java.util.concurrent.atomic.AtomicLong;
28
import java.util.function.BiFunction;
A
Arjen Poutsma 已提交
29 30 31

import org.reactivestreams.Publisher;
import reactor.core.publisher.Flux;
32
import reactor.core.publisher.FluxSink;
33
import reactor.core.publisher.SynchronousSink;
A
Arjen Poutsma 已提交
34 35 36

import org.springframework.util.Assert;

B
Brian Clozel 已提交
37
/**
38 39
 * Utility class for working with {@link DataBuffer}s.
 *
A
Arjen Poutsma 已提交
40
 * @author Arjen Poutsma
B
Brian Clozel 已提交
41
 * @author Brian Clozel
42
 * @since 5.0
A
Arjen Poutsma 已提交
43 44 45
 */
public abstract class DataBufferUtils {

A
Arjen Poutsma 已提交
46
	/**
47
	 * Read the given {@code InputStream} into a {@code Flux} of
A
Arjen Poutsma 已提交
48
	 * {@code DataBuffer}s. Closes the input stream when the flux is terminated.
A
Arjen Poutsma 已提交
49
	 * @param inputStream the input stream to read from
50
	 * @param dataBufferFactory the factory to create data buffers with
A
Arjen Poutsma 已提交
51 52 53
	 * @param bufferSize the maximum size of the data buffers
	 * @return a flux of data buffers read from the given channel
	 */
A
Arjen Poutsma 已提交
54
	public static Flux<DataBuffer> read(InputStream inputStream,
55
			DataBufferFactory dataBufferFactory, int bufferSize) {
56 57 58

		Assert.notNull(inputStream, "InputStream must not be null");
		Assert.notNull(dataBufferFactory, "DataBufferFactory must not be null");
A
Arjen Poutsma 已提交
59

A
Arjen Poutsma 已提交
60
		ReadableByteChannel channel = Channels.newChannel(inputStream);
61
		return read(channel, dataBufferFactory, bufferSize);
A
Arjen Poutsma 已提交
62 63 64
	}

	/**
65
	 * Read the given {@code ReadableByteChannel} into a {@code Flux} of
A
Arjen Poutsma 已提交
66 67
	 * {@code DataBuffer}s. Closes the channel when the flux is terminated.
	 * @param channel the channel to read from
68
	 * @param dataBufferFactory the factory to create data buffers with
A
Arjen Poutsma 已提交
69 70 71
	 * @param bufferSize the maximum size of the data buffers
	 * @return a flux of data buffers read from the given channel
	 */
A
Arjen Poutsma 已提交
72
	public static Flux<DataBuffer> read(ReadableByteChannel channel,
73
			DataBufferFactory dataBufferFactory, int bufferSize) {
74 75 76

		Assert.notNull(channel, "ReadableByteChannel must not be null");
		Assert.notNull(dataBufferFactory, "DataBufferFactory must not be null");
A
Arjen Poutsma 已提交
77

78
		return Flux.generate(() -> channel,
79
				new ReadableByteChannelGenerator(dataBufferFactory, bufferSize),
80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
				DataBufferUtils::closeChannel);
	}

	/**
	 * Read the given {@code AsynchronousFileChannel} into a {@code Flux} of
	 * {@code DataBuffer}s. Closes the channel when the flux is terminated.
	 * @param channel the channel to read from
	 * @param dataBufferFactory the factory to create data buffers with
	 * @param bufferSize the maximum size of the data buffers
	 * @return a flux of data buffers read from the given channel
	 */
	public static Flux<DataBuffer> read(AsynchronousFileChannel channel,
			DataBufferFactory dataBufferFactory, int bufferSize) {
		return read(channel, 0, dataBufferFactory, bufferSize);
	}

	/**
	 * Read the given {@code AsynchronousFileChannel} into a {@code Flux} of
	 * {@code DataBuffer}s, starting at the given position. Closes the channel when the flux is
	 * terminated.
	 * @param channel the channel to read from
	 * @param position the position to start reading from
	 * @param dataBufferFactory the factory to create data buffers with
	 * @param bufferSize the maximum size of the data buffers
	 * @return a flux of data buffers read from the given channel
	 */
106
	@SuppressWarnings("deprecation")
107 108 109 110 111 112 113 114 115 116
	public static Flux<DataBuffer> read(AsynchronousFileChannel channel,
			long position, DataBufferFactory dataBufferFactory, int bufferSize) {

		Assert.notNull(channel, "'channel' must not be null");
		Assert.notNull(dataBufferFactory, "'dataBufferFactory' must not be null");
		Assert.isTrue(position >= 0, "'position' must be >= 0");

		ByteBuffer byteBuffer = ByteBuffer.allocate(bufferSize);

		return Flux.create(emitter -> {
S
Sebastien Deleuze 已提交
117
			emitter.onDispose(() -> closeChannel(channel));
118 119 120 121 122 123 124 125 126 127 128 129 130 131 132
			AsynchronousFileChannelCompletionHandler completionHandler =
					new AsynchronousFileChannelCompletionHandler(emitter, position,
							dataBufferFactory, byteBuffer);
			channel.read(byteBuffer, position, channel, completionHandler);
		});
	}

	private static void closeChannel(Channel channel) {
		try {
			if (channel != null) {
				channel.close();
			}
		}
		catch (IOException ignored) {
		}
A
Arjen Poutsma 已提交
133 134 135
	}

	/**
136 137 138
	 * Relay buffers from the given {@link Publisher} until the total
	 * {@linkplain DataBuffer#readableByteCount() byte count} reaches
	 * the given maximum byte count, or until the publisher is complete.
A
Arjen Poutsma 已提交
139 140 141 142
	 * @param publisher the publisher to filter
	 * @param maxByteCount the maximum byte count
	 * @return a flux whose maximum byte count is {@code maxByteCount}
	 */
143 144
	public static Flux<DataBuffer> takeUntilByteCount(Publisher<DataBuffer> publisher, long maxByteCount) {
		Assert.notNull(publisher, "Publisher must not be null");
A
Arjen Poutsma 已提交
145
		Assert.isTrue(maxByteCount >= 0, "'maxByteCount' must be a positive number");
146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166
		AtomicLong byteCountDown = new AtomicLong(maxByteCount);

		return Flux.from(publisher).
				takeWhile(dataBuffer -> {
					int delta = -dataBuffer.readableByteCount();
					long currentCount = byteCountDown.getAndAdd(delta);
					return currentCount >= 0;
				}).
				map(dataBuffer -> {
					long currentCount = byteCountDown.get();
					if (currentCount >= 0) {
						return dataBuffer;
					}
					else {
						// last buffer
						int size = (int) (currentCount + dataBuffer.readableByteCount());
						return dataBuffer.slice(0, size);
					}
				});
	}

B
Brian Clozel 已提交
167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202
	/**
	 * Skip buffers from the given {@link Publisher} until the total
	 * {@linkplain DataBuffer#readableByteCount() byte count} reaches
	 * the given maximum byte count, or until the publisher is complete.
	 * @param publisher the publisher to filter
	 * @param maxByteCount the maximum byte count
	 * @return a flux with the remaining part of the given publisher
	 */
	public static Flux<DataBuffer> skipUntilByteCount(Publisher<DataBuffer> publisher, long maxByteCount) {
		Assert.notNull(publisher, "Publisher must not be null");
		Assert.isTrue(maxByteCount >= 0, "'maxByteCount' must be a positive number");
		AtomicLong byteCountDown = new AtomicLong(maxByteCount);

		return Flux.from(publisher).
				skipUntil(dataBuffer -> {
					int delta = -dataBuffer.readableByteCount();
					long currentCount = byteCountDown.addAndGet(delta);
					if(currentCount < 0) {
						return true;
					} else {
						DataBufferUtils.release(dataBuffer);
						return false;
					}
				}).
				map(dataBuffer -> {
					long currentCount = byteCountDown.get();
					// slice first buffer, then let others flow through
					if (currentCount < 0) {
						int skip = (int) (currentCount + dataBuffer.readableByteCount());
						byteCountDown.set(0);
						return dataBuffer.slice(skip, dataBuffer.readableByteCount() - skip);
					}
					return dataBuffer;
				});
	}

203
	/**
204
	 * Retain the given data buffer, it it is a {@link PooledDataBuffer}.
205 206 207 208 209 210 211 212 213 214 215
	 * @param dataBuffer the data buffer to retain
	 * @return the retained buffer
	 */
	@SuppressWarnings("unchecked")
	public static <T extends DataBuffer> T retain(T dataBuffer) {
		if (dataBuffer instanceof PooledDataBuffer) {
			return (T) ((PooledDataBuffer) dataBuffer).retain();
		}
		else {
			return dataBuffer;
		}
A
Arjen Poutsma 已提交
216 217
	}

A
Arjen Poutsma 已提交
218
	/**
219
	 * Release the given data buffer, if it is a {@link PooledDataBuffer}.
A
Arjen Poutsma 已提交
220 221 222 223 224 225 226 227 228 229
	 * @param dataBuffer the data buffer to release
	 * @return {@code true} if the buffer was released; {@code false} otherwise.
	 */
	public static boolean release(DataBuffer dataBuffer) {
		if (dataBuffer instanceof PooledDataBuffer) {
			return ((PooledDataBuffer) dataBuffer).release();
		}
		return false;
	}

230

231
	private static class ReadableByteChannelGenerator
232
			implements BiFunction<ReadableByteChannel, SynchronousSink<DataBuffer>, ReadableByteChannel> {
A
Arjen Poutsma 已提交
233

234
		private final DataBufferFactory dataBufferFactory;
A
Arjen Poutsma 已提交
235

236
		private final ByteBuffer byteBuffer;
A
Arjen Poutsma 已提交
237

238
		public ReadableByteChannelGenerator(DataBufferFactory dataBufferFactory, int chunkSize) {
239
			this.dataBufferFactory = dataBufferFactory;
240
			this.byteBuffer = ByteBuffer.allocate(chunkSize);
A
Arjen Poutsma 已提交
241 242 243
		}

		@Override
244
		public ReadableByteChannel apply(ReadableByteChannel channel, SynchronousSink<DataBuffer> sub) {
A
Arjen Poutsma 已提交
245 246
			try {
				int read;
247 248
				if ((read = channel.read(this.byteBuffer)) >= 0) {
					this.byteBuffer.flip();
A
Arjen Poutsma 已提交
249
					boolean release = true;
250
					DataBuffer dataBuffer = this.dataBufferFactory.allocateBuffer(read);
A
Arjen Poutsma 已提交
251
					try {
252
						dataBuffer.write(this.byteBuffer);
A
Arjen Poutsma 已提交
253
						release = false;
S
Stephane Maldini 已提交
254
						sub.next(dataBuffer);
A
Arjen Poutsma 已提交
255 256 257
					}
					finally {
						if (release) {
A
Arjen Poutsma 已提交
258
							release(dataBuffer);
A
Arjen Poutsma 已提交
259 260
						}
					}
261
					this.byteBuffer.clear();
A
Arjen Poutsma 已提交
262 263
				}
				else {
S
Stephane Maldini 已提交
264
					sub.complete();
A
Arjen Poutsma 已提交
265 266 267
				}
			}
			catch (IOException ex) {
268
				sub.error(ex);
A
Arjen Poutsma 已提交
269
			}
270
			return channel;
A
Arjen Poutsma 已提交
271 272 273
		}
	}

274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327
	private static class AsynchronousFileChannelCompletionHandler
			implements CompletionHandler<Integer, AsynchronousFileChannel> {

		private final FluxSink<DataBuffer> emitter;

		private final ByteBuffer byteBuffer;

		private final DataBufferFactory dataBufferFactory;

		private long position;

		private AsynchronousFileChannelCompletionHandler(FluxSink<DataBuffer> emitter,
				long position, DataBufferFactory dataBufferFactory, ByteBuffer byteBuffer) {
			this.emitter = emitter;
			this.position = position;
			this.dataBufferFactory = dataBufferFactory;
			this.byteBuffer = byteBuffer;
		}

		@Override
		public void completed(Integer read, AsynchronousFileChannel channel) {
			if (read != -1) {
				this.position += read;
				this.byteBuffer.flip();
				boolean release = true;
				DataBuffer dataBuffer = this.dataBufferFactory.allocateBuffer(read);
				try {
					dataBuffer.write(this.byteBuffer);
					release = false;
					this.emitter.next(dataBuffer);
				}
				finally {
					if (release) {
						release(dataBuffer);
					}
				}
				this.byteBuffer.clear();

				if (!this.emitter.isCancelled()) {
					channel.read(this.byteBuffer, this.position, channel, this);
				}
			}
			else {
				this.emitter.complete();
				closeChannel(channel);
			}
		}

		@Override
		public void failed(Throwable exc, AsynchronousFileChannel channel) {
			this.emitter.error(exc);
			closeChannel(channel);
		}
	}
A
Arjen Poutsma 已提交
328
}