Example usage for org.springframework.web.client RestTemplate exchange

List of usage examples for org.springframework.web.client RestTemplate exchange

Introduction

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

Prototype

@Override
    public <T> ResponseEntity<T> exchange(URI url, HttpMethod method, @Nullable HttpEntity<?> requestEntity,
            ParameterizedTypeReference<T> responseType) throws RestClientException 

Source Link

Usage

From source file:org.cloudfoundry.identity.uaa.integration.feature.AutologinIT.java

@Test
public void testSimpleAutologinFlow() throws Exception {
    HttpHeaders headers = getAppBasicAuthHttpHeaders();

    LinkedMultiValueMap<String, String> requestBody = new LinkedMultiValueMap<>();
    requestBody.add("username", testAccounts.getUserName());
    requestBody.add("password", testAccounts.getPassword());

    //generate an autologin code with our credentials
    ResponseEntity<Map> autologinResponseEntity = restOperations.exchange(baseUrl + "/autologin",
            HttpMethod.POST, new HttpEntity<>(requestBody.toSingleValueMap(), headers), Map.class);
    String autologinCode = (String) autologinResponseEntity.getBody().get("code");

    //start the authorization flow - this will issue a login event
    //by using the autologin code
    String authorizeUrl = UriComponentsBuilder.fromHttpUrl(baseUrl).path("/oauth/authorize")
            .queryParam("redirect_uri", appUrl).queryParam("response_type", "code")
            .queryParam("client_id", "app").queryParam("code", autologinCode).build().toUriString();

    //rest template that does NOT follow redirects
    RestTemplate template = new RestTemplate(new DefaultIntegrationTestConfig.HttpClientFactory());
    headers.remove("Authorization");
    headers.add(HttpHeaders.ACCEPT, MediaType.TEXT_HTML_VALUE);
    ResponseEntity<String> authorizeResponse = template.exchange(authorizeUrl, HttpMethod.GET,
            new HttpEntity<>(new HashMap<String, String>(), headers), String.class);

    //we are now logged in. retrieve the JSESSIONID
    List<String> cookies = authorizeResponse.getHeaders().get("Set-Cookie");
    int cookiesAdded = 0;
    headers = getAppBasicAuthHttpHeaders();
    for (String cookie : cookies) {
        if (cookie.startsWith("X-Uaa-Csrf=") || cookie.startsWith("JSESSIONID=")) {
            headers.add("Cookie", cookie);
            cookiesAdded++;/*w  w w  . j  a  va 2 s  .  c  om*/
        }
    }
    assertEquals(2, cookiesAdded);

    //if we receive a 200, then we must approve our scopes
    if (HttpStatus.OK == authorizeResponse.getStatusCode()) {
        authorizeUrl = UriComponentsBuilder.fromHttpUrl(baseUrl).path("/oauth/authorize")
                .queryParam("user_oauth_approval", "true")
                .queryParam(DEFAULT_CSRF_COOKIE_NAME,
                        IntegrationTestUtils.extractCookieCsrf(authorizeResponse.getBody()))
                .build().toUriString();
        authorizeResponse = template.exchange(authorizeUrl, HttpMethod.POST,
                new HttpEntity<>(new HashMap<String, String>(), headers), String.class);
    }

    //approval is complete, we receive a token code back
    assertEquals(HttpStatus.FOUND, authorizeResponse.getStatusCode());
    List<String> location = authorizeResponse.getHeaders().get("Location");
    assertEquals(1, location.size());
    String newCode = location.get(0).substring(location.get(0).indexOf("code=") + 5);

    //request a token using our code
    String tokenUrl = UriComponentsBuilder.fromHttpUrl(baseUrl).path("/oauth/token").build().toUriString();

    MultiValueMap<String, String> tokenParams = new LinkedMultiValueMap<>();
    tokenParams.add("response_type", "token");
    tokenParams.add("grant_type", GRANT_TYPE_AUTHORIZATION_CODE);
    tokenParams.add("code", newCode);
    tokenParams.add("redirect_uri", appUrl);
    headers.set(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED_VALUE);
    headers.set(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE);

    RequestEntity<MultiValueMap<String, String>> requestEntity = new RequestEntity<>(tokenParams, headers,
            HttpMethod.POST, new URI(tokenUrl));
    ResponseEntity<Map> tokenResponse = template.exchange(requestEntity, Map.class);
    assertEquals(HttpStatus.OK, tokenResponse.getStatusCode());

    //here we must reset our state. we do that by following the logout flow.
    headers.clear();

    BasicCookieStore cookieStore = new BasicCookieStore();
    ResponseEntity<String> loginResponse = template.exchange(baseUrl + "/login", HttpMethod.GET,
            new HttpEntity<>(null, getHeaders(cookieStore)), String.class);

    setCookiesFromResponse(cookieStore, loginResponse);
    String csrf = IntegrationTestUtils.extractCookieCsrf(loginResponse.getBody());
    requestBody.add(DEFAULT_CSRF_COOKIE_NAME, csrf);

    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
    loginResponse = restOperations.exchange(baseUrl + "/login.do", HttpMethod.POST,
            new HttpEntity<>(requestBody, getHeaders(cookieStore)), String.class);
    cookies = loginResponse.getHeaders().get("Set-Cookie");
    assertThat(cookies, hasItem(startsWith("JSESSIONID")));
    assertThat(cookies, hasItem(startsWith("X-Uaa-Csrf")));
    if (IdentityZoneHolder.get().getConfig().isAccountChooserEnabled()) {
        assertThat(cookies, hasItem(startsWith("Saved-Account-")));
    }
    assertThat(cookies, hasItem(startsWith("Current-User")));
    cookieStore.clear();
    setCookiesFromResponse(cookieStore, loginResponse);
    headers.add(HttpHeaders.ACCEPT, MediaType.TEXT_HTML_VALUE);
    ResponseEntity<String> profilePage = restOperations.exchange(baseUrl + "/profile", HttpMethod.GET,
            new HttpEntity<>(null, getHeaders(cookieStore)), String.class);

    setCookiesFromResponse(cookieStore, profilePage);
    String revokeApprovalsUrl = UriComponentsBuilder.fromHttpUrl(baseUrl).path("/profile").build()
            .toUriString();
    requestBody.clear();
    requestBody.add("clientId", "app");
    requestBody.add("delete", "");
    requestBody.add(DEFAULT_CSRF_COOKIE_NAME, IntegrationTestUtils.extractCookieCsrf(profilePage.getBody()));
    ResponseEntity<Void> revokeResponse = template.exchange(revokeApprovalsUrl, HttpMethod.POST,
            new HttpEntity<>(requestBody, getHeaders(cookieStore)), Void.class);
    assertEquals(HttpStatus.FOUND, revokeResponse.getStatusCode());
}

From source file:uk.ac.ebi.eva.vcfdump.cellbasewsclient.CellbaseWSClient.java

public Set<String> getChromosomes() {
    try {//from  www. j av a 2  s  . co m
        // call cellbase chromosomes WS
        RestTemplate restTemplate = new RestTemplate();
        ParameterizedTypeReference<QueryResponse<QueryResult<CellbaseChromosomesWSOutput>>> responseType = new ParameterizedTypeReference<QueryResponse<QueryResult<CellbaseChromosomesWSOutput>>>() {
        };

        String cellbaseGetChromosomesUrl = cellbaseRestURL + "/" + cellbaseRestVersion + "/" + species
                + "/genomic/chromosome/all";
        logger.debug("Getting chromosomes list from {} ...", cellbaseGetChromosomesUrl);
        ResponseEntity<QueryResponse<QueryResult<CellbaseChromosomesWSOutput>>> wsOutput = restTemplate
                .exchange(cellbaseGetChromosomesUrl, HttpMethod.GET, null, responseType);

        // parse WS output and return all chromosome names
        QueryResponse<QueryResult<CellbaseChromosomesWSOutput>> response = wsOutput.getBody();
        QueryResult<CellbaseChromosomesWSOutput> result = response.getResponse().get(0);
        CellbaseChromosomesWSOutput results = result.getResult().get(0);
        return results.getAllChromosomeNames();
    } catch (Exception e) {
        logger.debug("Error retrieving list of chromosomes: {}", e.getMessage());
        throw new RuntimeException("Error retrieving list of chromosomes", e);
    }
}

From source file:org.openlmis.notification.web.BaseWebIntegrationTest.java

private String fetchToken() {
    RestTemplate restTemplate = new RestTemplate();

    String plainCreds = clientId + ":" + clientSecret;
    byte[] plainCredsBytes = plainCreds.getBytes();
    byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes);
    String base64Creds = new String(base64CredsBytes);

    HttpHeaders headers = new HttpHeaders();
    headers.add("Authorization", "Basic " + base64Creds);

    HttpEntity<String> request = new HttpEntity<>(headers);

    Map<String, Object> params = new HashMap<>();
    params.put("grant_type", "password");

    ResponseEntity<?> response = restTemplate.exchange(buildUri(authorizationUrl, params), HttpMethod.POST,
            request, Object.class);

    return ((Map<String, String>) response.getBody()).get("access_token");
}

From source file:khs.trouble.service.impl.TroubleService.java

public String kill(String serviceName, String instanceId, String ltoken) {
    if (token != ltoken) {
        throw new RuntimeException("Invalid Access Token");
    }/*from  w  w  w  .  j a  va  2s . c o  m*/

    String url = FormatUrl.url(serviceInstanceURL(serviceName, instanceId) + "trouble/kill", ssl);

    // invoke kill api...
    RestTemplate restTemplate = new RestTemplate();
    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Arrays.asList(MediaType.TEXT_PLAIN));
    headers.add("token", token);
    HttpEntity<String> entity = new HttpEntity<String>("parameters", headers);

    try {
        // int instanceCount = registry.instanceCount(serviceName);
        ResponseEntity<String> result = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);
        if (result.getStatusCode() == HttpStatus.OK) {
            eventService.killed(serviceName, url);
            // monitorServiceRecovery(serviceName, instanceCount);
        }
    } catch (Exception e) {
        eventService.attempted("Attempted to Kill service " + serviceName + " at " + url
                + " Failed due to exception " + e.getMessage());
    }
    return serviceName;
}

From source file:com.auditbucket.client.AbRestClient.java

public String ping() {
    RestTemplate restTemplate = new RestTemplate();
    restTemplate.getMessageConverters().add(new StringHttpMessageConverter());
    HttpHeaders httpHeaders = getHeaders(userName, password);
    HttpEntity requestEntity = new HttpEntity<>(httpHeaders);
    try {/*from   w  ww.  j  a  v a2 s .  c o m*/
        ResponseEntity<String> response = restTemplate.exchange(PING, HttpMethod.GET, requestEntity,
                String.class);
        return response.getBody();
    } catch (HttpClientErrorException e) {
        // ToDo: Rest error handling pretty useless. need to know why it's failing
        logger.error("AB Client Audit error {}", getErrorMessage(e));
        return "err";
    } catch (HttpServerErrorException e) {
        logger.error("AB Server Audit error {}", getErrorMessage(e));
        return "err";

    }

}

From source file:com.auditbucket.client.AbRestClient.java

private String flushAudit(List<MetaInputBean> auditInput) {
    if (simulateOnly || auditInput.isEmpty())
        return "OK";
    RestTemplate restTemplate = new RestTemplate();
    restTemplate.getMessageConverters().add(new StringHttpMessageConverter());

    HttpHeaders httpHeaders = getHeaders(userName, password);
    HttpEntity<List<MetaInputBean>> requestEntity = new HttpEntity<>(auditInput, httpHeaders);

    try {/*from  www  .  ja v a  2 s.co m*/
        restTemplate.exchange(NEW_HEADER, HttpMethod.PUT, requestEntity, TrackResultBean.class);
        return "OK";
    } catch (HttpClientErrorException e) {
        // ToDo: Rest error handling pretty useless. need to know why it's failing
        logger.error("AB Client Audit error {}", getErrorMessage(e));
        return null;
    } catch (HttpServerErrorException e) {
        logger.error("AB Server Audit error {}", getErrorMessage(e));
        return null;

    }
}

From source file:org.obiba.mica.core.service.MailService.java

private synchronized void sendEmail(String subject, String text, String recipient) {
    try {//from  w w w  .j  a va  2s.c  o  m
        RestTemplate template = newRestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.set(APPLICATION_AUTH_HEADER, getApplicationAuth());
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        String form = (Strings.isNullOrEmpty(recipient) ? "" : recipient + "&") + "subject="
                + encode(subject, "UTF-8") + "&body=" + encode(text, "UTF-8");
        HttpEntity<String> entity = new HttpEntity<>(form, headers);

        ResponseEntity<String> response = template.exchange(getNotificationsUrl(), HttpMethod.POST, entity,
                String.class);

        if (response.getStatusCode().is2xxSuccessful()) {
            log.info("Email sent via Agate");
        } else {
            log.error("Sending email via Agate failed with status: {}", response.getStatusCode());
        }
    } catch (Exception e) {
        log.error("Agate connection failure: {}", e.getMessage());
    }
}

From source file:khs.trouble.service.impl.TroubleService.java

public void spawnLoadThread(final String serviceName, String instanceId, final long sleep) {

    Runnable run = new Runnable() {

        public void run() {
            try {

                String url = FormatUrl.url(serviceInstanceURL(serviceName, instanceId) + "/trouble/load", ssl);

                // invoke kill api...
                RestTemplate restTemplate = new RestTemplate();
                HttpHeaders headers = new HttpHeaders();
                headers.setAccept(Arrays.asList(MediaType.TEXT_PLAIN));
                headers.add("token", token);
                headers.add("timeout", "" + timeout);
                HttpEntity<String> entity = new HttpEntity<String>("parameters", headers);

                try {
                    restTemplate.exchange(url, HttpMethod.GET, entity, String.class);
                } catch (Exception e) {
                    eventService.attempted("Attempted to Load service " + serviceName + " at " + url
                            + " Failed due to exception " + e.getMessage());
                }/*from w  w w .j  a v  a  2  s  .  com*/
                Thread.sleep(sleep);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    };

    Thread thread = new Thread(run);
    thread.start();
}

From source file:org.cloudfoundry.identity.uaa.login.feature.InvitationsIT.java

private String generateCode() {
    String token = testClient.getOAuthAccessToken("login", "loginsecret", "client_credentials",
            "password.write,scim.write");
    HttpHeaders headers = new HttpHeaders();
    headers.add("Authorization", "Bearer " + token);
    RestTemplate uaaTemplate = new RestTemplate();

    String userEmail = "user" + new SecureRandom().nextInt() + "@example.com";
    ScimUser scimUser = new ScimUser();
    scimUser.setUserName(userEmail);/*ww w .j  a va 2 s .  c o m*/
    ScimUser.Email email = new ScimUser.Email();
    email.setPrimary(true);
    email.setValue(userEmail);
    scimUser.setEmails(Arrays.asList(email));
    scimUser.setOrigin(Origin.UAA);

    HttpEntity<ScimUser> request = new HttpEntity<>(scimUser, headers);
    ResponseEntity<ScimUser> response = uaaTemplate.exchange(uaaUrl + "/Users", HttpMethod.POST, request,
            ScimUser.class);

    Timestamp expiry = new Timestamp(System.currentTimeMillis()
            + TimeUnit.MILLISECONDS.convert(System.currentTimeMillis() + 24 * 3600, TimeUnit.MILLISECONDS));
    ExpiringCode expiringCode = new ExpiringCode(null, expiry, "{\"client_id\":\"app\", \"user_id\":\""
            + response.getBody().getId() + "\", \"email\":\"user@example.com\"}");
    HttpEntity<ExpiringCode> expiringCodeRequest = new HttpEntity<>(expiringCode, headers);
    ResponseEntity<ExpiringCode> expiringCodeResponse = uaaTemplate.exchange(uaaUrl + "/Codes", HttpMethod.POST,
            expiringCodeRequest, ExpiringCode.class);
    expiringCode = expiringCodeResponse.getBody();
    return expiringCode.getCode();
}

From source file:uta.ak.CollectTweets.java

public void collectTweetsByFileList(String sinceDate, String untilDate, String tag) {
    try {//from  w w  w  .j  a  v a  2 s  .co  m
        // The factory instance is re-useable and thread safe.
        System.out.println("Start to collect tweets from :");
        Set<String> mediaList = new HashSet<String>();
        Resource res = new ClassPathResource("new-social-meida-list.txt");
        //                File stopwords=res.getFile();
        //      File stopwords=new File("/Users/zhangcong/dev/corpus/StopWordTable2.txt");
        InputStreamReader isr = new InputStreamReader(res.getInputStream());
        //            File medias=new File(path);
        //            BufferedReader mdsreader = new BufferedReader(new FileReader(medias));
        BufferedReader mdsreader = new BufferedReader(isr);
        String tempString = mdsreader.readLine();
        while ((tempString = mdsreader.readLine()) != null) {
            System.out.println(tempString.toLowerCase());
            mediaList.add(tempString.toLowerCase());
        }

        ConfigurationBuilder cb = new ConfigurationBuilder();
        cb.setDebugEnabled(true).setOAuthConsumerKey("LuhVZOucqdHX6x0lcVgJO6QK3")
                .setOAuthConsumerSecret("6S7zbGLvHMXDMgRXq7jRIA6QmMpdI8i5IJNpnjlB55vpHpFMpj")
                .setOAuthAccessToken("861637891-kLunD37VRY8ipAK3TVOA0YKOKxeidliTqMtNb7wf")
                .setOAuthAccessTokenSecret("vcKDxs6qHnEE8fhIJr5ktDcTbPGql5o3cNtZuztZwPYl4");
        TwitterFactory tf = new TwitterFactory(cb.build());
        Twitter twitter = tf.getInstance();

        /*
        Connection con = null; //MYSQL
        Class.forName("com.mysql.jdbc.Driver").newInstance(); //MYSQL
        con = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/USTTMP", "root", "root.123"); //MYSQL
        System.out.println("connection yes");
                
        String insertSQL="INSERT INTO c_rawtext(mme_lastupdate, mme_updater, title, text, tag, text_createdate) "
                        + "VALUES (NOW(), \"AK\", ?, ?, ?, ?)";
        PreparedStatement insertPS = con.prepareStatement(insertSQL);
        */

        //?usttmp??
        String restUrl = "http://192.168.0.103:8991/usttmp_textreceiver/rest/addText";

        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DATE, 1);
        SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        for (String mediastr : mediaList) {
            Query query = new Query("from:" + mediastr);
            query.setSince(sinceDate);
            query.setUntil(untilDate);
            query.setCount(100);
            query.setLang("en");

            QueryResult result = twitter.search(query);
            for (Status status : result.getTweets()) {
                System.out.println("@" + status.getUser().getScreenName() + " | "
                        + status.getCreatedAt().toString() + ":" + status.getText());
                System.out.println("Inserting the record into the table...");

                String formattedDate = format1.format(status.getCreatedAt());
                /*
                insertPS.setString (1, status.getUser().getScreenName());
                insertPS.setString (2, status.getText());
                insertPS.setString (3, tag);
                insertPS.setString (4, formattedDate);
                insertPS.addBatch();*/

                //                    if(null!=status.getText()){
                //                        break;
                //                    }

                String interfaceMsg = "<message> " + "    <title> "
                        + ((null != status.getUser().getScreenName()) ? status.getUser().getScreenName()
                                : "NO TITLE")
                        + "    </title> " + "    <text> " + StringEscapeUtils.escapeXml10(status.getText())
                        + "    </text> " + "    <textCreatetime> " + formattedDate + "    </textCreatetime> "
                        + "    <tag> " + tag + "    </tag> " + "</message>";

                //                    String restUrl="http://127.0.0.1:8991/usttmp_textreceiver/rest/addText";

                RestTemplate restTemplate = new RestTemplate();

                HttpHeaders headers = new HttpHeaders();
                headers.setContentType(MediaType.TEXT_XML);
                headers.setAccept(Arrays.asList(MediaType.TEXT_XML));
                //            headers.setContentLength();
                HttpEntity<String> entity = new HttpEntity<String>(interfaceMsg, headers);

                ResponseEntity<String> resresult = restTemplate.exchange(restUrl, HttpMethod.POST, entity,
                        String.class);

                System.out.println(resresult.getBody());
                if (resresult.getBody().contains("<result>failed</result>")) {
                    throw new RuntimeException("response message error");
                }

            }
        }

        //            System.out.println("Start to insert records...");
        //            insertPS.clearParameters();
        //            int[] results = insertPS.executeBatch();

    } catch (Exception te) {
        te.printStackTrace();
        System.out.println("Failed: " + te.getMessage());
        System.exit(-1);
    }
}