1 | package eu.clarin.cmdi.virtualcollectionregistry.rest; |
---|
2 | |
---|
3 | import eu.clarin.cmdi.virtualcollectionregistry.service.VirtualCollectionMarshaller.Format; |
---|
4 | import java.util.List; |
---|
5 | import javax.ws.rs.core.HttpHeaders; |
---|
6 | import javax.ws.rs.core.MediaType; |
---|
7 | |
---|
8 | /** |
---|
9 | * REST input/ouput utilities for the Virtual Collection Registry REST resources |
---|
10 | * |
---|
11 | * @author twagoo |
---|
12 | */ |
---|
13 | public final class RestUtils { |
---|
14 | |
---|
15 | /** |
---|
16 | * |
---|
17 | * @param headers |
---|
18 | * @return the encoding specified in the headers, defaults to "utf-8" if |
---|
19 | * none is specified |
---|
20 | * @see HttpHeaders#getMediaType() |
---|
21 | */ |
---|
22 | public static String getInputEncoding(HttpHeaders headers) { |
---|
23 | String encoding |
---|
24 | = headers.getMediaType().getParameters().get("encoding"); |
---|
25 | return (encoding != null) ? encoding : "utf-8"; |
---|
26 | } |
---|
27 | |
---|
28 | /** |
---|
29 | * |
---|
30 | * @param headers |
---|
31 | * @return the input format specified in the headers, normalises to |
---|
32 | * {@link Format#XML} or {@link Format#JSON}, or defaults to |
---|
33 | * {@link Format#UNSUPPORTED} if none is specified in the headers |
---|
34 | * @see HttpHeaders#getMediaType() |
---|
35 | */ |
---|
36 | public static Format getInputFormat(HttpHeaders headers) { |
---|
37 | Format format = getMediaType(headers.getMediaType()); |
---|
38 | return (format != null) ? format : Format.UNSUPPORTED; |
---|
39 | } |
---|
40 | |
---|
41 | /** |
---|
42 | * |
---|
43 | * @param headers |
---|
44 | * @return the first accepted output format specified in the headers that |
---|
45 | * can be normalised to {@link Format#XML} or {@link Format#JSON}, or |
---|
46 | * defaults to {@link Format#UNSUPPORTED} if none is specified in the |
---|
47 | * headers |
---|
48 | * @see HttpHeaders#getAcceptableMediaTypes() |
---|
49 | */ |
---|
50 | public static Format getOutputFormat(List<MediaType> mediaTypes) { |
---|
51 | for (MediaType type : mediaTypes) { |
---|
52 | Format format = getMediaType(type); |
---|
53 | if (format != null) { |
---|
54 | return format; |
---|
55 | } |
---|
56 | } |
---|
57 | return Format.UNSUPPORTED; |
---|
58 | } |
---|
59 | |
---|
60 | private static Format getMediaType(MediaType type) { |
---|
61 | if (type.isCompatible(MediaType.APPLICATION_XML_TYPE) |
---|
62 | || type.isCompatible(MediaType.TEXT_XML_TYPE)) { |
---|
63 | return Format.XML; |
---|
64 | } |
---|
65 | if (type.isCompatible(MediaType.APPLICATION_JSON_TYPE)) { |
---|
66 | return Format.JSON; |
---|
67 | } |
---|
68 | return null; |
---|
69 | } |
---|
70 | } |
---|