|
package my.application.restutil; |
|
|
|
import javax.servlet.http.HttpServletRequest; |
|
import javax.ws.rs.client.Invocation; |
|
import java.util.Iterator; |
|
import java.util.Map; |
|
|
|
public class RequestOptions { |
|
|
|
public static final String HEADER_RECURSION = "X-Recursion"; |
|
public static final String RECURSION_ENABLED = "true"; |
|
public static final String RECURSION_DISABLED = "false"; |
|
|
|
private Pagination pagination = null; |
|
private Filtering filtering = null; |
|
private boolean recursive = false; |
|
private Fields fields = null; |
|
private Sorting sorting = null; |
|
|
|
public RequestOptions() { |
|
} |
|
|
|
public RequestOptions(HttpServletRequest request) { |
|
parse(request); |
|
} |
|
|
|
public Pagination getPagination() { |
|
return pagination; |
|
} |
|
|
|
public Filtering getFiltering() { |
|
return filtering; |
|
} |
|
|
|
public Fields getFields() { |
|
return fields; |
|
} |
|
|
|
public boolean isRecursive() { |
|
return recursive; |
|
} |
|
|
|
public Sorting getSorting() { |
|
return sorting; |
|
} |
|
|
|
public Invocation.Builder apply(Invocation.Builder builder) { |
|
if (pagination != null) { |
|
builder.header(PaginationFactory.HEADER_OFFSET, pagination.getOffset()); |
|
builder.header(PaginationFactory.HEADER_LIMIT, pagination.getLimit()); |
|
} |
|
return builder; |
|
} |
|
|
|
public RequestOptions parse(final HttpServletRequest request) { |
|
String recursion = request.getHeader(HEADER_RECURSION); |
|
if (recursion != null && recursion.trim().equalsIgnoreCase(RECURSION_ENABLED)) { |
|
recursive = true; |
|
} else { |
|
for (Iterator<Map.Entry<String, String[]>> iterator = request.getParameterMap().entrySet().iterator(); iterator.hasNext(); ) { |
|
Map.Entry<String, String[]> entry = iterator.next(); |
|
String key = entry.getKey(); |
|
String value = entry.getValue()[0]; |
|
if (key.equalsIgnoreCase("recursive") && value.trim().equalsIgnoreCase(RECURSION_ENABLED)) { |
|
recursive = true; |
|
} |
|
} |
|
} |
|
this.pagination = PaginationFactory.parse(request); |
|
this.filtering = FilteringFactory.parse(request); |
|
this.fields = FieldsFactory.parse(request); |
|
this.sorting = SortingFactory.parse(request); |
|
return this; |
|
} |
|
|
|
@Override |
|
public String toString() { |
|
StringBuilder str = new StringBuilder(); |
|
if (pagination != null) { |
|
str.append("Request Options: {" + pagination.toString() + ", Recursion: " + recursive + "}\n"); |
|
} else { |
|
str.append("No pagination defined\n"); |
|
} |
|
if (filtering != null) { |
|
str.append("Request Options: {" + filtering.toString() + ", Recursion: " + recursive + "}\n"); |
|
} else { |
|
str.append("No filtering defined\n"); |
|
} |
|
if (sorting != null) { |
|
str.append("Request Options: {" + sorting.toString() + ", Recursion: " + recursive + "}\n"); |
|
} else { |
|
str.append("No sorting defined\n"); |
|
} |
|
return str.toString(); |
|
} |
|
} |