Search in sources :

Example 96 with MultivaluedMap

use of javax.ws.rs.core.MultivaluedMap in project xwiki-platform by xwiki.

the class AbstractFormUrlEncodedAnnotationRequestReader method readFrom.

@Override
public T readFrom(Class<T> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException, WebApplicationException {
    ObjectFactory objectFactory = new ObjectFactory();
    T annotationRequest = getReadObjectInstance(objectFactory);
    Representation representation = new InputRepresentation(entityStream, org.restlet.data.MediaType.APPLICATION_WWW_FORM);
    Form form = new Form(representation);
    /*
         * If the form is empty then it might have happened that some filter has invalidated the entity stream. Try to
         * read data using getParameter()
         */
    if (!form.getNames().isEmpty()) {
        for (String paramName : form.getNames()) {
            for (String paramValue : form.getValuesArray(paramName)) {
                saveField(annotationRequest, paramName, paramValue, objectFactory);
            }
        }
    } else {
        HttpServletRequest httpServletRequest = ServletUtils.getRequest(Request.getCurrent());
        for (Map.Entry<String, String[]> entry : httpServletRequest.getParameterMap().entrySet()) {
            // skip method & media parameters, used by REST to carry its own parameters
            if ("method".equals(entry.getKey()) || "media".equals(entry.getKey())) {
                continue;
            }
            // save all the values of this field, one by one
            String[] paramValues = entry.getValue();
            for (String value : paramValues) {
                saveField(annotationRequest, entry.getKey(), value, objectFactory);
            }
        }
    }
    return annotationRequest;
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) ObjectFactory(org.xwiki.annotation.rest.model.jaxb.ObjectFactory) InputRepresentation(org.restlet.representation.InputRepresentation) Form(org.restlet.data.Form) InputRepresentation(org.restlet.representation.InputRepresentation) Representation(org.restlet.representation.Representation) MultivaluedMap(javax.ws.rs.core.MultivaluedMap) Map(java.util.Map)

Example 97 with MultivaluedMap

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

the class SalesforceCXFTransport method getContent.

@Override
public InputStream getContent() throws IOException {
    javax.ws.rs.core.Response response = client.post(new ByteArrayInputStream(this.payload.toByteArray()));
    successful = true;
    InputStream in = (InputStream) response.getEntity();
    if (response.getStatus() != 200) {
        successful = false;
    }
    if (!successful) {
        return in;
    }
    String encoding = response.getHeaderString("Content-Encoding");
    if (config.getMaxResponseSize() > 0) {
        in = new LimitingInputStream(config.getMaxResponseSize(), in);
    }
    if ("gzip".equals(encoding)) {
        in = new GZIPInputStream(in);
    }
    if (config.hasMessageHandlers() || config.isTraceMessage()) {
        byte[] bytes = FileUtil.toBytes(in);
        in = new ByteArrayInputStream(bytes);
        if (config.hasMessageHandlers()) {
            Iterator<MessageHandler> it = config.getMessagerHandlers();
            while (it.hasNext()) {
                MessageHandler handler = it.next();
                if (handler instanceof MessageHandlerWithHeaders) {
                    ((MessageHandlerWithHeaders) handler).handleResponse(url, bytes, modify(response.getHeaders()));
                } else {
                    handler.handleResponse(url, bytes);
                }
            }
        }
        if (config.isTraceMessage()) {
            MultivaluedMap<String, Object> headers = response.getHeaders();
            for (Map.Entry header : headers.entrySet()) {
                config.getTraceStream().print(header.getKey());
                config.getTraceStream().print("=");
                config.getTraceStream().println(header.getValue());
            }
            new TeeInputStream(config, bytes);
        }
    }
    return in;
}
Also used : Entry(java.util.Map.Entry) MessageHandler(com.sforce.ws.MessageHandler) GZIPInputStream(java.util.zip.GZIPInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) GZIPInputStream(java.util.zip.GZIPInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) MessageHandlerWithHeaders(com.sforce.ws.MessageHandlerWithHeaders) HashMap(java.util.HashMap) Map(java.util.Map) MultivaluedMap(javax.ws.rs.core.MultivaluedMap)

Example 98 with MultivaluedMap

use of javax.ws.rs.core.MultivaluedMap in project ddf by codice.

the class GetRecordsMessageBodyReaderTest method testConfigurationArguments.

@Test
public void testConfigurationArguments() throws Exception {
    CswSourceConfiguration config = new CswSourceConfiguration(encryptionService, permissions);
    config.setMetacardCswMappings(DefaultCswRecordMap.getCswToMetacardAttributeNames());
    config.setOutputSchema(CswConstants.CSW_OUTPUT_SCHEMA);
    config.setCswAxisOrder(CswAxisOrder.LAT_LON);
    config.putMetacardCswMapping(Core.THUMBNAIL, CswConstants.CSW_REFERENCES);
    config.putMetacardCswMapping(Core.RESOURCE_URI, CswConstants.CSW_SOURCE);
    GetRecordsMessageBodyReader reader = new GetRecordsMessageBodyReader(mockProvider, config);
    ArgumentCaptor<UnmarshallingContext> captor = ArgumentCaptor.forClass(UnmarshallingContext.class);
    try (InputStream is = GetRecordsMessageBodyReaderTest.class.getResourceAsStream("/getRecordsResponse.xml")) {
        MultivaluedMap<String, String> httpHeaders = new MultivaluedHashMap<>();
        reader.readFrom(CswRecordCollection.class, null, null, null, httpHeaders, is);
    }
    // Verify the context arguments were set correctly
    verify(mockProvider, times(1)).unmarshal(any(HierarchicalStreamReader.class), captor.capture());
    UnmarshallingContext context = captor.getValue();
    // Assert the properties needed for CswRecordConverter
    assertThat(context.get(CswConstants.CSW_MAPPING), notNullValue());
    Object cswMapping = context.get(CswConstants.CSW_MAPPING);
    assertThat(cswMapping, instanceOf(Map.class));
    assertThat(context.get(Core.RESOURCE_URI), instanceOf(String.class));
    assertThat(context.get(Core.RESOURCE_URI), is(CswConstants.CSW_SOURCE));
    assertThat(context.get(Core.THUMBNAIL), instanceOf(String.class));
    assertThat(context.get(Core.THUMBNAIL), is(CswConstants.CSW_REFERENCES));
    assertThat(context.get(CswConstants.AXIS_ORDER_PROPERTY), instanceOf(CswAxisOrder.class));
    assertThat(context.get(CswConstants.AXIS_ORDER_PROPERTY), is(CswAxisOrder.LAT_LON));
    // Assert the output Schema is set.
    assertThat(context.get(CswConstants.OUTPUT_SCHEMA_PARAMETER), instanceOf(String.class));
    assertThat(context.get(CswConstants.OUTPUT_SCHEMA_PARAMETER), is(CswConstants.CSW_OUTPUT_SCHEMA));
    assertThat(context.get(CswConstants.TRANSFORMER_LOOKUP_KEY), instanceOf(String.class));
    assertThat(context.get(CswConstants.TRANSFORMER_LOOKUP_KEY), is(TransformerManager.SCHEMA));
    assertThat(context.get(CswConstants.TRANSFORMER_LOOKUP_VALUE), instanceOf(String.class));
    assertThat(context.get(CswConstants.TRANSFORMER_LOOKUP_VALUE), is(CswConstants.CSW_OUTPUT_SCHEMA));
}
Also used : CswSourceConfiguration(org.codice.ddf.spatial.ogc.csw.catalog.common.CswSourceConfiguration) MultivaluedHashMap(javax.ws.rs.core.MultivaluedHashMap) CswAxisOrder(org.codice.ddf.spatial.ogc.csw.catalog.common.CswAxisOrder) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) HierarchicalStreamReader(com.thoughtworks.xstream.io.HierarchicalStreamReader) UnmarshallingContext(com.thoughtworks.xstream.converters.UnmarshallingContext) Matchers.containsString(org.hamcrest.Matchers.containsString) Matchers.anyString(org.mockito.Matchers.anyString) Map(java.util.Map) DefaultCswRecordMap(org.codice.ddf.spatial.ogc.csw.catalog.common.converter.DefaultCswRecordMap) HashMap(java.util.HashMap) MultivaluedHashMap(javax.ws.rs.core.MultivaluedHashMap) MultivaluedMap(javax.ws.rs.core.MultivaluedMap) Test(org.junit.Test)

Example 99 with MultivaluedMap

use of javax.ws.rs.core.MultivaluedMap in project ddf by codice.

the class BodyWriter method writeBody.

<T> void writeBody(T o, Message outMessage, Class<?> cls, Type type) {
    if (o == null) {
        return;
    }
    @SuppressWarnings("unchecked") MultivaluedMap<String, Object> headers = (MultivaluedMap<String, Object>) outMessage.get(Message.PROTOCOL_HEADERS);
    @SuppressWarnings("unchecked") Class<T> theClass = (Class<T>) cls;
    MediaType contentType = JAXRSUtils.toMediaType(headers.getFirst("Content-Type").toString());
    List<WriterInterceptor> writers = ClientProviderFactory.getInstance(outMessage).createMessageBodyWriterInterceptor(theClass, type, null, contentType, outMessage, null);
    if (writers != null) {
        try {
            JAXRSUtils.writeMessageBody(writers, o, theClass, type, null, contentType, headers, outMessage);
            OutputStream realOs = outMessage.get(OutputStream.class);
            if (realOs != null) {
                realOs.flush();
            }
        } catch (Exception ex) {
            LOGGER.debug("Unable to write message body for final ECP response.");
        }
    } else {
        LOGGER.debug("No writers available for final ECP response");
    }
}
Also used : WriterInterceptor(javax.ws.rs.ext.WriterInterceptor) OutputStream(java.io.OutputStream) MediaType(javax.ws.rs.core.MediaType) MultivaluedMap(javax.ws.rs.core.MultivaluedMap)

Example 100 with MultivaluedMap

use of javax.ws.rs.core.MultivaluedMap in project tomee by apache.

the class JAXRSUtils method processFormParam.

private static Object processFormParam(Message m, String key, Class<?> pClass, Type genericType, Annotation[] paramAnns, String defaultValue, boolean decode) {
    MessageContext mc = new MessageContextImpl(m);
    MediaType mt = mc.getHttpHeaders().getMediaType();
    @SuppressWarnings("unchecked") MultivaluedMap<String, String> params = (MultivaluedMap<String, String>) m.get(FormUtils.FORM_PARAM_MAP);
    String enc = HttpUtils.getEncoding(mt, StandardCharsets.UTF_8.name());
    if (params == null) {
        params = new MetadataMap<>();
        m.put(FormUtils.FORM_PARAM_MAP, params);
        if (mt == null || mt.isCompatible(MediaType.APPLICATION_FORM_URLENCODED_TYPE)) {
            InputStream entityStream = copyAndGetEntityStream(m);
            String body = FormUtils.readBody(entityStream, enc);
            // Do not decode unless the key is empty value, fe @FormParam("")
            FormUtils.populateMapFromStringOrHttpRequest(params, m, body, enc, StringUtils.isEmpty(key) && decode);
        } else {
            if ("multipart".equalsIgnoreCase(mt.getType()) && MediaType.MULTIPART_FORM_DATA_TYPE.isCompatible(mt)) {
                MultipartBody body = AttachmentUtils.getMultipartBody(mc);
                FormUtils.populateMapFromMultipart(params, body, m, decode);
            } else {
                org.apache.cxf.common.i18n.Message errorMsg = new org.apache.cxf.common.i18n.Message("WRONG_FORM_MEDIA_TYPE", BUNDLE, mt.toString());
                LOG.warning(errorMsg.toString());
                throw ExceptionUtils.toNotSupportedException(null, null);
            }
        }
    }
    if (decode && !MessageUtils.getContextualBoolean(m, FormUtils.FORM_PARAM_MAP_DECODED, false)) {
        List<String> values = params.get(key);
        if (values != null) {
            values = values.stream().map(value -> HttpUtils.urlDecode(value, enc)).collect(Collectors.toList());
            params.replace(key, values);
        }
    }
    if ("".equals(key)) {
        return InjectionUtils.handleBean(pClass, paramAnns, params, ParameterType.FORM, m, false);
    }
    List<String> results = params.get(key);
    return InjectionUtils.createParameterObject(results, pClass, genericType, paramAnns, defaultValue, false, ParameterType.FORM, m);
}
Also used : Message(org.apache.cxf.message.Message) ReaderInputStream(org.apache.cxf.io.ReaderInputStream) InputStream(java.io.InputStream) MultipartBody(org.apache.cxf.jaxrs.ext.multipart.MultipartBody) MediaType(javax.ws.rs.core.MediaType) MessageContext(org.apache.cxf.jaxrs.ext.MessageContext) MultivaluedMap(javax.ws.rs.core.MultivaluedMap) MessageContextImpl(org.apache.cxf.jaxrs.ext.MessageContextImpl)

Aggregations

MultivaluedMap (javax.ws.rs.core.MultivaluedMap)135 Map (java.util.Map)67 List (java.util.List)51 HashMap (java.util.HashMap)45 MediaType (javax.ws.rs.core.MediaType)35 MultivaluedHashMap (javax.ws.rs.core.MultivaluedHashMap)28 MetadataMap (org.apache.cxf.jaxrs.impl.MetadataMap)27 ArrayList (java.util.ArrayList)24 IOException (java.io.IOException)23 Test (org.junit.Test)21 WebApplicationException (javax.ws.rs.WebApplicationException)19 LinkedHashMap (java.util.LinkedHashMap)18 Type (java.lang.reflect.Type)16 Response (javax.ws.rs.core.Response)16 InputStream (java.io.InputStream)14 OutputStream (java.io.OutputStream)14 ByteArrayInputStream (java.io.ByteArrayInputStream)13 ClassResourceInfo (org.apache.cxf.jaxrs.model.ClassResourceInfo)13 Method (java.lang.reflect.Method)11 Optional (java.util.Optional)11