Example usage for org.springframework.web.client RequestCallback RequestCallback

List of usage examples for org.springframework.web.client RequestCallback RequestCallback

Introduction

In this page you can find the example usage for org.springframework.web.client RequestCallback RequestCallback.

Prototype

RequestCallback

Source Link

Usage

From source file:com.mycompany.trader.TradingConnect.java

private static void loginAndSaveJsessionIdCookie(final String user, final String password,
        final HttpHeaders headersToUpdate) {

    String url = "http://localhost:" + port + "/blueprint-trading-services/login.html";

    new RestTemplate().execute(url, HttpMethod.POST, new RequestCallback() {
        @Override/*  w  w  w  .  j a v  a 2 s. c o m*/
        public void doWithRequest(ClientHttpRequest request) throws IOException {
            MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
            map.add("username", user);
            map.add("password", password);
            new FormHttpMessageConverter().write(map, MediaType.APPLICATION_FORM_URLENCODED, request);
        }
    }, new ResponseExtractor<Object>() {
        @Override
        public Object extractData(ClientHttpResponse response) throws IOException {
            headersToUpdate.add("Cookie", response.getHeaders().getFirst("Set-Cookie"));
            return null;
        }
    });
}

From source file:de.hybris.platform.marketplaceintegrationbackoffice.utils.MarketplaceintegrationbackofficeHttpClientImpl.java

@Override
public boolean redirectRequest(final String requestUrl) throws IOException {

    final boolean result = true;
    final RestTemplate restTemplate = new RestTemplate();

    final java.net.URI uri = java.net.URI.create(requestUrl);
    final java.awt.Desktop dp = java.awt.Desktop.getDesktop();
    if (dp.isSupported(java.awt.Desktop.Action.BROWSE)) {
        dp.browse(uri);/*  w  w w  . java  2  s. co m*/
    }
    restTemplate.execute(requestUrl, HttpMethod.GET, new RequestCallback() {
        @Override
        public void doWithRequest(final ClientHttpRequest request) throws IOException {
            // empty block should be documented
        }
    }, new ResponseExtractor<Object>() {
        @Override
        public Object extractData(final ClientHttpResponse response) throws IOException {
            final HttpStatus statusCode = response.getStatusCode();
            LOG.debug("Response status: " + statusCode.toString());
            return response.getStatusCode();
        }
    });
    return result;
}

From source file:com.appglu.impl.StorageTemplate.java

/**
 * {@inheritDoc}/*from w ww .jav a  2 s  . c o m*/
 */
public void streamStorageFile(StorageFile file, InputStreamCallback inputStreamCallback)
        throws AppGluRestClientException {

    RequestCallback requestCallback = new RequestCallback() {
        public void doWithRequest(ClientHttpRequest request) throws IOException {

        }
    };

    this.streamStorageFile(file, inputStreamCallback, requestCallback);
}

From source file:com.appglu.impl.StorageTemplate.java

/**
 * {@inheritDoc}/* w  w  w .  j  a  v a  2 s .c om*/
 */
public boolean streamStorageFileIfModifiedSince(final StorageFile file, InputStreamCallback inputStreamCallback)
        throws AppGluRestClientException {

    RequestCallback requestCallback = new RequestCallback() {
        public void doWithRequest(ClientHttpRequest request) throws IOException {
            if (file.hasLastModifiedDate()) {
                request.getHeaders().setIfModifiedSince(file.getLastModified().getTime());
            }
        }
    };

    return this.streamStorageFile(file, inputStreamCallback, requestCallback);
}

From source file:org.springframework.integration.samples.rest.RestHttpClientTest.java

/**
 *
 * @throws Exception/*from  w  w w  .  jav  a  2  s .com*/
 */
@Test
public void testGetEmployeeAsXml() throws Exception {

    Map<String, Object> employeeSearchMap = getEmployeeSearchMap("0");

    final String fullUrl = "http://localhost:8080/rest-http/services/employee/{id}/search";

    EmployeeList employeeList = restTemplate.execute(fullUrl, HttpMethod.GET, new RequestCallback() {
        @Override
        public void doWithRequest(ClientHttpRequest request) throws IOException {
            HttpHeaders headers = getHttpHeadersWithUserCredentials(request);
            headers.add("Accept", "application/xml");
        }
    }, responseExtractor, employeeSearchMap);

    logger.info("The employee list size :" + employeeList.getEmployee().size());

    StringWriter sw = new StringWriter();
    StreamResult sr = new StreamResult(sw);

    marshaller.marshal(employeeList, sr);
    logger.info(sr.getWriter().toString());
    assertTrue(employeeList.getEmployee().size() > 0);
}

From source file:com.appglu.impl.StorageTemplate.java

/**
 * {@inheritDoc}//from  w w w .  j  a va2s  .  c  o  m
 */
public boolean streamStorageFileIfNoneMatch(final StorageFile file, InputStreamCallback inputStreamCallback)
        throws AppGluRestClientException {

    RequestCallback requestCallback = new RequestCallback() {
        public void doWithRequest(ClientHttpRequest request) throws IOException {
            if (file.hasETag()) {
                request.getHeaders().setIfNoneMatch(StringUtils.addDoubleQuotes(file.getETag()));
            }
        }
    };

    return this.streamStorageFile(file, inputStreamCallback, requestCallback);
}

From source file:de.zib.gndms.gndmc.test.gorfx.ESGFGet.java

@Override
protected void run() throws Exception {

    SetupSSL setupSSL = new SetupSSL();
    setupSSL.setKeyStoreLocation(keyStoreLocation);
    setupSSL.prepareKeyStore(passwd, passwd);
    setupSSL.setupDefaultSSLContext(passwd);

    final RestTemplate rt = new RestTemplate();

    rt.execute(url, HttpMethod.GET, null, new ResponseExtractor<Object>() {
        @Override//from   w  w w .j  a v a2 s. co  m
        public Object extractData(final ClientHttpResponse response) throws IOException {

            String url = null;
            String cookieTmp = null;
            System.out.println(response.getStatusCode().toString());
            for (String s : response.getHeaders().keySet())
                for (String v : response.getHeaders().get(s)) {
                    System.out.println(s + ":" + v);
                    if ("Location".equals(s))
                        url = v;
                    else if ("Set-Cookie".equals(s))
                        cookieTmp = v;
                }
            final String cookie = cookieTmp.split(";")[0];

            if (url != null)
                rt.execute(decodeUrl(url), HttpMethod.GET, new RequestCallback() {
                    @Override
                    public void doWithRequest(final ClientHttpRequest request) throws IOException {

                        System.out.println("setting cookie: " + cookie);
                        request.getHeaders().set("Cookie", cookie);
                    }
                }, new ResponseExtractor<Object>() {
                    @Override
                    public Object extractData(final ClientHttpResponse response) throws IOException {

                        System.out.println(response.getStatusCode().toString());
                        System.out.println("Received data, copying");
                        InputStream is = response.getBody();
                        OutputStream os = new FileOutputStream(off);
                        StreamCopyNIO.copyStream(is, os);
                        System.out.println("Done");
                        return null;
                    }
                });

            return null;
        }
    });
}

From source file:de.zib.gndms.gndmc.utils.HTTPGetter.java

public int get(final HttpMethod method, String url, final HttpHeaders headers)
        throws NoSuchAlgorithmException, KeyManagementException {
    logger.debug(method.toString() + " URL " + url);

    EnhancedResponseExtractor responseExtractor = get(method, url, new RequestCallback() {
        @Override/*from   w ww  . j a v  a 2  s  . c om*/
        public void doWithRequest(ClientHttpRequest request) throws IOException {
            // add headers
            if (headers != null)
                request.getHeaders().putAll(headers);
        }
    });
    int statusCode = responseExtractor.getStatusCode();

    int redirectionCounter = 0;

    // redirect as long as needed
    while (300 <= statusCode && statusCode < 400) {
        final List<String> cookies = DefaultResponseExtractor.getCookies(responseExtractor.getHeaders());
        final String location = DefaultResponseExtractor.getLocation(responseExtractor.getHeaders());

        logger.debug("Redirection " + ++redirectionCounter);
        logger.trace("Redirecting to " + location + " with cookies " + cookies.toString());

        responseExtractor = get(method, location, new RequestCallback() {
            @Override
            public void doWithRequest(ClientHttpRequest request) throws IOException {
                for (String c : cookies)
                    request.getHeaders().add("Cookie", c.split(";", 2)[0]);

                // add headers
                if (headers != null)
                    request.getHeaders().putAll(headers);
            }
        });

        statusCode = responseExtractor.getStatusCode();
    }

    logger.debug("HTTP " + method.toString() + " Status Code " + statusCode + " after " + redirectionCounter
            + " redirections");

    return statusCode;
}

From source file:com.appglu.impl.SyncTemplate.java

/**
 * {@inheritDoc}// www. j  ava  2s  .c om
 */
public void downloadChangesForTables(final List<TableVersion> tables,
        final InputStreamCallback inputStreamCallback) throws AppGluRestClientException {
    RequestCallback requestCallback = new RequestCallback() {
        public void doWithRequest(ClientHttpRequest request) throws IOException {
            HttpEntity<Object> requestEntity = new HttpEntity<Object>(new TableVersionBody(tables));

            HttpHeaders requestHeaders = requestEntity.getHeaders();
            if (!requestHeaders.isEmpty()) {
                request.getHeaders().putAll(requestHeaders);
            }

            jsonMessageConverter.write(requestEntity.getBody(), requestHeaders.getContentType(), request);
        }
    };

    ResponseExtractor<Object> responseExtractor = new ResponseExtractor<Object>() {
        public Object extractData(ClientHttpResponse response) throws IOException {
            inputStreamCallback.doWithInputStream(response.getBody());
            return null;
        }
    };

    try {
        this.restOperations.execute(CHANGES_FOR_TABLES_URL, HttpMethod.POST, requestCallback,
                responseExtractor);
    } catch (RestClientException e) {
        throw new AppGluRestClientException(e.getMessage(), e);
    }
}

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");
    }//w w  w  .jav a  2  s. c o  m

    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;
}