Example usage for org.springframework.http.client ClientHttpRequest getURI

List of usage examples for org.springframework.http.client ClientHttpRequest getURI

Introduction

In this page you can find the example usage for org.springframework.http.client ClientHttpRequest getURI.

Prototype

URI getURI();

Source Link

Document

Return the URI of the request (including a query string if any, but only if it is well-formed for a URI representation).

Usage

From source file:com.goldengekko.meetr.service.sugarcrm.SugarCRMClient.java

public String getToken(String user, String password) {
    LOG.debug("Get SugarCRM token");

    if (null == user || null == password || user.isEmpty() || password.isEmpty()) {
        LOG.info("User and password must be provided when creating token");
        throw new BadRequestException(ERR_MISSING_USER_PASSWORD,
                "User and password must be provided when creating token");
    }/*from w  w w  . j a v  a2s.  com*/

    String data = String.format(
            "{\"user_auth\":{\"user_name\":\"%s\",\"password\":\"%s\",\"version\":\"%s\"},\"application_name\":\"%s\"}",
            this.user, md5Hash(this.password), "1.0", "Meeter");
    //LOG.debug("Send login with data:{}", data);

    this.token = TEMPLATE.execute(this.sugarCRMUrl + PARAM_TEMPLATE, HttpMethod.GET, new RequestCallback() {
        @Override
        public void doWithRequest(ClientHttpRequest clientHttpRequest) throws IOException {
            LOG.debug("Sending login request with url:{}", clientHttpRequest.getURI().toURL().toExternalForm());
        }
    }, new ResponseExtractor<String>() {
        @Override
        public String extractData(ClientHttpResponse clientHttpResponse) throws IOException {
            LOG.debug("Response with http code:{}", clientHttpResponse.getStatusCode().value());

            if (clientHttpResponse.getStatusCode() == HttpStatus.OK) {
                SugarCRMLoginResponse response = MAPPER.readValue(clientHttpResponse.getBody(),
                        SugarCRMLoginResponse.class);
                LOG.debug("Response:{}", response);
                if (!response.hasError()) {
                    return response.getId();
                } else if (response.isInvalidCredentials()) {
                    LOG.info("SugarCRM login failed with invalid credentials",
                            new StringHttpMessageConverter().read(String.class, clientHttpResponse));
                    throw new RestException(ERR_SUGAR_LOGIN_FAILED, HttpStatus.FORBIDDEN,
                            "SugarCRM login failed with invalid credentials");
                } else {
                    LOG.info("SugarCRM login failed with unknown reason:{}",
                            new StringHttpMessageConverter().read(String.class, clientHttpResponse));
                    throw new RestException(ERR_SUGAR_LOGIN_FAILED, HttpStatus.FORBIDDEN,
                            "SugarCRM login failed with unknown reason");
                }
            } else {
                // If the SugarCRM does not respond with 200 throw http 503
                LOG.warn("SugarCRM is responding with http code:{}",
                        clientHttpResponse.getStatusCode().value());
                throw new RestException(ERR_SUGAR_NOT_AVAILABLE, HttpStatus.SERVICE_UNAVAILABLE,
                        "SugarCRM request failed");
            }
        }
    }, "login", "json", "json", data);

    LOG.debug("Got token:{}", this.token);

    return this.token;
}

From source file:com.goldengekko.meetr.service.sugarcrm.SugarCRMClient.java

@Override
public CursorPage<DmContact> getPage(int pageSize, String cursorKey) {
    LOG.debug("SugarCRM client, get contacts. Token:{}", token);

    // Check that we have a token
    if (null == this.token || null == token) {
        throw new RestException(ERR_SUGAR_INVALID_TOKEN, HttpStatus.FORBIDDEN,
                "Token missing, app must generate token first");
    }/*from  w  ww. j a v  a  2s.  c o  m*/

    // If the cursor is null start from the beginning
    if (null == cursorKey) {
        cursorKey = "0";
    }

    // The request
    // {"session":"f9psqc1rgd2iuri76u3v17aul1","module_name":"Contacts","query":"","order_by":"","offset":1,"select_fields":["id","name"],"link_name_to_fields_array":[],"max_results":2,"deleted":0,"Favorites":0}
    String data = String.format(
            "{\"session\":\"%s\",\"module_name\":\"Contacts\",\"query\":\"\",\"order_by\":\"\",\"offset\":%s,\"select_fields\":[\"id\",\"first_name\",\"last_name\",\"email\",\"phone_work\",\"primary_address_street\",\"primary_address_city\",\"primary_address_country\",\"primary_address_postalcode\"],\"link_name_to_fields_array\":[],\"max_results\":%s,\"deleted\":0,\"Favorites\":0}",
            this.token, cursorKey.toString(), pageSize);
    LOG.debug("get contacts with data:{}", data);

    SugarCRMContactsResponse contacts = TEMPLATE.execute(this.sugarCRMUrl + PARAM_TEMPLATE, HttpMethod.GET,
            new RequestCallback() {
                @Override
                public void doWithRequest(ClientHttpRequest clientHttpRequest) throws IOException {
                    LOG.debug("Sending get contact request with url:{}",
                            clientHttpRequest.getURI().toURL().toExternalForm());
                }
            }, new ResponseExtractor<SugarCRMContactsResponse>() {
                @Override
                public SugarCRMContactsResponse extractData(ClientHttpResponse clientHttpResponse)
                        throws IOException {
                    LOG.debug("Response with http code:{}", clientHttpResponse.getStatusCode().value());

                    if (clientHttpResponse.getStatusCode() == HttpStatus.OK) {
                        SugarCRMContactsResponse response = MAPPER.readValue(clientHttpResponse.getBody(),
                                SugarCRMContactsResponse.class);
                        LOG.debug("Response:{}", response);
                        if (!response.hasError()) {
                            return response;
                        } else if (response.isTokenInvalid()) {
                            LOG.info("Get contacts failed, invalid token");
                            throw new RestException(ERR_SUGAR_INVALID_TOKEN, HttpStatus.FORBIDDEN,
                                    "SugarCRM get contacts failed, invalid token");
                        } else {
                            LOG.info("SugarCRM get contacts failed with unknown reason:{}",
                                    new StringHttpMessageConverter().read(String.class, clientHttpResponse));
                            throw new RestException(ERR_SUGAR_GET_CONTACTS_FAILED,
                                    HttpStatus.SERVICE_UNAVAILABLE,
                                    "SugarCRM get contacts failed with unknown reason");
                        }
                    } else {
                        // If the SugarCRM does not respond with 200 throw http 503
                        LOG.warn("SugarCRM is responding with http code:{}",
                                clientHttpResponse.getStatusCode().value());
                        throw new RestException(ERR_SUGAR_NOT_AVAILABLE, HttpStatus.SERVICE_UNAVAILABLE,
                                "SugarCRM request failed");
                    }
                }
            }, "get_entry_list", "json", "json", data);

    LOG.debug("Got number of contacts:{}", contacts.getResult_count());

    CursorPage<DmContact> page = convertToPage(contacts, pageSize);
    return page;
}

From source file:com.alexshabanov.springrestapi.restapitest.RestOperationsTestClient.java

private MockHttpServletRequest toMockHttpServletRequest(URI url, HttpMethod method,
        ClientHttpRequest clientHttpRequest) throws IOException {
    final MockHttpServletRequest mockHttpServletRequest = new MockHttpServletRequest(method.name(),
            url.getPath());//from  w w w.j a va2 s  .  com

    // copy headers
    final HttpHeaders headers = clientHttpRequest.getHeaders();
    for (final String headerKey : headers.toSingleValueMap().keySet()) {
        final List<String> headerValues = headers.get(headerKey);
        for (final String headerValue : headerValues) {
            mockHttpServletRequest.addHeader(headerKey, headerValue);
        }
    }

    // copy query parameters
    final String query = clientHttpRequest.getURI().getQuery();
    if (query != null) {
        mockHttpServletRequest.setQueryString(query);
        final String[] queryParameters = query.split("&");
        for (String keyValueParam : queryParameters) {
            final String[] components = keyValueParam.split("=");
            if (components.length == 1) {
                continue; // optional parameter
            }

            Assert.isTrue(components.length == 2,
                    "Can't split query parameters " + keyValueParam + " by key-value pair");
            mockHttpServletRequest.setParameter(components[0], components[1]);
        }
    }

    // copy request body
    // TODO: another byte copying approach here
    // TODO: for now we rely to the fact that request body is always presented as byte array output stream
    final OutputStream requestBodyStream = clientHttpRequest.getBody();
    if (requestBodyStream instanceof ByteArrayOutputStream) {
        mockHttpServletRequest.setContent(((ByteArrayOutputStream) requestBodyStream).toByteArray());
    } else {
        throw new AssertionError("Ooops, client http request has non-ByteArrayOutputStream body");
    }

    return mockHttpServletRequest;
}

From source file:org.encuestame.oauth1.support.OAuth1Utils.java

/**
 *
 * @param request//from w  w w.jav a  2s  .c  o m
 * @param body
 * @param consumerKey
 * @param consumerSecret
 * @param accessToken
 * @param accessTokenSecret
 * @return
 */
public static String spring30buildAuthorizationHeaderValue(ClientHttpRequest request, byte[] body,
        String consumerKey, String consumerSecret, String accessToken, String accessTokenSecret) {
    Map<String, String> oauthParameters = commonOAuthParameters(consumerKey);
    oauthParameters.put("oauth_token", accessToken);
    Map<String, String> aditionalParameters = extractBodyParameters(request.getHeaders().getContentType(),
            body);
    Map<String, String> queryParameters = extractParameters(request.getURI().getQuery());
    aditionalParameters.putAll(queryParameters);
    String baseRequestUrl = getBaseUrlWithoutPortOrQueryString(request.getURI());
    return OAuth1Utils.buildAuthorizationHeaderValue(baseRequestUrl, oauthParameters, aditionalParameters,
            request.getMethod(), consumerSecret, accessTokenSecret);
}

From source file:org.springframework.social.oauth1.SigningSupport.java

/**
 * Builds an authorization header from a request.
 * Expects that the request's query parameters are form-encoded.
 * This method is a Spring 3.0-compatible version of buildAuthorizationHeaderValue(); planned for removal in Spring Social 1.1
 *///from  ww w .j  a va  2s .  c o m
public String spring30buildAuthorizationHeaderValue(ClientHttpRequest request, byte[] body, String consumerKey,
        String consumerSecret, String accessToken, String accessTokenSecret) {
    Map<String, String> oauthParameters = commonOAuthParameters(consumerKey);
    oauthParameters.put("oauth_token", accessToken);
    MultiValueMap<String, String> additionalParameters = union(
            readFormParameters(request.getHeaders().getContentType(), body),
            parseFormParameters(request.getURI().getRawQuery()));
    return buildAuthorizationHeaderValue(request.getMethod(), request.getURI(), oauthParameters,
            additionalParameters, consumerSecret, accessTokenSecret);
}

From source file:org.springframework.social.oauth1.SigningUtils.java

public static String spring30buildAuthorizationHeaderValue(ClientHttpRequest request, byte[] body,
        String consumerKey, String consumerSecret, String accessToken, String accessTokenSecret) {
    Map<String, String> oauthParameters = commonOAuthParameters(consumerKey);
    oauthParameters.put("oauth_token", accessToken);
    Map<String, String> aditionalParameters = extractBodyParameters(request.getHeaders().getContentType(),
            body);/*w ww.ja  va 2s .  co m*/
    Map<String, String> queryParameters = extractParameters(request.getURI().getQuery());
    aditionalParameters.putAll(queryParameters);
    String baseRequestUrl = getBaseUrlWithoutPortOrQueryString(request.getURI());
    return SigningUtils.buildAuthorizationHeaderValue(baseRequestUrl, oauthParameters, aditionalParameters,
            request.getMethod(), consumerSecret, accessTokenSecret);
}

From source file:software.coolstuff.springframework.owncloud.service.impl.rest.AbstractPipedStreamRestSynchronizerImpl.java

private void wrapRequestCallback(ClientHttpRequest clientHttpRequest, RequestCallback requestCallback)
        throws IOException {
    log.debug("Execute {} on {}", clientHttpRequest.getMethod(), clientHttpRequest.getURI());
    OwncloudRestUtils.addAuthorizationHeader(clientHttpRequest.getHeaders(), getAuthentication());
    addKeepAliveConnectionHeader(clientHttpRequest);
    if (requestCallback != null) {
        requestCallback.doWithRequest(clientHttpRequest);
    }/* ww  w.  j  av a  2s.c  o  m*/
}