HttpRange.java 10.4 KB
Newer Older
1
/*
2
 * Copyright 2002-2017 the original author or authors.
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
 *
 * 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.
 */

package org.springframework.http;

19
import java.io.IOException;
20 21 22 23 24 25
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

26 27
import org.springframework.core.io.InputStreamResource;
import org.springframework.core.io.Resource;
28
import org.springframework.core.io.support.ResourceRegion;
29
import org.springframework.lang.Nullable;
30
import org.springframework.util.Assert;
J
Juergen Hoeller 已提交
31
import org.springframework.util.CollectionUtils;
32 33 34 35
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

/**
36
 * Represents an HTTP (byte) range for use with the HTTP {@code "Range"} header.
37 38
 *
 * @author Arjen Poutsma
J
Juergen Hoeller 已提交
39 40
 * @author Juergen Hoeller
 * @since 4.2
41 42 43 44 45 46 47 48 49
 * @see <a href="http://tools.ietf.org/html/rfc7233">HTTP/1.1: Range Requests</a>
 * @see HttpHeaders#setRange(List)
 * @see HttpHeaders#getRange()
 */
public abstract class HttpRange {

	private static final String BYTE_RANGE_PREFIX = "bytes=";


50 51 52 53 54
	/**
	 * Turn a {@code Resource} into a {@link ResourceRegion} using the range
	 * information contained in the current {@code HttpRange}.
	 * @param resource the {@code Resource} to select the region from
	 * @return the selected region of the given {@code Resource}
55
	 * @since 4.3
56 57 58 59
	 */
	public ResourceRegion toResourceRegion(Resource resource) {
		// Don't try to determine contentLength on InputStreamResource - cannot be read afterwards...
		// Note: custom InputStreamResource subclasses could provide a pre-calculated content length!
J
Juergen Hoeller 已提交
60 61
		Assert.isTrue(resource.getClass() != InputStreamResource.class,
				"Cannot convert an InputStreamResource to a ResourceRegion");
62 63 64 65 66 67 68
		try {
			long contentLength = resource.contentLength();
			Assert.isTrue(contentLength > 0, "Resource content length should be > 0");
			long start = getRangeStart(contentLength);
			long end = getRangeEnd(contentLength);
			return new ResourceRegion(resource, start, end - start + 1);
		}
J
Juergen Hoeller 已提交
69 70
		catch (IOException ex) {
			throw new IllegalArgumentException("Failed to convert Resource to ResourceRegion", ex);
71 72 73
		}
	}

J
Juergen Hoeller 已提交
74 75 76 77 78 79 80 81 82 83 84 85 86 87
	/**
	 * Return the start of the range given the total length of a representation.
	 * @param length the length of the representation
	 * @return the start of this range for the representation
	 */
	public abstract long getRangeStart(long length);

	/**
	 * Return the end of the range (inclusive) given the total length of a representation.
	 * @param length the length of the representation
	 * @return the end of the range for the representation
	 */
	public abstract long getRangeEnd(long length);

88 89 90

	/**
	 * Create an {@code HttpRange} from the given position to the end.
91
	 * @param firstBytePos the first byte position
92
	 * @return a byte range that ranges from {@code firstPos} till the end
93 94 95 96 97 98 99
	 * @see <a href="http://tools.ietf.org/html/rfc7233#section-2.1">Byte Ranges</a>
	 */
	public static HttpRange createByteRange(long firstBytePos) {
		return new ByteRange(firstBytePos, null);
	}

	/**
100
	 * Create a {@code HttpRange} from the given fist to last position.
101 102
	 * @param firstBytePos the first byte position
	 * @param lastBytePos the last byte position
103
	 * @return a byte range that ranges from {@code firstPos} till {@code lastPos}
104 105 106 107 108 109 110
	 * @see <a href="http://tools.ietf.org/html/rfc7233#section-2.1">Byte Ranges</a>
	 */
	public static HttpRange createByteRange(long firstBytePos, long lastBytePos) {
		return new ByteRange(firstBytePos, lastBytePos);
	}

	/**
111 112
	 * Create an {@code HttpRange} that ranges over the last given number of bytes.
	 * @param suffixLength the number of bytes for the range
113 114 115 116 117 118 119 120 121 122 123 124 125 126
	 * @return a byte range that ranges over the last {@code suffixLength} number of bytes
	 * @see <a href="http://tools.ietf.org/html/rfc7233#section-2.1">Byte Ranges</a>
	 */
	public static HttpRange createSuffixRange(long suffixLength) {
		return new SuffixByteRange(suffixLength);
	}

	/**
	 * Parse the given, comma-separated string into a list of {@code HttpRange} objects.
	 * <p>This method can be used to parse an {@code Range} header.
	 * @param ranges the string to parse
	 * @return the list of ranges
	 * @throws IllegalArgumentException if the string cannot be parsed
	 */
127
	public static List<HttpRange> parseRanges(@Nullable String ranges) {
128 129 130 131
		if (!StringUtils.hasLength(ranges)) {
			return Collections.emptyList();
		}
		if (!ranges.startsWith(BYTE_RANGE_PREFIX)) {
132
			throw new IllegalArgumentException("Range '" + ranges + "' does not start with 'bytes='");
133 134 135
		}
		ranges = ranges.substring(BYTE_RANGE_PREFIX.length());

136
		String[] tokens = StringUtils.tokenizeToStringArray(ranges, ",");
137
		List<HttpRange> result = new ArrayList<>(tokens.length);
138 139 140 141 142 143 144
		for (String token : tokens) {
			result.add(parseRange(token));
		}
		return result;
	}

	private static HttpRange parseRange(String range) {
J
Juergen Hoeller 已提交
145
		Assert.hasLength(range, "Range String must not be empty");
146
		int dashIdx = range.indexOf('-');
147
		if (dashIdx > 0) {
148 149
			long firstPos = Long.parseLong(range.substring(0, dashIdx));
			if (dashIdx < range.length() - 1) {
150 151
				Long lastPos = Long.parseLong(range.substring(dashIdx + 1, range.length()));
				return new ByteRange(firstPos, lastPos);
152 153
			}
			else {
154
				return new ByteRange(firstPos, null);
155 156
			}
		}
157
		else if (dashIdx == 0) {
158 159 160
			long suffixLength = Long.parseLong(range.substring(1));
			return new SuffixByteRange(suffixLength);
		}
161 162 163
		else {
			throw new IllegalArgumentException("Range '" + range + "' does not contain \"-\"");
		}
164 165
	}

166
	/**
J
Juergen Hoeller 已提交
167 168
	 * Convert each {@code HttpRange} into a {@code ResourceRegion}, selecting the
	 * appropriate segment of the given {@code Resource} using HTTP Range information.
169 170 171
	 * @param ranges the list of ranges
	 * @param resource the resource to select the regions from
	 * @return the list of regions for the given resource
J
Juergen Hoeller 已提交
172
	 * @since 4.3
173 174
	 */
	public static List<ResourceRegion> toResourceRegions(List<HttpRange> ranges, Resource resource) {
J
Juergen Hoeller 已提交
175
		if (CollectionUtils.isEmpty(ranges)) {
176 177
			return Collections.emptyList();
		}
178
		List<ResourceRegion> regions = new ArrayList<>(ranges.size());
J
Juergen Hoeller 已提交
179
		for (HttpRange range : ranges) {
180 181 182 183 184
			regions.add(range.toResourceRegion(resource));
		}
		return regions;
	}

185 186 187 188 189 190 191
	/**
	 * Return a string representation of the given list of {@code HttpRange} objects.
	 * <p>This method can be used to for an {@code Range} header.
	 * @param ranges the ranges to create a string of
	 * @return the string representation
	 */
	public static String toString(Collection<HttpRange> ranges) {
J
Juergen Hoeller 已提交
192
		Assert.notEmpty(ranges, "Ranges Collection must not be empty");
193 194 195
		StringBuilder builder = new StringBuilder(BYTE_RANGE_PREFIX);
		for (Iterator<HttpRange> iterator = ranges.iterator(); iterator.hasNext(); ) {
			HttpRange range = iterator.next();
J
Juergen Hoeller 已提交
196
			builder.append(range);
197 198 199 200 201 202 203
			if (iterator.hasNext()) {
				builder.append(", ");
			}
		}
		return builder.toString();
	}

204

205 206 207 208 209 210 211 212 213 214 215 216
	/**
	 * Represents an HTTP/1.1 byte range, with a first and optional last position.
	 * @see <a href="http://tools.ietf.org/html/rfc7233#section-2.1">Byte Ranges</a>
	 * @see HttpRange#createByteRange(long)
	 * @see HttpRange#createByteRange(long, long)
	 */
	private static class ByteRange extends HttpRange {

		private final long firstPos;

		private final Long lastPos;

217
		public ByteRange(long firstPos, @Nullable Long lastPos) {
218
			assertPositions(firstPos, lastPos);
219 220 221 222
			this.firstPos = firstPos;
			this.lastPos = lastPos;
		}

223
		private void assertPositions(long firstBytePos, @Nullable Long lastBytePos) {
224
			if (firstBytePos < 0) {
J
Juergen Hoeller 已提交
225
				throw new IllegalArgumentException("Invalid first byte position: " + firstBytePos);
226 227
			}
			if (lastBytePos != null && lastBytePos < firstBytePos) {
J
Juergen Hoeller 已提交
228
				throw new IllegalArgumentException("firstBytePosition=" + firstBytePos +
229 230 231 232
						" should be less then or equal to lastBytePosition=" + lastBytePos);
			}
		}

233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248
		@Override
		public long getRangeStart(long length) {
			return this.firstPos;
		}

		@Override
		public long getRangeEnd(long length) {
			if (this.lastPos != null && this.lastPos < length) {
				return this.lastPos;
			}
			else {
				return length - 1;
			}
		}

		@Override
J
Juergen Hoeller 已提交
249 250
		public boolean equals(Object other) {
			if (this == other) {
251 252
				return true;
			}
J
Juergen Hoeller 已提交
253
			if (!(other instanceof ByteRange)) {
254 255
				return false;
			}
J
Juergen Hoeller 已提交
256 257 258
			ByteRange otherRange = (ByteRange) other;
			return (this.firstPos == otherRange.firstPos &&
					ObjectUtils.nullSafeEquals(this.lastPos, otherRange.lastPos));
259 260 261 262
		}

		@Override
		public int hashCode() {
J
Juergen Hoeller 已提交
263 264 265 266 267 268 269 270 271 272 273 274 275
			return (ObjectUtils.nullSafeHashCode(this.firstPos) * 31 +
					ObjectUtils.nullSafeHashCode(this.lastPos));
		}

		@Override
		public String toString() {
			StringBuilder builder = new StringBuilder();
			builder.append(this.firstPos);
			builder.append('-');
			if (this.lastPos != null) {
				builder.append(this.lastPos);
			}
			return builder.toString();
276 277 278
		}
	}

J
Juergen Hoeller 已提交
279

280 281 282 283 284 285 286 287 288
	/**
	 * Represents an HTTP/1.1 suffix byte range, with a number of suffix bytes.
	 * @see <a href="http://tools.ietf.org/html/rfc7233#section-2.1">Byte Ranges</a>
	 * @see HttpRange#createSuffixRange(long)
	 */
	private static class SuffixByteRange extends HttpRange {

		private final long suffixLength;

J
Juergen Hoeller 已提交
289
		public SuffixByteRange(long suffixLength) {
290
			if (suffixLength < 0) {
J
Juergen Hoeller 已提交
291
				throw new IllegalArgumentException("Invalid suffix length: " + suffixLength);
292
			}
293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310
			this.suffixLength = suffixLength;
		}

		@Override
		public long getRangeStart(long length) {
			if (this.suffixLength < length) {
				return length - this.suffixLength;
			}
			else {
				return 0;
			}
		}

		@Override
		public long getRangeEnd(long length) {
			return length - 1;
		}

311
		@Override
J
Juergen Hoeller 已提交
312 313
		public boolean equals(Object other) {
			if (this == other) {
314 315
				return true;
			}
J
Juergen Hoeller 已提交
316
			if (!(other instanceof SuffixByteRange)) {
317 318
				return false;
			}
J
Juergen Hoeller 已提交
319 320
			SuffixByteRange otherRange = (SuffixByteRange) other;
			return (this.suffixLength == otherRange.suffixLength);
321 322 323 324
		}

		@Override
		public int hashCode() {
325
			return Long.hashCode(this.suffixLength);
326
		}
J
Juergen Hoeller 已提交
327 328 329 330 331

		@Override
		public String toString() {
			return "-" + this.suffixLength;
		}
332
	}
J
Juergen Hoeller 已提交
333

334
}