Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- @Context
- private HttpHeaders headers;
- @Inject
- private ResourceInfo resourceInfo;
- private final static Set<MediaType> MEDIA_SUPPORTED = new HashSet<>(Arrays.asList(
- MediaType.APPLICATION_JSON_TYPE, MediaType.TEXT_HTML_TYPE));
- private MediaType getMediaType() {
- Optional<MediaType> mt = getMediaTypeFromHeaders(headers);
- if (!mt.isPresent()) {
- mt = getMediaTypeFromMethodAnnotation(resourceInfo);
- }
- if (!mt.isPresent()) {
- mt = Optional.of(MediaType.TEXT_HTML_TYPE);
- }
- return mt.get();
- }
- private Optional<MediaType> getMediaTypeFromMethodAnnotation(final ResourceInfo resourceInfo) {
- final Optional<Method> method = Optional.fromNullable(
- resourceInfo.getResourceMethod());
- if (!method.isPresent()) {
- return Optional.absent();
- }
- Optional<Produces> produces = Optional.fromNullable(
- method.get().getAnnotation(Produces.class));
- if (!produces.isPresent()) {
- final Class<?> cls = resourceInfo.getResourceClass();
- produces = Optional.fromNullable((Produces) cls.getAnnotation(Produces.class));
- }
- if (!produces.isPresent()) {
- return Optional.absent();
- }
- final List<String> mediaTypes = new LinkedList<>();
- for (final String mtlist: produces.get().value()) { // comma separated list
- for (final String mt: mtlist.split(",")) {
- mediaTypes.add(mt.trim());
- }
- }
- for (final String mtype: mediaTypes) {
- final MediaType putativeType;
- try {
- putativeType = MediaType.valueOf(mtype);
- } catch (IllegalArgumentException e) {
- // this might be impossible if JAX-RS validates the method annotations...
- LoggerFactory.getLogger(getClass()).error(String.format(
- "Invalid @Produces annotation on method %s: %s",
- method.get().toGenericString(), mtype));
- continue; // an else block like python would be nice here
- }
- if (MEDIA_SUPPORTED.contains(putativeType)) {
- return Optional.of(putativeType);
- } else {
- LoggerFactory.getLogger(getClass()).error(String.format(
- "Unsupported @Produces annotation on method %s: %s",
- method.get().toGenericString(), mtype));
- }
- }
- return Optional.absent();
- }
- /* JAX-RS will cause an error to be thrown if the Accept header does not contain a supported
- * media type, so we can ignore any unsupported types here
- */
- private Optional<MediaType> getMediaTypeFromHeaders(final HttpHeaders headers) {
- //sorted by q-value
- final Optional<List<MediaType>> mtypes = Optional.fromNullable(
- headers.getAcceptableMediaTypes());
- if (mtypes.isPresent()) {
- for (final MediaType m: mtypes.get()) {
- if (MEDIA_SUPPORTED.contains(m)) {
- return Optional.of(m);
- }
- }
- }
- return Optional.absent();
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement