RangesHeaderDelegate implements RuntimeDelegate.HeaderDelegate<Ranges> { @Override public Ranges fromString(String value) throws IllegalArgumentException { if (value == null) { throw new IllegalArgumentException(); } if (!value.startsWith("bytes")) { throw new IllegalArgumentException(String.format("Invalid byte range: %s", value)); } int eq = scan(value, '='); if (charAtIsNot(value, eq, '=')) { throw new IllegalArgumentException(String.format("Invalid byte range: %s", value)); } value = value.substring(eq + 1); String[] tokens = value.split(","); List<Range> ranges = new ArrayList<>(); for (String token : tokens) { long start = 0; long end = -1L; token = token.trim(); int dash = scan(token, '-'); if (charAtIsNot(token, dash, '-')) { throw new IllegalArgumentException("Invalid byte range."); } else if (dash == 0) { start = Long.parseLong(token); } else if (dash > 0) { start = Long.parseLong(token.substring(0, dash).trim()); if (dash < token.length() - 1) { end = Long.parseLong(token.substring(dash + 1, token.length()).trim()); } } ranges.add(new Range(start, end)); } return new Ranges(ranges); }  @Override Ranges fromString(String value); @Override String toString(Ranges value);  }
@Test public void parsesSingleRange() { Ranges ranges = rangesHeaderDelegate.fromString("bytes=49-100"); assertEquals(newArrayList(new Range(49, 100)), ranges.getRanges()); }
@Test public void parsesSingleRangeWithoutStart() { Ranges ranges = rangesHeaderDelegate.fromString("bytes=-100"); assertEquals(newArrayList(new Range(-100, -1)), ranges.getRanges()); }
@Test public void parsesSingleRangeWithoutEnd() { Ranges ranges = rangesHeaderDelegate.fromString("bytes=100-"); assertEquals(newArrayList(new Range(100, -1)), ranges.getRanges()); }
@Test public void parsesMultiRangeWithoutStart() { Ranges ranges = rangesHeaderDelegate.fromString("bytes=49-100,150-250"); assertEquals(newArrayList(new Range(49, 100), new Range(150, 250)), ranges.getRanges()); }
@Test(expected = IllegalArgumentException.class) public void throwsExceptionWhenByteRangesHeaderIsNull() throws Exception { rangesHeaderDelegate.fromString(null); }
@Test(expected = IllegalArgumentException.class) public void throwsExceptionWhenByteRangesHeaderDoesNotStartWith_bytes() throws Exception { rangesHeaderDelegate.fromString("49-100"); }
@Test(expected = IllegalArgumentException.class) public void throwsExceptionWhenByteRangesHeaderDoesNotContainEqual() throws Exception { rangesHeaderDelegate.fromString("bytes49-100"); }
@Test(expected = IllegalArgumentException.class) public void throwsExceptionWhenByteRangesHeaderDoesNotContainDash() throws Exception { rangesHeaderDelegate.fromString("bytes=100"); }