Example usage for org.springframework.util MultiValueMap add

List of usage examples for org.springframework.util MultiValueMap add

Introduction

In this page you can find the example usage for org.springframework.util MultiValueMap add.

Prototype

void add(K key, @Nullable V value);

Source Link

Document

Add the given single value to the current list of values for the given key.

Usage

From source file:com.gvmax.web.api.WebAppAPI.java

private void ensureExists(String key, MultiValueMap<String, String> form) {
    if (!form.containsKey(key)) {
        form.add(key, "false");
    }//w  w w  .ja va 2  s. c o m
}

From source file:com.esri.geoportal.harvester.rest.TaskController.java

/**
 * Gets task by id./*from ww w.  ja va 2 s .co m*/
 *
 * @param taskId task id
 * @return task info or <code>null</code> if no task found
 */
@RequestMapping(value = "/rest/harvester/tasks/{taskId}/export", method = RequestMethod.GET)
public ResponseEntity<String> export(@PathVariable UUID taskId) {
    try {
        LOG.debug(formatForLog("GET /rest/harvester/tasks/%s", taskId));
        TaskDefinition taskDefinition = engine.getTasksService().readTaskDefinition(taskId);
        if (taskDefinition == null) {
            return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
        }
        MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
        headers.add("Content-disposition", String.format("attachment; filename=\"%s.json\"", taskId));
        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        ResponseEntity<String> responseEntity = new ResponseEntity<>(mapper.writeValueAsString(taskDefinition),
                headers, HttpStatus.OK);
        return responseEntity;
    } catch (DataProcessorException | JsonProcessingException ex) {
        LOG.error(formatForLog("Error getting task: %s", taskId), ex);
        return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

From source file:apiserver.core.connectors.coldfusion.ColdFusionHttpBridge.java

public ResponseEntity invokeFilePost(String cfcPath_, String method_, Map<String, Object> methodArgs_)
        throws ColdFusionException {
    try (CloseableHttpClient httpClient = HttpClients.createDefault()) {

        HttpHost host = new HttpHost(cfHost, cfPort, cfProtocol);
        HttpPost method = new HttpPost(validatePath(cfPath) + cfcPath_);

        MultipartEntityBuilder me = MultipartEntityBuilder.create();
        me.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

        if (methodArgs_ != null) {
            for (String s : methodArgs_.keySet()) {
                Object obj = methodArgs_.get(s);

                if (obj != null) {
                    if (obj instanceof String) {
                        me.addTextBody(s, (String) obj);
                    } else if (obj instanceof Integer) {
                        me.addTextBody(s, ((Integer) obj).toString());
                    } else if (obj instanceof File) {
                        me.addBinaryBody(s, (File) obj);
                    } else if (obj instanceof IDocument) {
                        me.addBinaryBody(s, ((IDocument) obj).getFile());
                        //me.addTextBody( "name", ((IDocument)obj).getFileName() );
                        //me.addTextBody("contentType", ((IDocument) obj).getContentType().contentType );
                    } else if (obj instanceof IDocument[]) {
                        for (int i = 0; i < ((IDocument[]) obj).length; i++) {
                            IDocument iDocument = ((IDocument[]) obj)[i];
                            me.addBinaryBody(s, iDocument.getFile());
                            //me.addTextBody("name", iDocument.getFileName() );
                            //me.addTextBody("contentType", iDocument.getContentType().contentType );
                        }//from  w  w  w.  j a v a2 s. c  om

                    } else if (obj instanceof BufferedImage) {

                        ByteArrayOutputStream baos = new ByteArrayOutputStream();
                        ImageIO.write((BufferedImage) obj, "jpg", baos);

                        String _fileName = (String) methodArgs_.get(ApiServerConstants.FILE_NAME);
                        String _mimeType = ((MimeType) methodArgs_.get(ApiServerConstants.CONTENT_TYPE))
                                .getExtension();
                        ContentType _contentType = ContentType.create(_mimeType);
                        me.addBinaryBody(s, baos.toByteArray(), _contentType, _fileName);
                    } else if (obj instanceof byte[]) {
                        me.addBinaryBody(s, (byte[]) obj);
                    } else if (obj instanceof Map) {
                        ObjectMapper mapper = new ObjectMapper();
                        String _json = mapper.writeValueAsString(obj);

                        me.addTextBody(s, _json);
                    }
                }
            }
        }

        HttpEntity httpEntity = me.build();
        method.setEntity(httpEntity);

        HttpResponse response = httpClient.execute(host, method);//, responseHandler);

        // Examine the response status
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            // Get hold of the response entity
            HttpEntity entity = response.getEntity();

            if (entity != null) {
                InputStream inputStream = entity.getContent();
                //return inputStream;

                byte[] _body = IOUtils.toByteArray(inputStream);

                MultiValueMap _headers = new LinkedMultiValueMap();
                for (Header header : response.getAllHeaders()) {
                    if (header.getName().equalsIgnoreCase("content-length")) {
                        _headers.add(header.getName(), header.getValue());
                    } else if (header.getName().equalsIgnoreCase("content-type")) {
                        _headers.add(header.getName(), header.getValue());

                        // special condition to add zip to the file name.
                        if (header.getValue().indexOf("text/") > -1) {
                            //add nothing extra
                        } else if (header.getValue().indexOf("zip") > -1) {
                            if (methodArgs_.get("file") != null) {
                                String _fileName = ((Document) methodArgs_.get("file")).getFileName();
                                _headers.add("Content-Disposition",
                                        "attachment; filename=\"" + _fileName + ".zip\"");
                            }
                        } else if (methodArgs_.get("file") != null) {
                            String _fileName = ((Document) methodArgs_.get("file")).getFileName();
                            _headers.add("Content-Disposition", "attachment; filename=\"" + _fileName + "\"");
                        }

                    }
                }

                return new ResponseEntity(_body, _headers, org.springframework.http.HttpStatus.OK);
                //Map json = (Map)deSerializeJson(inputStream);
                //return json;
            }
        }

        MultiValueMap _headers = new LinkedMultiValueMap();
        _headers.add("Content-Type", "text/plain");
        return new ResponseEntity(response.getStatusLine().toString(), _headers,
                org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR);
    } catch (Exception ex) {
        ex.printStackTrace();
        throw new RuntimeException(ex);
    }
}

From source file:jails.http.converter.FormHttpMessageConverter.java

public MultiValueMap<String, String> read(Class<? extends MultiValueMap<String, ?>> clazz,
        HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException {

    MediaType contentType = inputMessage.getHeaders().getContentType();
    Charset charset = contentType.getCharSet() != null ? contentType.getCharSet() : this.charset;
    String body = FileCopyUtils.copyToString(new InputStreamReader(inputMessage.getBody(), charset));

    String[] pairs = StringUtils.tokenizeToStringArray(body, "&");

    MultiValueMap<String, String> result = new LinkedMultiValueMap<String, String>(pairs.length);

    for (String pair : pairs) {
        int idx = pair.indexOf('=');
        if (idx == -1) {
            result.add(URLDecoder.decode(pair, charset.name()), null);
        } else {// ww w.j a v a2  s  .  co  m
            String name = URLDecoder.decode(pair.substring(0, idx), charset.name());
            String value = URLDecoder.decode(pair.substring(idx + 1), charset.name());
            result.add(name, value);
        }
    }
    return result;
}

From source file:org.openmhealth.shim.withings.WithingsShim.java

URI createWithingsRequestUri(ShimDataRequest shimDataRequest, String userid,
        WithingsDataType withingsDataType) {

    MultiValueMap<String, String> dateTimeMap = new LinkedMultiValueMap<>();
    if (withingsDataType.usesUnixEpochSecondsDate || isPartnerAccessActivityMeasure(withingsDataType)) {
        //the partner access endpoints for activity also use epoch secs

        dateTimeMap.add("startdate", String.valueOf(shimDataRequest.getStartDateTime().toEpochSecond()));
        dateTimeMap.add("enddate",
                String.valueOf(shimDataRequest.getEndDateTime().plusDays(1).toEpochSecond()));
    } else {/*from w  w w  . ja va 2  s.  c  o m*/
        dateTimeMap.add("startdateymd", shimDataRequest.getStartDateTime().toLocalDate().toString());
        dateTimeMap.add("enddateymd", shimDataRequest.getEndDateTime().toLocalDate().toString());

    }

    UriComponentsBuilder uriComponentsBuilder = UriComponentsBuilder.fromUriString(DATA_URL)
            .pathSegment(withingsDataType.getEndpoint());
    String measureParameter;
    if (isPartnerAccessActivityMeasure(withingsDataType)) {
        // partner level access allows greater detail around activity, but uses a different endpoint
        measureParameter = PARTNER_ACCESS_ACTIVITY_ENDPOINT;
    } else {
        measureParameter = withingsDataType.getMeasureParameter();
    }
    uriComponentsBuilder.queryParam("action", measureParameter).queryParam("userid", userid)
            .queryParams(dateTimeMap);

    // if it's a body measure
    if (Objects.equals(withingsDataType.getMeasureParameter(), "getmeas")) {

        /*
        The Withings API allows us to query for single body measures, which we take advantage of to reduce
        unnecessary data transfer. However, since blood pressure is represented as two separate measures,
        namely a diastolic and a systolic measure, when the measure type is blood pressure we ask for all
        measures and then filter out the ones we don't care about.
         */
        if (withingsDataType != WithingsDataType.BLOOD_PRESSURE) {

            WithingsBodyMeasureType measureType = WithingsBodyMeasureType.valueOf(withingsDataType.name());
            uriComponentsBuilder.queryParam("meastype", measureType.getMagicNumber());
        }

        uriComponentsBuilder.queryParam("category", 1); //filter out goal datapoints

    }

    UriComponents uriComponents = uriComponentsBuilder.build();
    return uriComponents.toUri();

}

From source file:ch.rasc.wampspring.config.WebMvcWampWebSocketEndpointRegistration.java

public final MultiValueMap<HttpRequestHandler, String> getMappings() {
    MultiValueMap<HttpRequestHandler, String> mappings = new LinkedMultiValueMap<>();
    if (this.registration != null) {
        SockJsService sockJsService = this.registration.getSockJsService();
        for (String path : this.paths) {
            String pattern = path.endsWith("/") ? path + "**" : path + "/**";
            SockJsHttpRequestHandler handler = new SockJsHttpRequestHandler(sockJsService,
                    this.webSocketHandler);
            mappings.add(handler, pattern);
        }//from ww  w  .  j av  a  2  s . c o  m
    } else {
        for (String path : this.paths) {
            WebSocketHttpRequestHandler handler;
            if (this.handshakeHandler != null) {
                handler = new WebSocketHttpRequestHandler(this.webSocketHandler, this.handshakeHandler);
            } else {
                handler = new WebSocketHttpRequestHandler(this.webSocketHandler);
            }
            HandshakeInterceptor[] handshakeInterceptors = getInterceptors();
            if (handshakeInterceptors.length > 0) {
                handler.setHandshakeInterceptors(Arrays.asList(handshakeInterceptors));
            }
            mappings.add(handler, path);
        }
    }
    return mappings;
}

From source file:com.httpMessageConvert.FormHttpMessageConverter.java

public Object read(Class<? extends Object> clazz, HttpInputMessage inputMessage)
        throws IOException, HttpMessageNotReadableException {

    MediaType contentType = inputMessage.getHeaders().getContentType();
    Charset charset = contentType.getCharSet() != null ? contentType.getCharSet() : this.charset;
    String body = StreamUtils.copyToString(inputMessage.getBody(), charset);

    String[] pairs = StringUtils.tokenizeToStringArray(body, "&");

    MultiValueMap<String, String> result = new LinkedMultiValueMap<String, String>(pairs.length);

    for (String pair : pairs) {
        int idx = pair.indexOf('=');
        if (idx == -1) {
            result.add(URLDecoder.decode(pair, charset.name()), null);
        } else {/*  w ww . j av a 2  s  . c  o  m*/
            String name = URLDecoder.decode(pair.substring(0, idx), charset.name());
            String value = URLDecoder.decode(pair.substring(idx + 1), charset.name());
            result.add(name, value);
        }
    }

    Map<String, String> map = result.toSingleValueMap();
    String json = JSONObject.toJSONString(map);
    JavaType javaType = getJavaType(clazz, null);
    ObjectMapper objectMapper = new ObjectMapper();
    return objectMapper.readValue(json, javaType);
}

From source file:com.ge.predix.integration.test.PrivilegeManagementAccessControlServiceIT.java

public void testCreateSubjectWithMalformedJSON() {
    try {//  w w w  . j a  v  a  2  s.co m
        String badSubject = "{\"subject\": bad-subject-form\"}";
        MultiValueMap<String, String> headers = new HttpHeaders();
        headers.add("Content-type", "application/json");
        headers.add(PolicyHelper.PREDIX_ZONE_ID, this.acsZone1Name);
        HttpEntity<String> httpEntity = new HttpEntity<String>(badSubject, headers);
        this.acsAdminRestTemplate.put(this.acsUrl + PrivilegeHelper.ACS_SUBJECT_API_PATH + "/bad-subject-form",
                httpEntity);
    } catch (HttpClientErrorException e) {
        Assert.assertEquals(e.getStatusCode(), HttpStatus.BAD_REQUEST);
        return;
    }
    this.acsAdminRestTemplate.exchange(this.acsUrl + PrivilegeHelper.ACS_SUBJECT_API_PATH + "/bad-subject-form",
            HttpMethod.DELETE, new HttpEntity<>(this.zone1Headers), ResponseEntity.class);
    Assert.fail("testCreateSubjectWithMalformedJSON should have failed!");
}

From source file:com.ge.predix.integration.test.PrivilegeManagementAccessControlServiceIT.java

public void testCreateResourceWithMalformedJSON() {
    try {/*from   www . j a  v a2  s . c o m*/
        String badResource = "{\"resource\": bad-resource-form\"}";
        MultiValueMap<String, String> headers = new HttpHeaders();
        headers.add("Content-type", "application/json");
        headers.add(PolicyHelper.PREDIX_ZONE_ID, this.acsZone1Name);
        HttpEntity<String> httpEntity = new HttpEntity<String>(badResource, headers);
        this.acsAdminRestTemplate
                .put(this.acsUrl + PrivilegeHelper.ACS_RESOURCE_API_PATH + "/bad-resource-form", httpEntity);
    } catch (HttpClientErrorException e) {
        Assert.assertEquals(e.getStatusCode(), HttpStatus.BAD_REQUEST);
        return;
    }
    this.acsAdminRestTemplate.exchange(
            this.acsUrl + PrivilegeHelper.ACS_RESOURCE_API_PATH + "/bad-resource-form", HttpMethod.DELETE,
            new HttpEntity<>(this.zone1Headers), ResponseEntity.class);
    Assert.fail("testCreateResourceWithMalformedJSON should have failed!");
}

From source file:com.ge.predix.integration.test.PrivilegeManagementAccessControlServiceIT.java

public void testCreateBatchResourcesWithMalformedJSON() {
    try {/*from  www.j  a  v a 2 s . com*/
        String badResource = "{\"resource\":{\"name\" : \"Site\", \"uriTemplate\" : "
                + "\"/secured-by-value/sites/{site_id}\"},{\"resource\": bad-resource-form\"}";
        MultiValueMap<String, String> headers = new HttpHeaders();
        headers.add("Content-type", "application/json");
        headers.add(PolicyHelper.PREDIX_ZONE_ID, this.acsZone1Name);
        HttpEntity<String> httpEntity = new HttpEntity<String>(badResource, headers);
        this.acsAdminRestTemplate.postForEntity(this.acsUrl + PrivilegeHelper.ACS_RESOURCE_API_PATH, httpEntity,
                BaseResource[].class);
    } catch (HttpClientErrorException e) {
        Assert.assertEquals(e.getStatusCode(), HttpStatus.BAD_REQUEST);
        return;
    }
    this.acsAdminRestTemplate.exchange(
            this.acsUrl + PrivilegeHelper.ACS_RESOURCE_API_PATH + "/bad-resource-form", HttpMethod.DELETE,
            new HttpEntity<>(this.zone1Headers), ResponseEntity.class);
    this.acsAdminRestTemplate.exchange(this.acsUrl + PrivilegeHelper.ACS_RESOURCE_API_PATH + "/Site",
            HttpMethod.DELETE, new HttpEntity<>(this.zone1Headers), ResponseEntity.class);
    Assert.fail("testCreateBatchResourcesWithMalformedJSON should have failed!");
}