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:io.fabric8.che.starter.client.CheRestClient.java

@Async
public void createProject(String cheServerURL, String workspaceId, String name, String repo, String branch)
        throws IOException {

    // Before we can create a project, we must start the new workspace
    startWorkspace(cheServerURL, workspaceId);

    // Poll until the workspace is started
    WorkspaceStatus status = checkWorkspace(cheServerURL, workspaceId);
    long currentTime = System.currentTimeMillis();
    while (!WORKSPACE_STATUS_RUNNING.equals(status.getWorkspaceStatus())
            && System.currentTimeMillis() < (currentTime + WORKSPACE_START_TIMEOUT_MS)) {
        try {/*  w  w w .j a va2s . co  m*/
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            LOG.error("Error while polling for workspace status", e);
            break;
        }
        status = checkWorkspace(cheServerURL, workspaceId);
    }

    Workspace workspace = getWorkspaceByKey(cheServerURL, workspaceId);

    DevMachineServer server = workspace.getRuntime().getDevMachine().getRuntime().getServers().get("4401/tcp");

    // Next we create a new project within the workspace
    String url = generateURL(server.getUrl(), CheRestEndpoints.CREATE_PROJECT, workspaceId);
    LOG.info("Creating project against workspace agent URL: {}", url);

    String jsonTemplate = projectTemplate.createRequest().setName(name).setRepo(repo).setBranch(branch)
            .getJSON();

    RestTemplate template = new RestTemplate();
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    HttpEntity<String> entity = new HttpEntity<String>(jsonTemplate, headers);

    ResponseEntity<Project[]> response = template.exchange(url, HttpMethod.POST, entity, Project[].class);

    if (response.getBody().length > 0) {
        Project p = response.getBody()[0];
        LOG.info("Successfully created project {}", p.getName());
    } else {
        LOG.info("There seems to have been a problem creating project {}", name);
    }
}

From source file:com.cloudera.nav.sdk.client.NavigatorPluginTest.java

private void assertModelRegistration() {
    RestTemplate mockTemplate = mock(RestTemplate.class);
    NavApiCient client = spy(plugin.getClient());
    when(plugin.getClient()).thenReturn(client);
    when(client.newRestTemplate()).thenReturn(mockTemplate);
    MetadataModel mockResponse = new MetadataModel();
    Map<String, Collection<String>> mockErrs = Maps.newHashMap();
    mockErrs.put("model1", Sets.newHashSet("msg1", "msg2"));
    when(mockTemplate.exchange(eq(plugin.getClient().getApiUrl() + "/models"), eq(HttpMethod.POST),
            any(HttpEntity.class), eq(MetadataModel.class)))
                    .thenReturn(new ResponseEntity<>(mockResponse, HttpStatus.OK));
    MetadataModel response = plugin.registerModel(TestMClass.class);
    assertEquals(mockResponse, response);
}

From source file:io.getlime.push.controller.web.WebAdminController.java

@RequestMapping(value = "web/admin/message/create/do.submit", method = RequestMethod.POST)
public String actionCreatePushMessage(@Valid ComposePushMessageForm form, BindingResult bindingResult,
        RedirectAttributes attr, HttpServletRequest httpRequest) {
    if (bindingResult.hasErrors()) {
        attr.addFlashAttribute("fields", bindingResult);
        attr.addFlashAttribute("form", form);
        return "redirect:/web/admin/message/create";
    }/*  www. ja  v a 2s. c o  m*/
    SendPushMessageRequest request = new SendPushMessageRequest();
    request.setAppId(form.getAppId());
    PushMessage message = new PushMessage();
    message.setUserId(form.getUserId());
    PushMessageBody body = new PushMessageBody();
    body.setTitle(form.getTitle());
    body.setBody(form.getBody());
    body.setSound(form.isSound() ? "default" : null);
    message.setBody(body);
    request.setMessage(message);
    HttpEntity<ObjectRequest<SendPushMessageRequest>> requestEntity = new HttpEntity<>(
            new ObjectRequest<>(request));
    RestTemplate template = new RestTemplate();
    String baseUrl = String.format("%s://%s:%d/%s", httpRequest.getScheme(), httpRequest.getServerName(),
            httpRequest.getServerPort(), httpRequest.getContextPath());
    template.exchange(baseUrl + "/push/message/send", HttpMethod.POST, requestEntity,
            new ParameterizedTypeReference<ObjectResponse<PushMessageSendResult>>() {
            });
    return "redirect:/web/admin/message/create";
}

From source file:it.reply.orchestrator.service.OneDataServiceImpl.java

private <T> ResponseEntity<T> getForEntity(RestTemplate restTemplate, String endpoint, String oneDataToken,
        Class<T> entityClass) {
    HttpHeaders headers = new HttpHeaders();
    headers.set("macaroon", oneDataToken);

    HttpEntity<?> entity = new HttpEntity<>(headers);
    return restTemplate.exchange(endpoint, HttpMethod.GET, entity, entityClass);
}

From source file:com.cloudera.nav.sdk.client.NavApiCient.java

private <R, T> T sendRequest(String url, HttpMethod method, Class<? extends T> resultClass, R requestPayload) {
    RestTemplate restTemplate = newRestTemplate();
    HttpHeaders headers = getAuthHeaders();
    HttpEntity<?> request = requestPayload == null ? new HttpEntity<String>(headers)
            : new HttpEntity<>(requestPayload, headers);
    ResponseEntity<? extends T> response = restTemplate.exchange(url, method, request, resultClass);
    return response.getBody();
}

From source file:eu.freme.broker.eservices.FremeNER.java

private ResponseEntity<String> callBackend(String uri, HttpMethod method, String body) {

    RestTemplate restTemplate = new RestTemplate();
    try {/*from ww  w .  ja  va2  s .  co m*/
        if (body == null) {
            return restTemplate.exchange(new URI(uri), method, null, String.class);
        } else {
            ResponseEntity<String> response = restTemplate.exchange(new URI(uri), method,
                    new HttpEntity<String>(body), String.class);

            if (response.getStatusCode() == HttpStatus.CONFLICT) {
                throw new eu.freme.broker.exception.BadRequestException(
                        "Dataset with this name already existis and it cannot be created.");
            } else {
                return response;
            }
            //                return restTemplate.exchange(new URI(uri), method, new HttpEntity<String>(body), String.class);
        }
    } catch (HttpClientErrorException rce) {
        if (rce.getStatusCode() == HttpStatus.CONFLICT) {
            throw new eu.freme.broker.exception.BadRequestException(
                    "Dataset with this name already existis and it cannot be created.");
        } else {
            throw new eu.freme.broker.exception.ExternalServiceFailedException(rce.getMessage());
        }
    } catch (RestClientException rce) {
        logger.error("failed", rce);
        throw new eu.freme.broker.exception.ExternalServiceFailedException(rce.getMessage());
    } catch (Exception e) {
        logger.error("failed", e);
        return new ResponseEntity<String>(HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

From source file:cz.zcu.kiv.eeg.mobile.base.ws.asynctask.FetchExperiments.java

/**
 * Method, where all experiments are read from server.
 * All heavy lifting is made here.//from  w  w w. ja  va 2  s  .  com
 *
 * @param params not used (omitted) here
 * @return list of fetched experiments
 */
@Override
protected List<Experiment> doInBackground(Void... params) {
    SharedPreferences credentials = getCredentials();
    String username = credentials.getString("username", null);
    String password = credentials.getString("password", null);
    String url = credentials.getString("url", null) + Values.SERVICE_EXPERIMENTS;

    setState(RUNNING, R.string.working_ws_experiments);
    HttpAuthentication authHeader = new HttpBasicAuthentication(username, password);
    HttpHeaders requestHeaders = new HttpHeaders();
    requestHeaders.setAuthorization(authHeader);
    requestHeaders.setAccept(Collections.singletonList(MediaType.APPLICATION_XML));
    HttpEntity<Object> entity = new HttpEntity<Object>(requestHeaders);

    SSLSimpleClientHttpRequestFactory factory = new SSLSimpleClientHttpRequestFactory();
    // Create a new RestTemplate instance
    RestTemplate restTemplate = new RestTemplate(factory);
    restTemplate.getMessageConverters().add(new SimpleXmlHttpMessageConverter());

    try {

        //obtain all public records if qualifier is all
        if (Values.SERVICE_QUALIFIER_ALL.equals(qualifier)) {
            String countUrl = url + "count";
            ResponseEntity<RecordCount> count = restTemplate.exchange(countUrl, HttpMethod.GET, entity,
                    RecordCount.class);

            url += "public/" + count.getBody().getPublicRecords();
        } else
            url += qualifier;

        // Make the network request
        Log.d(TAG, url);
        ResponseEntity<ExperimentList> response = restTemplate.exchange(url, HttpMethod.GET, entity,
                ExperimentList.class);
        ExperimentList body = response.getBody();

        if (body != null) {
            return body.getExperiments();
        }

    } catch (Exception e) {
        Log.e(TAG, e.getLocalizedMessage(), e);
        setState(ERROR, e);
    } finally {
        setState(DONE);
    }
    return Collections.emptyList();
}

From source file:com.ge.predix.test.utils.PrivilegeHelper.java

public void deleteSubject(final RestTemplate restTemplate, final String acsUrl, final String subjectId,
        final HttpHeaders headers) throws Exception {
    if (subjectId != null) {
        URI subjectUri = URI.create(acsUrl + ACS_SUBJECT_API_PATH + URLEncoder.encode(subjectId, "UTF-8"));
        restTemplate.exchange(subjectUri, HttpMethod.DELETE, new HttpEntity<>(headers), String.class);
    }/*from   w  ww.j a  v  a2  s .  c  o  m*/
}

From source file:com.ge.predix.test.utils.PrivilegeHelper.java

public void deleteResource(final RestTemplate restTemplate, final String acsUrl, final String resourceId,
        final HttpHeaders headers) throws Exception {
    if (resourceId != null) {
        URI resourceUri = URI.create(acsUrl + ACS_RESOURCE_API_PATH + URLEncoder.encode(resourceId, "UTF-8"));
        restTemplate.exchange(resourceUri, HttpMethod.DELETE, new HttpEntity<>(headers), String.class);
    }// w w w  . j  a v  a 2  s  . c  om
}

From source file:cz.muni.fi.mushroomhunter.restclient.LocationUpdateSwingWorker.java

@Override
protected Integer doInBackground() throws Exception {
    DefaultTableModel model = (DefaultTableModel) restClient.getTblLocation().getModel();
    int selectedRow = restClient.getTblLocation().getSelectedRow();

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

    RestTemplate restTemplate = new RestTemplate();

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    List<MediaType> mediaTypeList = new ArrayList<>();
    mediaTypeList.add(MediaType.ALL);/* w  w  w  .jav a  2s. c  o m*/
    headers.setAccept(mediaTypeList);

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

    HttpEntity request = new HttpEntity<>(headers);

    ResponseEntity<LocationDto> responseEntity = restTemplate.exchange(
            RestClient.SERVER_URL + "pa165/rest/location/" + RestClient.getLocationIDs().get(selectedRow),
            HttpMethod.GET, request, LocationDto.class);

    LocationDto locationDto = responseEntity.getBody();

    locationDto.setName(restClient.getTfLocationName().getText());
    locationDto.setDescription(restClient.getTfLocationDescription().getText());
    locationDto.setNearCity(restClient.getTfLocationNearCity().getText());

    ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
    String json = ow.writeValueAsString(locationDto);
    request = new HttpEntity(json, headers);

    restTemplate.exchange(RestClient.SERVER_URL + "pa165/rest/location", HttpMethod.PUT, request,
            LocationDto.class);
    return selectedRow;
}