Search in sources :

Example 16 with MediaType

use of javax.ws.rs.core.MediaType in project jersey by jersey.

the class CombinedMediaType method create.

/**
     * Create combined client/server media type.
     *
     * if the two types are not compatible, {@link #NO_MATCH} is returned.
     *
     * @param clientType client-side media type.
     * @param serverType server-side media type.
     * @return combined client/server media type.
     */
static CombinedMediaType create(MediaType clientType, EffectiveMediaType serverType) {
    if (!clientType.isCompatible(serverType.getMediaType())) {
        return NO_MATCH;
    }
    final MediaType strippedClientType = MediaTypes.stripQualityParams(clientType);
    final MediaType strippedServerType = MediaTypes.stripQualityParams(serverType.getMediaType());
    return new CombinedMediaType(MediaTypes.mostSpecific(strippedClientType, strippedServerType), MediaTypes.getQuality(clientType), QualitySourceMediaType.getQualitySource(serverType.getMediaType()), matchedWildcards(clientType, serverType));
}
Also used : MediaType(javax.ws.rs.core.MediaType) QualitySourceMediaType(org.glassfish.jersey.message.internal.QualitySourceMediaType)

Example 17 with MediaType

use of javax.ws.rs.core.MediaType in project jersey by jersey.

the class MethodSelectingRouter method getMethodRouter.

private List<Router> getMethodRouter(final RequestProcessingContext context) {
    final ContainerRequest request = context.request();
    final List<ConsumesProducesAcceptor> acceptors = consumesProducesAcceptors.get(request.getMethod());
    if (acceptors == null) {
        throw new NotAllowedException(Response.status(Status.METHOD_NOT_ALLOWED).allow(consumesProducesAcceptors.keySet()).build());
    }
    final List<ConsumesProducesAcceptor> satisfyingAcceptors = new LinkedList<>();
    final Set<ResourceMethod> differentInvokableMethods = Collections.newSetFromMap(new IdentityHashMap<>());
    for (ConsumesProducesAcceptor cpi : acceptors) {
        if (cpi.isConsumable(request)) {
            satisfyingAcceptors.add(cpi);
            differentInvokableMethods.add(cpi.methodRouting.method);
        }
    }
    if (satisfyingAcceptors.isEmpty()) {
        throw new NotSupportedException();
    }
    final List<AcceptableMediaType> acceptableMediaTypes = request.getQualifiedAcceptableMediaTypes();
    final MediaType requestContentType = request.getMediaType();
    final MediaType effectiveContentType = requestContentType == null ? MediaType.WILDCARD_TYPE : requestContentType;
    final MethodSelector methodSelector = selectMethod(acceptableMediaTypes, satisfyingAcceptors, effectiveContentType, differentInvokableMethods.size() == 1);
    if (methodSelector.selected != null) {
        final RequestSpecificConsumesProducesAcceptor selected = methodSelector.selected;
        if (methodSelector.sameFitnessAcceptors != null) {
            reportMethodSelectionAmbiguity(acceptableMediaTypes, methodSelector.selected, methodSelector.sameFitnessAcceptors);
        }
        context.push(new Function<ContainerResponse, ContainerResponse>() {

            @Override
            public ContainerResponse apply(final ContainerResponse responseContext) {
                // - either there is an entity, or we are responding to a HEAD request
                if (responseContext.getMediaType() == null && ((responseContext.hasEntity() || HttpMethod.HEAD.equals(request.getMethod())))) {
                    MediaType effectiveResponseType = determineResponseMediaType(responseContext.getEntityClass(), responseContext.getEntityType(), methodSelector.selected, acceptableMediaTypes);
                    if (MediaTypes.isWildcard(effectiveResponseType)) {
                        if (effectiveResponseType.isWildcardType() || "application".equalsIgnoreCase(effectiveResponseType.getType())) {
                            effectiveResponseType = MediaType.APPLICATION_OCTET_STREAM_TYPE;
                        } else {
                            throw new NotAcceptableException();
                        }
                    }
                    responseContext.setMediaType(effectiveResponseType);
                }
                return responseContext;
            }
        });
        return selected.methodRouting.routers;
    }
    throw new NotAcceptableException();
}
Also used : NotAllowedException(javax.ws.rs.NotAllowedException) ContainerResponse(org.glassfish.jersey.server.ContainerResponse) LinkedList(java.util.LinkedList) NotAcceptableException(javax.ws.rs.NotAcceptableException) AcceptableMediaType(org.glassfish.jersey.message.internal.AcceptableMediaType) MediaType(javax.ws.rs.core.MediaType) AcceptableMediaType(org.glassfish.jersey.message.internal.AcceptableMediaType) ContainerRequest(org.glassfish.jersey.server.ContainerRequest) NotSupportedException(javax.ws.rs.NotSupportedException) ResourceMethod(org.glassfish.jersey.server.model.ResourceMethod)

Example 18 with MediaType

use of javax.ws.rs.core.MediaType in project jersey by jersey.

the class RequestUtil method getEntityParameters.

/**
     * Returns the form parameters from a request entity as a multi-valued map.
     * If the request does not have a POST method, or the media type is not
     * x-www-form-urlencoded, then null is returned.
     *
     * @param request the client request containing the entity to extract parameters from.
     * @return a {@link javax.ws.rs.core.MultivaluedMap} containing the entity form parameters.
     */
@SuppressWarnings("unchecked")
public static MultivaluedMap<String, String> getEntityParameters(ClientRequestContext request, MessageBodyWorkers messageBodyWorkers) {
    Object entity = request.getEntity();
    String method = request.getMethod();
    MediaType mediaType = request.getMediaType();
    // no entity, not a post or not x-www-form-urlencoded: return empty map
    if (entity == null || method == null || !HttpMethod.POST.equalsIgnoreCase(method) || mediaType == null || !mediaType.equals(MediaType.APPLICATION_FORM_URLENCODED_TYPE)) {
        return new MultivaluedHashMap<String, String>();
    }
    // it's ready to go if already expressed as a multi-valued map
    if (entity instanceof MultivaluedMap) {
        return (MultivaluedMap<String, String>) entity;
    }
    Type entityType = entity.getClass();
    // if the entity is generic, get specific type and class
    if (entity instanceof GenericEntity) {
        final GenericEntity generic = (GenericEntity) entity;
        // overwrite
        entityType = generic.getType();
        entity = generic.getEntity();
    }
    final Class entityClass = entity.getClass();
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    MessageBodyWriter writer = messageBodyWorkers.getMessageBodyWriter(entityClass, entityType, EMPTY_ANNOTATIONS, MediaType.APPLICATION_FORM_URLENCODED_TYPE);
    try {
        writer.writeTo(entity, entityClass, entityType, EMPTY_ANNOTATIONS, MediaType.APPLICATION_FORM_URLENCODED_TYPE, null, out);
    } catch (WebApplicationException wae) {
        throw new IllegalStateException(wae);
    } catch (IOException ioe) {
        throw new IllegalStateException(ioe);
    }
    ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
    MessageBodyReader reader = messageBodyWorkers.getMessageBodyReader(MultivaluedMap.class, MultivaluedMap.class, EMPTY_ANNOTATIONS, MediaType.APPLICATION_FORM_URLENCODED_TYPE);
    try {
        return (MultivaluedMap<String, String>) reader.readFrom(MultivaluedMap.class, MultivaluedMap.class, EMPTY_ANNOTATIONS, MediaType.APPLICATION_FORM_URLENCODED_TYPE, null, in);
    } catch (IOException ioe) {
        throw new IllegalStateException(ioe);
    }
}
Also used : WebApplicationException(javax.ws.rs.WebApplicationException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) MultivaluedHashMap(javax.ws.rs.core.MultivaluedHashMap) MessageBodyReader(javax.ws.rs.ext.MessageBodyReader) MediaType(javax.ws.rs.core.MediaType) Type(java.lang.reflect.Type) ByteArrayInputStream(java.io.ByteArrayInputStream) GenericEntity(javax.ws.rs.core.GenericEntity) MediaType(javax.ws.rs.core.MediaType) MultivaluedMap(javax.ws.rs.core.MultivaluedMap) MessageBodyWriter(javax.ws.rs.ext.MessageBodyWriter)

Example 19 with MediaType

use of javax.ws.rs.core.MediaType in project jersey by jersey.

the class InboundEvent method readData.

/**
     * Read event data as a given generic type.
     *
     * @param type      generic type to be used for event data de-serialization.
     * @param mediaType {@link MediaType media type} to be used for event data de-serialization.
     * @return event data de-serialized as an instance of a given type.
     * @throws javax.ws.rs.ProcessingException when provided type can't be read. The thrown exception wraps the original cause.
     * @since 2.3
     */
public <T> T readData(GenericType<T> type, MediaType mediaType) {
    final MediaType effectiveMediaType = mediaType == null ? this.mediaType : mediaType;
    final MessageBodyReader reader = messageBodyWorkers.getMessageBodyReader(type.getRawType(), type.getType(), annotations, mediaType);
    if (reader == null) {
        throw new MessageBodyProviderNotFoundException(LocalizationMessages.EVENT_DATA_READER_NOT_FOUND());
    }
    return readAndCast(type, effectiveMediaType, reader);
}
Also used : MessageBodyReader(javax.ws.rs.ext.MessageBodyReader) MessageBodyProviderNotFoundException(org.glassfish.jersey.message.internal.MessageBodyProviderNotFoundException) MediaType(javax.ws.rs.core.MediaType)

Example 20 with MediaType

use of javax.ws.rs.core.MediaType in project jersey by jersey.

the class FormDataMultiPartReaderWriterTest method testMediaTypeWithBoundaryResource.

@Test
public void testMediaTypeWithBoundaryResource() {
    final Map<String, String> parameters = new HashMap<>();
    parameters.put("boundary", "XXXX_YYYY");
    final MediaType mediaType = new MediaType(MediaType.MULTIPART_FORM_DATA_TYPE.getType(), MediaType.MULTIPART_FORM_DATA_TYPE.getSubtype(), parameters);
    final FormDataMultiPart entity = new FormDataMultiPart().field("submit", "OK");
    final Invocation.Builder request = target().path("MediaTypeWithBoundaryResource").request("text/plain");
    final String response = request.put(Entity.entity(entity, mediaType), String.class);
    assertEquals("OK", response);
}
Also used : Invocation(javax.ws.rs.client.Invocation) HashMap(java.util.HashMap) MediaType(javax.ws.rs.core.MediaType) FormDataMultiPart(org.glassfish.jersey.media.multipart.FormDataMultiPart) Test(org.junit.Test)

Aggregations

MediaType (javax.ws.rs.core.MediaType)228 Test (org.junit.Test)112 ResponseBuilder (javax.ws.rs.core.Response.ResponseBuilder)29 Path (javax.ws.rs.Path)25 Produces (javax.ws.rs.Produces)24 WebApplicationException (javax.ws.rs.WebApplicationException)24 ByteArrayInputStream (java.io.ByteArrayInputStream)20 HashSet (java.util.HashSet)20 MediaTypeUtil.getAcceptableMediaType (org.apache.stanbol.commons.web.base.utils.MediaTypeUtil.getAcceptableMediaType)20 IOException (java.io.IOException)18 AcceptableMediaType (org.glassfish.jersey.message.internal.AcceptableMediaType)18 InputStream (java.io.InputStream)16 GET (javax.ws.rs.GET)16 ContainerResponse (org.glassfish.jersey.server.ContainerResponse)16 EntityhubLDPath (org.apache.stanbol.entityhub.ldpath.EntityhubLDPath)15 ArrayList (java.util.ArrayList)14 Consumes (javax.ws.rs.Consumes)14 HashMap (java.util.HashMap)13 Viewable (org.apache.stanbol.commons.web.viewable.Viewable)12 MultiPart (org.glassfish.jersey.media.multipart.MultiPart)12