Search in sources :

Example 6 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)

Example 7 with MultivaluedMap

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

the class EntityTypesTest method testFormMultivaluedMapRepresentation.

@Test
public void testFormMultivaluedMapRepresentation() {
    final MultivaluedMap<String, String> fp = new MultivaluedStringMap();
    fp.add("Email", "johndoe@gmail.com");
    fp.add("Passwd", "north 23AZ");
    fp.add("service", "cl");
    fp.add("source", "Gulp-CalGul-1.05");
    fp.add("source", "foo.java");
    fp.add("source", "bar.java");
    final WebTarget target = target("FormMultivaluedMapResource");
    final MultivaluedMap _fp = target.request().post(Entity.entity(fp, "application/x-www-form-urlencoded"), MultivaluedMap.class);
    assertEquals(fp, _fp);
}
Also used : MultivaluedStringMap(org.glassfish.jersey.internal.util.collection.MultivaluedStringMap) WebTarget(javax.ws.rs.client.WebTarget) MultivaluedMap(javax.ws.rs.core.MultivaluedMap) Test(org.junit.Test)

Example 8 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 9 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 10 with MultivaluedMap

use of javax.ws.rs.core.MultivaluedMap in project midpoint by Evolveum.

the class MidpointAbstractProvider method readFrom.

@Override
public T readFrom(Class<T> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException, WebApplicationException {
    if (entityStream == null) {
        return null;
    }
    PrismParser parser = getParser(entityStream);
    T object;
    try {
        LOGGER.info("type of request: {}", type);
        if (PrismObject.class.isAssignableFrom(type)) {
            object = (T) parser.parse();
        } else {
            // TODO consider prescribing type here (if no convertor is specified)
            object = parser.parseRealValue();
        }
        if (object != null && !type.isAssignableFrom(object.getClass())) {
            // TODO treat multivalues here
            Optional<Annotation> convertorAnnotation = Arrays.stream(annotations).filter(a -> a instanceof Convertor).findFirst();
            if (convertorAnnotation.isPresent()) {
                Class<? extends ConvertorInterface> convertorClass = ((Convertor) convertorAnnotation.get()).value();
                ConvertorInterface convertor;
                try {
                    convertor = convertorClass.newInstance();
                } catch (InstantiationException | IllegalAccessException e) {
                    throw new SystemException("Couldn't instantiate convertor class " + convertorClass, e);
                }
                object = (T) convertor.convert(object);
            }
        }
        return object;
    } catch (SchemaException ex) {
        throw new WebApplicationException(ex);
    }
}
Also used : Arrays(java.util.Arrays) OperationResult(com.evolveum.midpoint.schema.result.OperationResult) Autowired(org.springframework.beans.factory.annotation.Autowired) SchemaException(com.evolveum.midpoint.util.exception.SchemaException) MessageBodyWriter(javax.ws.rs.ext.MessageBodyWriter) Trace(com.evolveum.midpoint.util.logging.Trace) AbstractConfigurableProvider(org.apache.cxf.jaxrs.provider.AbstractConfigurableProvider) OperationResultType(com.evolveum.midpoint.xml.ns._public.common.common_3.OperationResultType) MediaType(javax.ws.rs.core.MediaType) com.evolveum.midpoint.prism(com.evolveum.midpoint.prism) OutputStream(java.io.OutputStream) IOException(java.io.IOException) LoggingUtils(com.evolveum.midpoint.util.logging.LoggingUtils) MultivaluedMap(javax.ws.rs.core.MultivaluedMap) List(java.util.List) Type(java.lang.reflect.Type) SystemException(com.evolveum.midpoint.util.exception.SystemException) Annotation(java.lang.annotation.Annotation) Optional(java.util.Optional) WebApplicationException(javax.ws.rs.WebApplicationException) ClassResourceInfo(org.apache.cxf.jaxrs.model.ClassResourceInfo) QName(javax.xml.namespace.QName) TraceManager(com.evolveum.midpoint.util.logging.TraceManager) InputStream(java.io.InputStream) MessageBodyReader(javax.ws.rs.ext.MessageBodyReader) SchemaException(com.evolveum.midpoint.util.exception.SchemaException) WebApplicationException(javax.ws.rs.WebApplicationException) Annotation(java.lang.annotation.Annotation) SystemException(com.evolveum.midpoint.util.exception.SystemException)

Aggregations

MultivaluedMap (javax.ws.rs.core.MultivaluedMap)29 Map (java.util.Map)11 MultivaluedMapImpl (com.sun.jersey.core.util.MultivaluedMapImpl)8 List (java.util.List)8 IOException (java.io.IOException)6 MediaType (javax.ws.rs.core.MediaType)6 MultivaluedHashMap (javax.ws.rs.core.MultivaluedHashMap)6 OutputStream (java.io.OutputStream)5 HashMap (java.util.HashMap)5 ByteArrayInputStream (java.io.ByteArrayInputStream)4 InputStream (java.io.InputStream)4 WebApplicationException (javax.ws.rs.WebApplicationException)4 OutputStreamWriter (java.io.OutputStreamWriter)3 Type (java.lang.reflect.Type)3 URI (java.net.URI)3 MessageBodyWriter (javax.ws.rs.ext.MessageBodyWriter)3 JSONEntitlement (com.sun.identity.entitlement.JSONEntitlement)2 OAuthServiceException (com.sun.identity.oauth.service.OAuthServiceException)2 UniformInterfaceException (com.sun.jersey.api.client.UniformInterfaceException)2 ByteArrayOutputStream (java.io.ByteArrayOutputStream)2