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:khs.trouble.service.impl.TroubleService.java

public String exception(String serviceName, String instanceId, String ltoken) {
    if (token != ltoken) {
        throw new RuntimeException("Invalid Access Token");
    }//from   w  w w .java2  s .c  o  m

    String url = FormatUrl.url(serviceInstanceURL(serviceName, instanceId) + "/trouble/exception", 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 {
        restTemplate.exchange(url, HttpMethod.GET, entity, String.class);
        eventService.exception(serviceName, url);
    } catch (Exception e) {
        eventService.attempted("Attempted to throw exception at service " + serviceName + " at " + url
                + " Failed due to exception " + e.getMessage());
    }
    return serviceName;
}

From source file:org.kurento.repository.test.RangePutTests.java

private ResponseEntity<String> putContent(String url, byte[] info, int firstByte) {

    RestTemplate httpClient = getRestTemplate();

    HttpHeaders requestHeaders = new HttpHeaders();
    requestHeaders.set("Content-Range", "bytes " + firstByte + "-" + (firstByte + info.length) + "/*");
    requestHeaders.set("Content-Length", Integer.toString(info.length));

    HttpEntity<byte[]> requestEntity = new HttpEntity<byte[]>(info, requestHeaders);

    ResponseEntity<String> response = httpClient.exchange(url, HttpMethod.PUT, requestEntity, String.class);

    log.info("Put " + info.length + " bytes from " + firstByte + " to " + (firstByte + info.length));

    return response;

}

From source file:org.intermine.app.net.request.PostRequest.java

protected String post() {
    RestTemplate rtp = getRestTemplate();
    HttpHeaders headers = getHeaders();//  w  w  w  .  j  a v  a  2 s .  c  o m
    String uriString = getUrl();
    Map<String, ?> params = getUrlParams();
    MultiValueMap<String, String> post = getPost();

    HttpEntity<?> req;
    if (null != post) {
        req = new HttpEntity<Object>(post, headers);
    } else {
        req = new HttpEntity<String>(headers);
    }

    ResponseEntity<String> res;

    String uri = Uris.expandQuery(uriString, params);

    res = rtp.exchange(uri, POST, req, String.class);
    return res.getBody();
}

From source file:org.intermine.app.net.request.post.CreateGenesList.java

@Override
public Void loadDataFromNetwork() throws Exception {
    RestTemplate rtp = getRestTemplate();
    HttpHeaders headers = getHeaders();/*ww w .  j  a  v  a  2 s .c om*/
    String uriString = getUrl();
    Map<String, ?> params = getUrlParams();
    String post = generateBody();

    HttpEntity<?> req;
    if (null != post) {
        req = new HttpEntity<Object>(post, headers);
    } else {
        req = new HttpEntity<String>(headers);
    }

    ResponseEntity<String> res;

    String uri = Uris.expandQuery(uriString, params);
    rtp.exchange(uri, POST, req, String.class);
    return null;
}

From source file:io.fabric8.che.starter.client.WorkspaceClient.java

/**
 * Create workspace on the Che server with given URL.
 * /*ww  w . j  av  a  2  s. co m*/
 * @param cheServerUrl
 * @param keycloakToken
 * @param name
 * @param stackId
 * @param repo
 * @param branch
 * @return
 * @throws StackNotFoundException
 * @throws IOException
 */
public Workspace createWorkspace(String cheServerUrl, String keycloakToken, String name, String stackId,
        String repo, String branch) throws StackNotFoundException, IOException {
    // The first step is to create the workspace
    String url = CheRestEndpoints.CREATE_WORKSPACE.generateUrl(cheServerUrl);

    name = StringUtils.isBlank(name) ? workspaceHelper.generateName() : name;

    WorkspaceConfig wsConfig = stackClient.getStack(cheServerUrl, stackId, null).getWorkspaceConfig();
    wsConfig.setName(name);
    wsConfig.setDescription(repo + "#" + branch);

    RestTemplate template = new RestTemplate();
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);

    if (keycloakToken != null) {
        template.setInterceptors(Collections.singletonList(new KeycloakInterceptor(keycloakToken)));
    }

    HttpEntity<WorkspaceConfig> entity = new HttpEntity<WorkspaceConfig>(wsConfig, headers);

    ResponseEntity<Workspace> workspaceResponse = template.exchange(url, HttpMethod.POST, entity,
            Workspace.class);
    Workspace workspace = workspaceResponse.getBody();

    LOG.info("Workspace has been created: {}", workspace);

    return workspace;
}

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

public String memory(String serviceName, String instanceId, String ltoken) {
    if (token != ltoken) {
        throw new RuntimeException("Invalid Access Token");
    }//w  w w .jav  a2s . co m

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

    // invoke memory 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);
        eventService.memory(serviceName, url);
    } catch (Exception e) {
        eventService.attempted("Attempted to consume memory at service " + serviceName + " at " + url
                + " Failed due to exception " + e.getMessage());
    }
    return serviceName;
}

From source file:org.trustedanalytics.h2oscoringengine.publisher.steps.RegisteringInApplicationBrokerStep.java

public CreatingPlanVisibilityStep register(BasicAuthServerCredentials appBrokerCredentials,
        RestTemplate appBrokerRestTemplate, String serviceName, String serviceDescription) {

    LOGGER.info("Registering service " + serviceName + " in application-broker");

    String requestBody = prepareAppBrokerJsonRequest(serviceName, serviceDescription);
    HttpHeaders headers = HttpCommunication.basicAuthJsonHeaders(appBrokerCredentials.getBasicAuthToken());
    HttpEntity<String> request = new HttpEntity<>(requestBody, headers);

    String appBrokerEndpoint = appBrokerCredentials.getHost() + APP_BROKER_CATALOG_ENDPOINT;
    appBrokerRestTemplate.exchange(appBrokerEndpoint, HttpMethod.POST, request, String.class);

    return new CreatingPlanVisibilityStep(cfApiUrl, cfRestTemplate);

}

From source file:org.kurento.repository.test.RangeGetTests.java

@Test
public void test() throws Exception {

    String id = "logo.png";

    RepositoryItem item;// ww  w.  j av a  2  s .  c o m
    try {
        item = getRepository().findRepositoryItemById(id);
    } catch (NoSuchElementException e) {
        item = getRepository().createRepositoryItem(id);
        uploadFile(new File("test-files/" + id), item);
    }

    RepositoryHttpPlayer player = item.createRepositoryHttpPlayer();

    String url = player.getURL();

    player.setAutoTerminationTimeout(100000);

    // Following sample
    // http://stackoverflow.com/questions/8293687/sample-http-range-request-session

    RestTemplate httpClient = getRestTemplate();

    {
        HttpHeaders requestHeaders = new HttpHeaders();

        MultiValueMap<String, String> postParameters = new LinkedMultiValueMap<String, String>();

        HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<MultiValueMap<String, String>>(
                postParameters, requestHeaders);

        ResponseEntity<byte[]> response = httpClient.exchange(url, HttpMethod.GET, requestEntity, byte[].class);

        System.out.println(response);

        assertTrue("The server doesn't accept ranges", response.getHeaders().containsKey("Accept-ranges"));
        assertTrue("The server doesn't accept ranges with bytes",
                response.getHeaders().get("Accept-ranges").contains("bytes"));
    }

    long fileLength = 0;

    {
        // Range: bytes=0-

        HttpHeaders requestHeaders = new HttpHeaders();
        requestHeaders.set("Range", "bytes=0-");

        MultiValueMap<String, String> postParameters = new LinkedMultiValueMap<String, String>();

        HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<MultiValueMap<String, String>>(
                postParameters, requestHeaders);

        ResponseEntity<byte[]> response = httpClient.exchange(url, HttpMethod.GET, requestEntity, byte[].class);

        System.out.println(response);

        assertEquals("The server doesn't respond with http status code 206 to a request with ranges",
                HttpStatus.PARTIAL_CONTENT, response.getStatusCode());

        fileLength = Long.parseLong(response.getHeaders().get("Content-Length").get(0));

    }

    {
        HttpHeaders requestHeaders = new HttpHeaders();

        long firstByte = fileLength - 3000;
        long lastByte = fileLength - 1;
        long numBytes = lastByte - firstByte + 1;

        requestHeaders.set("Range", "bytes=" + firstByte + "-" + lastByte);

        MultiValueMap<String, String> postParameters = new LinkedMultiValueMap<String, String>();

        HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<MultiValueMap<String, String>>(
                postParameters, requestHeaders);

        ResponseEntity<byte[]> response = httpClient.exchange(url, HttpMethod.GET, requestEntity, byte[].class);

        System.out.println(response);

        assertEquals("The server doesn't respond with http status code 206 to a request with ranges",
                response.getStatusCode(), HttpStatus.PARTIAL_CONTENT);

        long responseContentLength = Long.parseLong(response.getHeaders().get("Content-Length").get(0));
        assertEquals("The server doesn't send the requested bytes", numBytes, responseContentLength);

        assertEquals("The server doesn't send the requested bytes", responseContentLength,
                response.getBody().length);

    }
}

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

private PolicySet getPolicySet(final RestTemplate acs, final String policyName, final HttpHeaders headers,
        final String acsEndpointParam) {
    ResponseEntity<PolicySet> policySetResponse = acs.exchange(
            acsEndpointParam + PolicyHelper.ACS_POLICY_SET_API_PATH + policyName, HttpMethod.GET,
            new HttpEntity<>(headers), PolicySet.class);
    return policySetResponse.getBody();
}

From source file:com.fredhopper.core.connector.index.upload.impl.RestPublishingStrategy.java

@Override
public String checkStatus(final InstanceConfig config, final URI triggerUrl) throws ResponseStatusException {
    Preconditions.checkArgument(config != null);
    Preconditions.checkArgument(triggerUrl != null);

    final RestTemplate restTemplate = restTemplateProvider.createTemplate(config.getHost(), config.getPort(),
            config.getUsername(), config.getPassword());
    final URI url = triggerUrl.resolve(triggerUrl.getPath() + STATUS_PATH);

    final HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.TEXT_PLAIN);
    final HttpEntity<String> httpEntity = new HttpEntity<>(headers);

    final ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, httpEntity,
            String.class);
    final HttpStatus status = response.getStatusCode();
    if (status.equals(HttpStatus.OK)) {
        return response.getBody();
    } else {/*from ww  w  .j  av  a  2  s.  com*/
        throw new ResponseStatusException(
                "HttpStatus " + status.toString() + " response received. Load trigger monitoring failed.");
    }
}