Reputation: 2718
I want to use the http header 'Range' in a Jax-rs application, can I define a unit for this? for example, number of records.
What I want to implement is to limit the number of records returned in the response to the maximum value of the 'Range'
Upvotes: 2
Views: 983
Reputation: 10961
For parsing more complex Parameters you can implement a ParamConverter:
@Provider
public class RangeHeaderConverter implements ParamConverter<RangeHeader> {
@Override
public RangeHeader fromString(String value) {
return RangeHeader.fromValue(value);
}
@Override
public String toString(RangeHeader value) {
return value.toString();
}
}
The implementation of your RangeHeader might look like this:
public class RangeHeader {
public static enum Unit {
BYTES;
}
private Unit unit;
private long from;
private long to;
public RangeHeader(Unit unit, long from, long to) {
this.unit = unit;
this.from = from;
this.to = to;
}
public Unit getUnit() {
return unit;
}
public long getFrom() {
return from;
}
public long getTo() {
return to;
}
public static RangeHeader fromValue(String range) {
if (range == null) {
return null;
}
String[] tokens = range.replace("Range: ", "").split("=");
Unit unit = Unit.valueOf(tokens[0].toUpperCase());
String[] fromTo = tokens[1].split("-");
long from = Long.valueOf(fromTo[0]);
long to = Long.valueOf(fromTo[1]);
return new RangeHeader(unit, from, to);
}
public String toString() {
return String.format("Range: %s=%d-%d", unit.name().toLowerCase(), from, to);
}
}
You can use this class like this:
public Response get(@HeaderParam("Range") RangeHeader range) {
//
}
Note: This is just a quick+dirty implementation and doesn't handle special values or errors.
Upvotes: 3