Search in sources :

Example 51 with MultivaluedMap

use of javax.ws.rs.core.MultivaluedMap in project mycore by MyCoRe-Org.

the class MCRPropertiesToJSONTransformer method writeTo.

@Override
public void writeTo(Properties t, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException {
    httpHeaders.putSingle(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_TYPE.withCharset(StandardCharsets.UTF_8.name()));
    final Type mapType = new TypeToken<Map<String, String>>() {

        private static final long serialVersionUID = 1L;
    }.getType();
    Map<String, String> writeMap = t.entrySet().stream().collect(Collectors.toMap(e -> e.getKey().toString(), e -> e.getValue().toString()));
    String json = new GsonBuilder().registerTypeAdapter(mapType, new BundleMapSerializer()).create().toJson(writeMap, mapType);
    entityStream.write(json.getBytes(StandardCharsets.UTF_8));
}
Also used : OutputStream(java.io.OutputStream) JsonObject(com.google.gson.JsonObject) Properties(java.util.Properties) Produces(javax.ws.rs.Produces) Provider(javax.ws.rs.ext.Provider) IOException(java.io.IOException) MessageBodyWriter(javax.ws.rs.ext.MessageBodyWriter) JsonSerializer(com.google.gson.JsonSerializer) TypeToken(com.google.common.reflect.TypeToken) Collectors(java.util.stream.Collectors) StandardCharsets(java.nio.charset.StandardCharsets) GsonBuilder(com.google.gson.GsonBuilder) MultivaluedMap(javax.ws.rs.core.MultivaluedMap) JsonElement(com.google.gson.JsonElement) MediaType(javax.ws.rs.core.MediaType) HttpHeaders(javax.ws.rs.core.HttpHeaders) Logger(org.apache.logging.log4j.Logger) Type(java.lang.reflect.Type) Map(java.util.Map) Annotation(java.lang.annotation.Annotation) WebApplicationException(javax.ws.rs.WebApplicationException) JsonSerializationContext(com.google.gson.JsonSerializationContext) LogManager(org.apache.logging.log4j.LogManager) MediaType(javax.ws.rs.core.MediaType) Type(java.lang.reflect.Type) GsonBuilder(com.google.gson.GsonBuilder) MultivaluedMap(javax.ws.rs.core.MultivaluedMap) Map(java.util.Map)

Example 52 with MultivaluedMap

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

the class AbstractCatalogService method getDocument.

@Override
public BinaryContent getDocument(String encodedSourceId, String encodedId, String transformerParam, URI absolutePath, MultivaluedMap<String, String> queryParameters, HttpServletRequest httpRequest) throws CatalogServiceException, DataUsageLimitExceededException, InternalServerErrorException {
    QueryResponse queryResponse;
    Metacard card = null;
    LOGGER.trace("GET");
    if (encodedId != null) {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Got id: {}", LogSanitizer.sanitize(encodedId));
            LOGGER.debug("Got service: {}", LogSanitizer.sanitize(transformerParam));
            LOGGER.debug("Map of query parameters: \n{}", LogSanitizer.sanitize(queryParameters));
        }
        Map<String, Serializable> convertedMap = convert(queryParameters);
        convertedMap.put("url", absolutePath.toString());
        LOGGER.debug("Map converted, retrieving product.");
        // default to xml if no transformer specified
        try {
            String id = URLDecoder.decode(encodedId, CharEncoding.UTF_8);
            String transformer = DEFAULT_METACARD_TRANSFORMER;
            if (transformerParam != null) {
                transformer = transformerParam;
            }
            Filter filter = getFilterBuilder().attribute(Metacard.ID).is().equalTo().text(id);
            Collection<String> sources = null;
            if (encodedSourceId != null) {
                String sourceid = URLDecoder.decode(encodedSourceId, CharEncoding.UTF_8);
                sources = new ArrayList<>();
                sources.add(sourceid);
            }
            QueryRequestImpl request = new QueryRequestImpl(new QueryImpl(filter), sources);
            request.setProperties(convertedMap);
            queryResponse = catalogFramework.query(request, null);
            // pull the metacard out of the blocking queue
            List<Result> results = queryResponse.getResults();
            // return null if timeout elapsed)
            if (results != null && !results.isEmpty()) {
                card = results.get(0).getMetacard();
            }
            if (card == null) {
                return null;
            }
            // Check for Range header set the value in the map appropriately so that the
            // catalogFramework
            // can take care of the skipping
            long bytesToSkip = getRangeStart(httpRequest);
            if (bytesToSkip > 0) {
                LOGGER.debug("Bytes to skip: {}", bytesToSkip);
                convertedMap.put(BYTES_TO_SKIP, bytesToSkip);
            }
            LOGGER.debug("Calling transform.");
            final BinaryContent content = catalogFramework.transform(card, transformer, convertedMap);
            LOGGER.debug("Read and transform complete, preparing response.");
            return content;
        } catch (FederationException e) {
            String exceptionMessage = "READ failed due to unexpected exception: ";
            LOGGER.info(exceptionMessage, e);
            throw new InternalServerErrorException(exceptionMessage);
        } catch (CatalogTransformerException e) {
            String exceptionMessage = "Unable to transform Metacard.  Try different transformer: ";
            LOGGER.info(exceptionMessage, e);
            throw new InternalServerErrorException(exceptionMessage);
        } catch (SourceUnavailableException e) {
            String exceptionMessage = "Cannot obtain query results because source is unavailable: ";
            LOGGER.info(exceptionMessage, e);
            throw new InternalServerErrorException(exceptionMessage);
        } catch (UnsupportedQueryException e) {
            String errorMessage = "Specified query is unsupported.  Change query and resubmit: ";
            LOGGER.info(errorMessage, e);
            throw new CatalogServiceException(errorMessage);
        } catch (DataUsageLimitExceededException e) {
            String errorMessage = "Unable to process request. Data usage limit exceeded: ";
            LOGGER.debug(errorMessage, e);
            throw new DataUsageLimitExceededException(errorMessage);
        } catch (OAuthPluginException e) {
            Map<String, String> parameters = e.getParameters();
            String url = constructUrl(httpRequest, e.getBaseUrl(), parameters);
            if (url != null) {
                parameters.put(REDIRECT_URI, url);
                throw new OAuthPluginException(e.getSourceId(), url, e.getBaseUrl(), parameters, e.getErrorType());
            }
            throw e;
        // The catalog framework will throw this if any of the transformers blow up.
        // We need to catch this exception here or else execution will return to CXF and
        // we'll lose this message and end up with a huge stack trace in a GUI or whatever
        // else is connected to this endpoint
        } catch (RuntimeException | UnsupportedEncodingException e) {
            String exceptionMessage = "Unknown error occurred while processing request.";
            LOGGER.info(exceptionMessage, e);
            throw new InternalServerErrorException(exceptionMessage);
        }
    } else {
        throw new CatalogServiceException("No ID specified.");
    }
}
Also used : SourceUnavailableException(ddf.catalog.source.SourceUnavailableException) Serializable(java.io.Serializable) UnsupportedQueryException(ddf.catalog.source.UnsupportedQueryException) CatalogTransformerException(ddf.catalog.transform.CatalogTransformerException) BinaryContent(ddf.catalog.data.BinaryContent) Result(ddf.catalog.data.Result) QueryImpl(ddf.catalog.operation.impl.QueryImpl) DataUsageLimitExceededException(ddf.catalog.resource.DataUsageLimitExceededException) CatalogServiceException(org.codice.ddf.rest.api.CatalogServiceException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) FederationException(ddf.catalog.federation.FederationException) Metacard(ddf.catalog.data.Metacard) OAuthPluginException(ddf.catalog.plugin.OAuthPluginException) Filter(org.opengis.filter.Filter) QueryResponse(ddf.catalog.operation.QueryResponse) QueryRequestImpl(ddf.catalog.operation.impl.QueryRequestImpl) InternalServerErrorException(javax.ws.rs.InternalServerErrorException) Map(java.util.Map) HashMap(java.util.HashMap) MultivaluedMap(javax.ws.rs.core.MultivaluedMap)

Example 53 with MultivaluedMap

use of javax.ws.rs.core.MultivaluedMap in project Payara by payara.

the class RestClientBase method buildMultivalueMap.

private MultivaluedMap<String, Object> buildMultivalueMap(Map<String, Object> payload) {
    MultivaluedMap formData = new MultivaluedHashMap();
    for (final Map.Entry<String, Object> entry : payload.entrySet()) {
        Object value = entry.getValue();
        if (JsonObject.NULL.equals(value)) {
            value = null;
        } else if (value != null) {
            value = value.toString();
        }
        formData.add(entry.getKey(), value);
    }
    return formData;
}
Also used : MultivaluedHashMap(javax.ws.rs.core.MultivaluedHashMap) JsonObject(javax.json.JsonObject) MultivaluedMap(javax.ws.rs.core.MultivaluedMap) HashMap(java.util.HashMap) MultivaluedHashMap(javax.ws.rs.core.MultivaluedHashMap) MultivaluedMap(javax.ws.rs.core.MultivaluedMap) Map(java.util.Map)

Example 54 with MultivaluedMap

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

the class JAXRSUtilsTest method testFormParametersAndMap.

@SuppressWarnings("unchecked")
@Test
public void testFormParametersAndMap() throws Exception {
    Class<?>[] argType = { MultivaluedMap.class, String.class, List.class };
    Method m = Customer.class.getMethod("testMultivaluedMapAndFormParam", argType);
    final Message messageImpl = createMessage();
    String body = "p1=1&p2=2&p2=3";
    messageImpl.put(Message.REQUEST_URI, "/foo");
    messageImpl.put("Content-Type", MediaType.APPLICATION_FORM_URLENCODED);
    messageImpl.setContent(InputStream.class, new ByteArrayInputStream(body.getBytes()));
    ProviderFactory.getInstance(messageImpl).registerUserProvider(new FormEncodingProvider<Object>() {

        @Override
        protected void persistParamsOnMessage(MultivaluedMap<String, String> params) {
            messageImpl.put(FormUtils.FORM_PARAM_MAP, params);
        }
    });
    List<Object> params = JAXRSUtils.processParameters(new OperationResourceInfo(m, new ClassResourceInfo(Customer.class)), new MetadataMap<String, String>(), messageImpl);
    assertEquals("3 params should've been identified", 3, params.size());
    MultivaluedMap<String, String> map = (MultivaluedMap<String, String>) params.get(0);
    assertEquals(2, map.size());
    assertEquals(1, map.get("p1").size());
    assertEquals("First map parameter not matched correctly", "1", map.getFirst("p1"));
    assertEquals(2, map.get("p2").size());
    assertEquals("2", map.get("p2").get(0));
    assertEquals("3", map.get("p2").get(1));
    assertEquals("First Form Parameter not matched correctly", "1", params.get(1));
    List<String> list = (List<String>) params.get(2);
    assertEquals(2, list.size());
    assertEquals("2", list.get(0));
    assertEquals("3", list.get(1));
}
Also used : Message(org.apache.cxf.message.Message) ClassResourceInfo(org.apache.cxf.jaxrs.model.ClassResourceInfo) Method(java.lang.reflect.Method) ByteArrayInputStream(java.io.ByteArrayInputStream) OperationResourceInfo(org.apache.cxf.jaxrs.model.OperationResourceInfo) List(java.util.List) ArrayList(java.util.ArrayList) MultivaluedMap(javax.ws.rs.core.MultivaluedMap) Test(org.junit.Test)

Example 55 with MultivaluedMap

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

the class FormEncodingProviderTest method testWriteMultipleValues2.

@Test
public void testWriteMultipleValues2() throws Exception {
    MultivaluedMap<String, String> mvMap = new MetadataMap<>();
    mvMap.add("a", "a1");
    mvMap.add("a", "a2");
    mvMap.add("b", "b1");
    FormEncodingProvider<MultivaluedMap<?, ?>> ferp = new FormEncodingProvider<>();
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    ferp.writeTo(mvMap, MultivaluedMap.class, MultivaluedMap.class, new Annotation[0], MediaType.APPLICATION_FORM_URLENCODED_TYPE, new MetadataMap<String, Object>(), bos);
    String result = bos.toString();
    assertEquals("Wrong value", "a=a1&a=a2&b=b1", result);
}
Also used : MetadataMap(org.apache.cxf.jaxrs.impl.MetadataMap) ByteArrayOutputStream(java.io.ByteArrayOutputStream) MultivaluedMap(javax.ws.rs.core.MultivaluedMap) Test(org.junit.Test)

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