Search in sources :

Example 1 with MultivaluedMap

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

the class FreemarkerViewProcessor method writeTo.

@Override
public void writeTo(final Template template, final Viewable viewable, final MediaType mediaType, final MultivaluedMap<String, Object> httpHeaders, final OutputStream out) throws IOException {
    try {
        Object model = viewable.getModel();
        if (!(model instanceof Map)) {
            model = new HashMap<String, Object>() {

                {
                    put("model", viewable.getModel());
                }
            };
        }
        Charset encoding = setContentType(mediaType, httpHeaders);
        template.process(model, new OutputStreamWriter(out, encoding));
    } catch (TemplateException te) {
        throw new ContainerException(te);
    }
}
Also used : TemplateException(freemarker.template.TemplateException) ContainerException(org.glassfish.jersey.server.ContainerException) Charset(java.nio.charset.Charset) OutputStreamWriter(java.io.OutputStreamWriter) HashMap(java.util.HashMap) MultivaluedMap(javax.ws.rs.core.MultivaluedMap) Map(java.util.Map)

Example 2 with MultivaluedMap

use of javax.ws.rs.core.MultivaluedMap 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)

Example 3 with MultivaluedMap

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

the class FormMultivaluedMapProviderTest method readFrom.

@SuppressWarnings("unchecked")
private static MultivaluedMap<String, String> readFrom(String body) {
    try {
        InputStream stream = new ByteArrayInputStream(body.getBytes(StandardCharsets.UTF_8));
        Class<MultivaluedMap<String, String>> clazz = (Class<MultivaluedMap<String, String>>) (Class<?>) MultivaluedHashMap.class;
        return PROVIDER.readFrom(clazz, clazz, new Annotation[] {}, MediaType.APPLICATION_FORM_URLENCODED_TYPE, null, stream);
    } catch (IOException e) {
        throw new RuntimeException("Unexpected exception", e);
    }
}
Also used : MultivaluedHashMap(javax.ws.rs.core.MultivaluedHashMap) ByteArrayInputStream(java.io.ByteArrayInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) IOException(java.io.IOException) MultivaluedMap(javax.ws.rs.core.MultivaluedMap)

Example 4 with MultivaluedMap

use of javax.ws.rs.core.MultivaluedMap 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 5 with MultivaluedMap

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

the class InMemoryConnector method apply.

/**
     * {@inheritDoc}
     * <p/>
     * Transforms client-side request to server-side and invokes it on provided application ({@link ApplicationHandler}
     * instance).
     *
     * @param clientRequest client side request to be invoked.
     */
@Override
public ClientResponse apply(final ClientRequest clientRequest) {
    PropertiesDelegate propertiesDelegate = new MapPropertiesDelegate();
    final ContainerRequest containerRequest = new ContainerRequest(baseUri, clientRequest.getUri(), clientRequest.getMethod(), null, propertiesDelegate);
    containerRequest.getHeaders().putAll(clientRequest.getStringHeaders());
    final ByteArrayOutputStream clientOutput = new ByteArrayOutputStream();
    if (clientRequest.getEntity() != null) {
        clientRequest.setStreamProvider(new OutboundMessageContext.StreamProvider() {

            @Override
            public OutputStream getOutputStream(int contentLength) throws IOException {
                final MultivaluedMap<String, Object> clientHeaders = clientRequest.getHeaders();
                if (contentLength != -1 && !clientHeaders.containsKey(HttpHeaders.CONTENT_LENGTH)) {
                    containerRequest.getHeaders().putSingle(HttpHeaders.CONTENT_LENGTH, String.valueOf(contentLength));
                }
                return clientOutput;
            }
        });
        clientRequest.enableBuffering();
        try {
            clientRequest.writeEntity();
        } catch (IOException e) {
            final String msg = "Error while writing entity to the output stream.";
            LOGGER.log(Level.SEVERE, msg, e);
            throw new ProcessingException(msg, e);
        }
    }
    containerRequest.setEntityStream(new ByteArrayInputStream(clientOutput.toByteArray()));
    boolean followRedirects = ClientProperties.getValue(clientRequest.getConfiguration().getProperties(), ClientProperties.FOLLOW_REDIRECTS, true);
    final InMemoryResponseWriter inMemoryResponseWriter = new InMemoryResponseWriter();
    containerRequest.setWriter(inMemoryResponseWriter);
    containerRequest.setSecurityContext(new SecurityContext() {

        @Override
        public Principal getUserPrincipal() {
            return null;
        }

        @Override
        public boolean isUserInRole(String role) {
            return false;
        }

        @Override
        public boolean isSecure() {
            return false;
        }

        @Override
        public String getAuthenticationScheme() {
            return null;
        }
    });
    appHandler.handle(containerRequest);
    return tryFollowRedirects(followRedirects, createClientResponse(clientRequest, inMemoryResponseWriter), new ClientRequest(clientRequest));
}
Also used : ByteArrayOutputStream(java.io.ByteArrayOutputStream) OutputStream(java.io.OutputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) OutboundMessageContext(org.glassfish.jersey.message.internal.OutboundMessageContext) MapPropertiesDelegate(org.glassfish.jersey.internal.MapPropertiesDelegate) ByteArrayInputStream(java.io.ByteArrayInputStream) SecurityContext(javax.ws.rs.core.SecurityContext) ContainerRequest(org.glassfish.jersey.server.ContainerRequest) MultivaluedMap(javax.ws.rs.core.MultivaluedMap) MapPropertiesDelegate(org.glassfish.jersey.internal.MapPropertiesDelegate) PropertiesDelegate(org.glassfish.jersey.internal.PropertiesDelegate) Principal(java.security.Principal) ClientRequest(org.glassfish.jersey.client.ClientRequest) ProcessingException(javax.ws.rs.ProcessingException)

Aggregations

MultivaluedMap (javax.ws.rs.core.MultivaluedMap)130 Map (java.util.Map)65 List (java.util.List)46 HashMap (java.util.HashMap)44 MediaType (javax.ws.rs.core.MediaType)33 MultivaluedHashMap (javax.ws.rs.core.MultivaluedHashMap)27 MetadataMap (org.apache.cxf.jaxrs.impl.MetadataMap)27 IOException (java.io.IOException)22 ArrayList (java.util.ArrayList)22 Test (org.junit.Test)21 WebApplicationException (javax.ws.rs.WebApplicationException)19 LinkedHashMap (java.util.LinkedHashMap)18 Type (java.lang.reflect.Type)16 InputStream (java.io.InputStream)14 OutputStream (java.io.OutputStream)14 Response (javax.ws.rs.core.Response)14 ByteArrayInputStream (java.io.ByteArrayInputStream)13 ClassResourceInfo (org.apache.cxf.jaxrs.model.ClassResourceInfo)13 Message (org.apache.cxf.message.Message)13 Optional (java.util.Optional)10