Search in sources :

Example 21 with MultiValueMap

use of org.springframework.util.MultiValueMap in project OpenClinica by OpenClinica.

the class RandomizeService method addOrUpdateASite.

private void addOrUpdateASite(String randomiseUrl, StudyBean studyBean, HttpHeaders headers, String timezone) {
    // mehtod : POST
    randomiseUrl = randomiseUrl + "/api/sites";
    RestTemplate rest = new RestTemplate(requestFactory);
    ResponseEntity<String> response = null;
    MultiValueMap<String, String> siteMap = new LinkedMultiValueMap<String, String>();
    siteMap.add("siteIdentifier", studyBean.getOid());
    siteMap.add("name", studyBean.getName());
    siteMap.add("timezone", timezone);
    HttpEntity<MultiValueMap<String, String>> siteRequest = new HttpEntity<MultiValueMap<String, String>>(siteMap, headers);
    try {
        response = rest.exchange(randomiseUrl, HttpMethod.POST, siteRequest, String.class);
    } catch (Exception e) {
        logger.error(e.getMessage());
        logger.error(ExceptionUtils.getStackTrace(e));
    }
}
Also used : HttpEntity(org.springframework.http.HttpEntity) LinkedMultiValueMap(org.springframework.util.LinkedMultiValueMap) RestTemplate(org.springframework.web.client.RestTemplate) MultiValueMap(org.springframework.util.MultiValueMap) LinkedMultiValueMap(org.springframework.util.LinkedMultiValueMap) JSONException(org.json.JSONException)

Example 22 with MultiValueMap

use of org.springframework.util.MultiValueMap in project amos-ss17-alexa by c-i-ber.

the class AuthenticationAPI method updateAccessToken.

/**
 * Updates the access token if necessary.
 *
 * @param userId the user id
 */
public static void updateAccessToken(String userId) {
    if (!accessTokenUsers.containsKey(userId)) {
        // (model.db.User) DynamoDbClient.instance.getItem(model.db.User.TABLE_NAME, userId, model.db.User.factory);
        User user = (User) DynamoDbMapper.getInstance().load(User.class, userId);
        accessTokenUsers.put(user.getId(), user);
    }
    model.db.User user = accessTokenUsers.get(userId);
    if (user == null) {
        user = new model.db.User();
        user.setBalanceLimit(0);
        user.setId(userId);
        // Update the user object in the db
        DynamoDbMapper.getInstance().save(user);
    // DynamoDbClient.instance.putItem(model.db.User.TABLE_NAME, user);
    }
    if (shouldRefresh(user)) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
        map.add("username", "anton");
        map.add("password", "anton");
        map.add("grant_type", "password");
        map.add("client_id", "public_auth");
        HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers);
        AuthResponse authResponse = new RestTemplate().exchange(AUTH_URL, HttpMethod.POST, request, AuthResponse.class).getBody();
        log.info("AuthToken: " + authResponse.getAccess_token());
        user.setAccessToken(authResponse.getAccess_token());
        // Add expiry time (seconds) to current time, store this value as a String in the User object
        int expiresInSeconds = Integer.valueOf(authResponse.getExpires_in());
        DateTime expiryDateTime = DateTime.now().withZone(DateTimeZone.UTC).plusSeconds(expiresInSeconds);
        String dtStr = fmt.print(expiryDateTime);
        user.setAccessTokenExpiryTime(dtStr);
        log.info("new expiry time: " + dtStr);
        // Store this token in our HashMap
        accessTokenUsers.put(user.getId(), user);
        // Update the user object in the db
        DynamoDbMapper.getInstance().save(user);
    // DynamoDbClient.instance.putItem(model.db.User.TABLE_NAME, user);
    }
}
Also used : User(model.db.User) LinkedMultiValueMap(org.springframework.util.LinkedMultiValueMap) DateTime(org.joda.time.DateTime) RestTemplate(org.springframework.web.client.RestTemplate) User(model.db.User) MultiValueMap(org.springframework.util.MultiValueMap) LinkedMultiValueMap(org.springframework.util.LinkedMultiValueMap)

Example 23 with MultiValueMap

use of org.springframework.util.MultiValueMap in project h2o-2 by h2oai.

the class h2oService method ParseCSVFile.

public String ParseCSVFile(String key, String framename) throws org.json.JSONException {
    //http://localhost:54321/2/Parse2.query?source_key=nfs://tmp/etsy_images/image_deep_features_csv
    String h2oUrlImportEndPoint = H2O_HOST_URL + H2O_PARSE_URL + key;
    log.debug("@@@ Calling endpoint {}", h2oUrlImportEndPoint);
    MultiValueMap<String, String> parameters = new LinkedMultiValueMap<String, String>();
    /*parser_type:CSV
        separator:44
        header:1
        header_with_hash:0
        single_quotes:0
        header_from_file:
        exclude:
        source_key:nfs://tmp/etsy_images/deep_features_csv
        destination_key:deep_features_csv.hex
        preview:
        delete_on_done:1*/
    parameters.add("parser_type", "CSV");
    parameters.add("separator", "44");
    parameters.add("header", "1");
    parameters.add("singleQuotes", "0");
    parameters.add("source_key", key);
    parameters.add("destination_key", framename);
    parameters.add("delete_on_done", "true");
    RestTemplate restTemplate = new RestTemplate();
    HttpHeaders headers = new HttpHeaders();
    headers.add("Accept", MediaType.APPLICATION_JSON_VALUE);
    HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(parameters, headers);
    ResponseEntity<String> response = restTemplate.exchange(h2oUrlImportEndPoint, HttpMethod.GET, request, String.class);
    String responseBody = response.getBody();
    /*

        {"Request2":0,
        "response_info":{"h2o":"paragsanghavi","node":"/172.16.2.46:54321","time":25,"status":"redirect",
        "redirect_url":"/2/Progress2.json?job_key=%240301ac10022e32d4ffffffff%24_96ec9394a616c1e5d4ff8a63f17b428e&destination_key=image_deep_features_csv.hex"},
        "job_key":"$0301ac10022e32d4ffffffff$_96ec9394a616c1e5d4ff8a63f17b428e",
        "destination_key":"image_deep_features_csv.hex"}
         */
    log.debug("@@@ Response json from h2o {}", responseBody);
    JSONObject jsonobject = new JSONObject(responseBody);
    String job_key = (String) jsonobject.get("job_key");
    log.debug("!!!!!! Job name {}", job_key);
    String destination_key = (String) jsonobject.get("destination_key");
    String job_status = JobStatus(job_key, destination_key);
    if (job_status != null) {
        return destination_key;
    }
    return null;
}
Also used : JSONObject(org.json.JSONObject) LinkedMultiValueMap(org.springframework.util.LinkedMultiValueMap) RestTemplate(org.springframework.web.client.RestTemplate) MultiValueMap(org.springframework.util.MultiValueMap) LinkedMultiValueMap(org.springframework.util.LinkedMultiValueMap)

Example 24 with MultiValueMap

use of org.springframework.util.MultiValueMap in project spring-framework by spring-projects.

the class StompDecoder method decodeMessage.

/**
	 * Decode a single STOMP frame from the given {@code buffer} into a {@link Message}.
	 */
private Message<byte[]> decodeMessage(ByteBuffer byteBuffer, MultiValueMap<String, String> headers) {
    Message<byte[]> decodedMessage = null;
    skipLeadingEol(byteBuffer);
    // Explicit mark/reset access via Buffer base type for compatibility
    // with covariant return type on JDK 9's ByteBuffer...
    Buffer buffer = byteBuffer;
    buffer.mark();
    String command = readCommand(byteBuffer);
    if (command.length() > 0) {
        StompHeaderAccessor headerAccessor = null;
        byte[] payload = null;
        if (byteBuffer.remaining() > 0) {
            StompCommand stompCommand = StompCommand.valueOf(command);
            headerAccessor = StompHeaderAccessor.create(stompCommand);
            initHeaders(headerAccessor);
            readHeaders(byteBuffer, headerAccessor);
            payload = readPayload(byteBuffer, headerAccessor);
        }
        if (payload != null) {
            if (payload.length > 0 && !headerAccessor.getCommand().isBodyAllowed()) {
                throw new StompConversionException(headerAccessor.getCommand() + " shouldn't have a payload: length=" + payload.length + ", headers=" + headers);
            }
            headerAccessor.updateSimpMessageHeadersFromStompHeaders();
            headerAccessor.setLeaveMutable(true);
            decodedMessage = MessageBuilder.createMessage(payload, headerAccessor.getMessageHeaders());
            if (logger.isTraceEnabled()) {
                logger.trace("Decoded " + headerAccessor.getDetailedLogMessage(payload));
            }
        } else {
            if (logger.isTraceEnabled()) {
                logger.trace("Incomplete frame, resetting input buffer...");
            }
            if (headers != null && headerAccessor != null) {
                String name = NativeMessageHeaderAccessor.NATIVE_HEADERS;
                @SuppressWarnings("unchecked") MultiValueMap<String, String> map = (MultiValueMap<String, String>) headerAccessor.getHeader(name);
                if (map != null) {
                    headers.putAll(map);
                }
            }
            buffer.reset();
        }
    } else {
        StompHeaderAccessor headerAccessor = StompHeaderAccessor.createForHeartbeat();
        initHeaders(headerAccessor);
        headerAccessor.setLeaveMutable(true);
        decodedMessage = MessageBuilder.createMessage(HEARTBEAT_PAYLOAD, headerAccessor.getMessageHeaders());
        if (logger.isTraceEnabled()) {
            logger.trace("Decoded " + headerAccessor.getDetailedLogMessage(null));
        }
    }
    return decodedMessage;
}
Also used : ByteBuffer(java.nio.ByteBuffer) Buffer(java.nio.Buffer) MultiValueMap(org.springframework.util.MultiValueMap)

Example 25 with MultiValueMap

use of org.springframework.util.MultiValueMap in project spring-framework by spring-projects.

the class FormHttpMessageWriter method write.

@Override
public Mono<Void> write(Publisher<? extends MultiValueMap<String, String>> inputStream, ResolvableType elementType, MediaType mediaType, ReactiveHttpOutputMessage outputMessage, Map<String, Object> hints) {
    MediaType contentType = outputMessage.getHeaders().getContentType();
    if (contentType == null) {
        contentType = MediaType.APPLICATION_FORM_URLENCODED;
        outputMessage.getHeaders().setContentType(contentType);
    }
    Charset charset = getMediaTypeCharset(contentType);
    return Flux.from(inputStream).single().map(form -> generateForm(form, charset)).then(value -> {
        ByteBuffer byteBuffer = charset.encode(value);
        DataBuffer buffer = outputMessage.bufferFactory().wrap(byteBuffer);
        outputMessage.getHeaders().setContentLength(byteBuffer.remaining());
        return outputMessage.writeWith(Mono.just(buffer));
    });
}
Also used : Iterator(java.util.Iterator) Publisher(org.reactivestreams.Publisher) MediaType(org.springframework.http.MediaType) MultiValueMap(org.springframework.util.MultiValueMap) Mono(reactor.core.publisher.Mono) DataBuffer(org.springframework.core.io.buffer.DataBuffer) ByteBuffer(java.nio.ByteBuffer) StandardCharsets(java.nio.charset.StandardCharsets) ReactiveHttpOutputMessage(org.springframework.http.ReactiveHttpOutputMessage) Flux(reactor.core.publisher.Flux) URLEncoder(java.net.URLEncoder) List(java.util.List) Charset(java.nio.charset.Charset) Map(java.util.Map) ResolvableType(org.springframework.core.ResolvableType) UnsupportedEncodingException(java.io.UnsupportedEncodingException) Collections(java.util.Collections) Assert(org.springframework.util.Assert) MediaType(org.springframework.http.MediaType) Charset(java.nio.charset.Charset) ByteBuffer(java.nio.ByteBuffer) DataBuffer(org.springframework.core.io.buffer.DataBuffer)

Aggregations

MultiValueMap (org.springframework.util.MultiValueMap)48 LinkedMultiValueMap (org.springframework.util.LinkedMultiValueMap)34 Test (org.junit.Test)18 Map (java.util.Map)17 HttpHeaders (org.springframework.http.HttpHeaders)17 List (java.util.List)10 HttpEntity (org.springframework.http.HttpEntity)9 RestTemplate (org.springframework.web.client.RestTemplate)7 URI (java.net.URI)4 LinkedHashMap (java.util.LinkedHashMap)4 DefaultOAuth2AccessToken (org.springframework.security.oauth2.common.DefaultOAuth2AccessToken)4 OAuth2AccessToken (org.springframework.security.oauth2.common.OAuth2AccessToken)4 ArrayList (java.util.ArrayList)3 HashMap (java.util.HashMap)3 ResponseEntity (org.springframework.http.ResponseEntity)3 HttpRequestHandler (org.springframework.web.HttpRequestHandler)3 DefaultHandshakeHandler (org.springframework.web.socket.server.support.DefaultHandshakeHandler)3 HttpSessionHandshakeInterceptor (org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor)3 WebSocketHttpRequestHandler (org.springframework.web.socket.server.support.WebSocketHttpRequestHandler)3 SockJsHttpRequestHandler (org.springframework.web.socket.sockjs.support.SockJsHttpRequestHandler)3