Created
September 25, 2015 04:43
-
-
Save gliviu/aa8f7cdf8198109bcdf3 to your computer and use it in GitHub Desktop.
Java Http header byte range decoder
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.regex.Matcher; | |
import java.util.regex.Pattern; | |
/** | |
* Http header byte range decoder. | |
* According to http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35 | |
*/ | |
public class ParseHeaderByteRange { | |
public static void main(final String[] args) { | |
final String input = "bytes=33-22,-333,20-"; | |
final String byteRangeSetRegex = "(((?<byteRangeSpec>(?<firstBytePos>\\d+)-(?<lastBytePos>\\d+)?)|(?<suffixByteRangeSpec>-(?<suffixLength>\\d+)))(,|$))"; | |
final String byteRangesSpecifierRegex = "bytes=(?<byteRangeSet>" + byteRangeSetRegex + "{1,})"; | |
final Pattern byteRangeSetPattern = Pattern.compile(byteRangeSetRegex); | |
final Pattern byteRangesSpecifierPattern = Pattern.compile(byteRangesSpecifierRegex); | |
final Matcher byteRangesSpecifierMatcher = byteRangesSpecifierPattern.matcher(input); | |
if (byteRangesSpecifierMatcher.matches()) { | |
final String byteRangeSet = byteRangesSpecifierMatcher.group("byteRangeSet"); | |
final Matcher byteRangeSetMatcher = byteRangeSetPattern.matcher(byteRangeSet); | |
while (byteRangeSetMatcher.find()) { | |
if (byteRangeSetMatcher.group("byteRangeSpec") != null) { | |
System.out.println( | |
String.format("range: %s->%s", byteRangeSetMatcher.group("firstBytePos"), byteRangeSetMatcher.group("lastBytePos"))); | |
} | |
if (byteRangeSetMatcher.group("suffixByteRangeSpec") != null) { | |
System.out.println(String.format("suffix length: %s", byteRangeSetMatcher.group("suffixLength"))); | |
} | |
} | |
} else { | |
System.out.println("Invalid range header"); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment