Search in sources :

Example 36 with MediaType

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

the class CharsetTest method _test.

@Override
public <T> void _test(T in, Class resource, MediaType m) {
    WebTarget t = target(resource.getSimpleName());
    for (String charset : CHARSETS) {
        Map<String, String> p = new HashMap<>();
        p.put("charset", charset);
        MediaType _m = new MediaType(m.getType(), m.getSubtype(), p);
        Response rib = t.request().post(Entity.entity(in, _m));
        byte[] inBytes = getRequestEntity();
        byte[] outBytes = getEntityAsByteArray(rib);
        _verify(inBytes, outBytes);
    }
}
Also used : ClientResponse(org.glassfish.jersey.client.ClientResponse) Response(javax.ws.rs.core.Response) HashMap(java.util.HashMap) MultivaluedHashMap(javax.ws.rs.core.MultivaluedHashMap) MediaType(javax.ws.rs.core.MediaType) WebTarget(javax.ws.rs.client.WebTarget)

Example 37 with MediaType

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

the class ModelProcessorUtil method enhanceResource.

/**
     * Enhance the runtime resource referenced by {@code resource} parameter with a list of additional methods.
     *
     * The new {@code methods} are added to the runtime resource. In case of method conflicts, the existing resource methods
     * will be preserved and will not be 'overridden' by any new method from the {@code methods} list.
     * Overriding check takes into account media types of methods so that new resource methods with same HTTP method
     * can be defined only for a more more specific media type.
     *
     * @param resource Runtime resource to be enhanced.
     * @param enhancedModelBuilder Builder for the enhanced resource model to be used.
     * @param methods List of enhancing methods.
     * @param extended This flag will initialize the property
     *                  {@link org.glassfish.jersey.server.model.ResourceMethod#isExtended()}.
     */
public static void enhanceResource(RuntimeResource resource, ResourceModel.Builder enhancedModelBuilder, List<Method> methods, boolean extended) {
    final Resource firstResource = resource.getResources().get(0);
    if (methodsSuitableForResource(firstResource, methods)) {
        for (Method method : methods) {
            final Set<MediaType> produces = new HashSet<>(method.produces);
            for (ResourceMethod resourceMethod : resource.getResourceMethods()) {
                for (final MediaType produce : method.produces) {
                    if (ModelProcessorUtil.isMethodOverridden(resourceMethod, method.httpMethod, method.consumes.get(0), produce)) {
                        produces.remove(produce);
                    }
                }
            }
            if (!produces.isEmpty()) {
                final Resource parentResource = resource.getParentResources().get(0);
                if (parentResource != null && method.path != null) {
                    continue;
                }
                final Resource.Builder resourceBuilder = Resource.builder(firstResource.getPath());
                final Resource.Builder builder = method.path != null ? resourceBuilder.addChildResource(method.path) : resourceBuilder;
                final ResourceMethod.Builder methodBuilder = builder.addMethod(method.httpMethod).consumes(method.consumes).produces(produces);
                if (method.inflector != null) {
                    methodBuilder.handledBy(method.inflector);
                } else {
                    methodBuilder.handledBy(method.inflectorClass);
                }
                methodBuilder.extended(extended);
                final Resource newResource = resourceBuilder.build();
                if (parentResource != null) {
                    final Resource.Builder parentBuilder = Resource.builder(parentResource.getPath());
                    parentBuilder.addChildResource(newResource);
                    enhancedModelBuilder.addResource(parentBuilder.build());
                } else {
                    enhancedModelBuilder.addResource(newResource);
                }
            }
        }
    }
    for (RuntimeResource child : resource.getChildRuntimeResources()) {
        enhanceResource(child, enhancedModelBuilder, methods, extended);
    }
}
Also used : Resource(org.glassfish.jersey.server.model.Resource) RuntimeResource(org.glassfish.jersey.server.model.RuntimeResource) MediaType(javax.ws.rs.core.MediaType) HttpMethod(javax.ws.rs.HttpMethod) ResourceMethod(org.glassfish.jersey.server.model.ResourceMethod) ResourceMethod(org.glassfish.jersey.server.model.ResourceMethod) HashSet(java.util.HashSet) RuntimeResource(org.glassfish.jersey.server.model.RuntimeResource)

Example 38 with MediaType

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

the class IntrospectionModeller method doCreateResourceBuilder.

private Resource.Builder doCreateResourceBuilder() {
    if (!disableValidation) {
        checkForNonPublicMethodIssues();
    }
    final Class<?> annotatedResourceClass = ModelHelper.getAnnotatedResourceClass(handlerClass);
    final Path rPathAnnotation = annotatedResourceClass.getAnnotation(Path.class);
    final boolean keepEncodedParams = (null != annotatedResourceClass.getAnnotation(Encoded.class));
    final List<MediaType> defaultConsumedTypes = extractMediaTypes(annotatedResourceClass.getAnnotation(Consumes.class));
    final List<MediaType> defaultProducedTypes = extractMediaTypes(annotatedResourceClass.getAnnotation(Produces.class));
    final Collection<Class<? extends Annotation>> defaultNameBindings = ReflectionHelper.getAnnotationTypes(annotatedResourceClass, NameBinding.class);
    final MethodList methodList = new MethodList(handlerClass);
    final List<Parameter> resourceClassParameters = new LinkedList<>();
    checkResourceClassSetters(methodList, keepEncodedParams, resourceClassParameters);
    checkResourceClassFields(keepEncodedParams, InvocableValidator.isSingleton(handlerClass), resourceClassParameters);
    Resource.Builder resourceBuilder;
    if (null != rPathAnnotation) {
        resourceBuilder = Resource.builder(rPathAnnotation.value());
    } else {
        resourceBuilder = Resource.builder();
    }
    boolean extended = false;
    if (handlerClass.isAnnotationPresent(ExtendedResource.class)) {
        resourceBuilder.extended(true);
        extended = true;
    }
    resourceBuilder.name(handlerClass.getName());
    addResourceMethods(resourceBuilder, methodList, resourceClassParameters, keepEncodedParams, defaultConsumedTypes, defaultProducedTypes, defaultNameBindings, extended);
    addSubResourceMethods(resourceBuilder, methodList, resourceClassParameters, keepEncodedParams, defaultConsumedTypes, defaultProducedTypes, defaultNameBindings, extended);
    addSubResourceLocators(resourceBuilder, methodList, resourceClassParameters, keepEncodedParams, extended);
    if (LOGGER.isLoggable(Level.FINEST)) {
        LOGGER.finest(LocalizationMessages.NEW_AR_CREATED_BY_INTROSPECTION_MODELER(resourceBuilder.toString()));
    }
    return resourceBuilder;
}
Also used : Path(javax.ws.rs.Path) Annotation(java.lang.annotation.Annotation) LinkedList(java.util.LinkedList) Consumes(javax.ws.rs.Consumes) Produces(javax.ws.rs.Produces) MediaType(javax.ws.rs.core.MediaType)

Example 39 with MediaType

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

the class JaxbStringReaderProviderTest method stringReaderDoesNotReadExternalDtds.

@Test
public void stringReaderDoesNotReadExternalDtds() {
    Provider<SAXParserFactory> saxParserFactoryProvider = new Provider<SAXParserFactory>() {

        final SaxParserFactoryInjectionProvider spf = new SaxParserFactoryInjectionProvider(new CommonConfig(RuntimeType.SERVER, ComponentBag.INCLUDE_ALL));

        @Override
        public SAXParserFactory get() {
            return spf.get();
        }
    };
    JaxbStringReaderProvider.RootElementProvider provider = new JaxbStringReaderProvider.RootElementProvider(saxParserFactoryProvider, new Providers() {

        @Override
        public <T> MessageBodyReader<T> getMessageBodyReader(Class<T> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
            return null;
        }

        @Override
        public <T> MessageBodyWriter<T> getMessageBodyWriter(Class<T> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
            return null;
        }

        @Override
        public <T extends Throwable> ExceptionMapper<T> getExceptionMapper(Class<T> type) {
            return null;
        }

        @Override
        public <T> ContextResolver<T> getContextResolver(Class<T> contextType, MediaType mediaType) {
            return null;
        }
    });
    String content = "<!DOCTYPE x SYSTEM 'file:///no-such-file'> <rootObject/>";
    provider.getConverter(RootObject.class, null, null).fromString(content);
}
Also used : CommonConfig(org.glassfish.jersey.model.internal.CommonConfig) Providers(javax.ws.rs.ext.Providers) Annotation(java.lang.annotation.Annotation) Provider(javax.inject.Provider) MessageBodyReader(javax.ws.rs.ext.MessageBodyReader) RuntimeType(javax.ws.rs.RuntimeType) MediaType(javax.ws.rs.core.MediaType) Type(java.lang.reflect.Type) ExceptionMapper(javax.ws.rs.ext.ExceptionMapper) MediaType(javax.ws.rs.core.MediaType) ContextResolver(javax.ws.rs.ext.ContextResolver) MessageBodyWriter(javax.ws.rs.ext.MessageBodyWriter) SAXParserFactory(javax.xml.parsers.SAXParserFactory) Test(org.junit.Test)

Example 40 with MediaType

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

the class MultiPartWriter method writeTo.

/**
     * Write the entire list of body parts to the output stream, using the
     * appropriate provider implementation to serialize each body part's entity.
     *
     * @param entity      the {@link MultiPart} instance to write.
     * @param type        the class of the object to be written (i.e. {@link MultiPart}.class).
     * @param genericType the type of object to be written.
     * @param annotations annotations on the resource method that returned this object.
     * @param mediaType   media type ({@code multipart/*}) of this entity.
     * @param headers     mutable map of HTTP headers for the entire response.
     * @param stream      output stream to which the entity should be written.
     * @throws java.io.IOException if an I/O error occurs.
     * @throws javax.ws.rs.WebApplicationException
     *                             if an HTTP error response
     *                             needs to be produced (only effective if the response is not committed yet).
     */
@Override
public void writeTo(final MultiPart entity, final Class<?> type, final Type genericType, final Annotation[] annotations, final MediaType mediaType, final MultivaluedMap<String, Object> headers, final OutputStream stream) throws IOException, WebApplicationException {
    // Verify that there is at least one body part.
    if ((entity.getBodyParts() == null) || (entity.getBodyParts().size() < 1)) {
        throw new IllegalArgumentException(LocalizationMessages.MUST_SPECIFY_BODY_PART());
    }
    // If our entity is not nested, make sure the MIME-Version header is set.
    if (entity.getParent() == null) {
        final Object value = headers.getFirst("MIME-Version");
        if (value == null) {
            headers.putSingle("MIME-Version", "1.0");
        }
    }
    // Initialize local variables we need.
    final Writer writer = new BufferedWriter(new OutputStreamWriter(stream, MessageUtils.getCharset(mediaType)));
    // Determine the boundary string to be used, creating one if needed.
    final MediaType boundaryMediaType = Boundary.addBoundary(mediaType);
    if (boundaryMediaType != mediaType) {
        headers.putSingle(HttpHeaders.CONTENT_TYPE, boundaryMediaType.toString());
    }
    final String boundaryString = boundaryMediaType.getParameters().get("boundary");
    // Iterate through the body parts for this message.
    boolean isFirst = true;
    for (final BodyPart bodyPart : entity.getBodyParts()) {
        // Write the leading boundary string
        if (isFirst) {
            isFirst = false;
            writer.write("--");
        } else {
            writer.write("\r\n--");
        }
        writer.write(boundaryString);
        writer.write("\r\n");
        // Write the headers for this body part
        final MediaType bodyMediaType = bodyPart.getMediaType();
        if (bodyMediaType == null) {
            throw new IllegalArgumentException(LocalizationMessages.MISSING_MEDIA_TYPE_OF_BODY_PART());
        }
        final MultivaluedMap<String, String> bodyHeaders = bodyPart.getHeaders();
        bodyHeaders.putSingle("Content-Type", bodyMediaType.toString());
        if (bodyHeaders.getFirst("Content-Disposition") == null && bodyPart.getContentDisposition() != null) {
            bodyHeaders.putSingle("Content-Disposition", bodyPart.getContentDisposition().toString());
        }
        // Iterate for the nested body parts
        for (final Map.Entry<String, List<String>> entry : bodyHeaders.entrySet()) {
            // Write this header and its value(s)
            writer.write(entry.getKey());
            writer.write(':');
            boolean first = true;
            for (final String value : entry.getValue()) {
                if (first) {
                    writer.write(' ');
                    first = false;
                } else {
                    writer.write(',');
                }
                writer.write(value);
            }
            writer.write("\r\n");
        }
        // Mark the end of the headers for this body part
        writer.write("\r\n");
        writer.flush();
        // Write the entity for this body part
        Object bodyEntity = bodyPart.getEntity();
        if (bodyEntity == null) {
            throw new IllegalArgumentException(LocalizationMessages.MISSING_ENTITY_OF_BODY_PART(bodyMediaType));
        }
        Class bodyClass = bodyEntity.getClass();
        if (bodyEntity instanceof BodyPartEntity) {
            bodyClass = InputStream.class;
            bodyEntity = ((BodyPartEntity) bodyEntity).getInputStream();
        }
        final MessageBodyWriter bodyWriter = providers.getMessageBodyWriter(bodyClass, bodyClass, EMPTY_ANNOTATIONS, bodyMediaType);
        if (bodyWriter == null) {
            throw new IllegalArgumentException(LocalizationMessages.NO_AVAILABLE_MBW(bodyClass, mediaType));
        }
        bodyWriter.writeTo(bodyEntity, bodyClass, bodyClass, EMPTY_ANNOTATIONS, bodyMediaType, bodyHeaders, stream);
    }
    // Write the final boundary string
    writer.write("\r\n--");
    writer.write(boundaryString);
    writer.write("--\r\n");
    writer.flush();
}
Also used : BodyPart(org.glassfish.jersey.media.multipart.BodyPart) BufferedWriter(java.io.BufferedWriter) BodyPartEntity(org.glassfish.jersey.media.multipart.BodyPartEntity) MediaType(javax.ws.rs.core.MediaType) OutputStreamWriter(java.io.OutputStreamWriter) List(java.util.List) MessageBodyWriter(javax.ws.rs.ext.MessageBodyWriter) Map(java.util.Map) MultivaluedMap(javax.ws.rs.core.MultivaluedMap) MessageBodyWriter(javax.ws.rs.ext.MessageBodyWriter) OutputStreamWriter(java.io.OutputStreamWriter) BufferedWriter(java.io.BufferedWriter) Writer(java.io.Writer)

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