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

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

Introduction

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

Prototype

public RestTemplate() 

Source Link

Document

Create a new instance of the RestTemplate using default settings.

Usage

From source file:com.neiljbrown.brighttalk.channels.reportingapi.client.spring.SpringApiClientImplTest.java

/**
 * Tests constructor {@link SpringApiClientImpl#SpringApiClientImpl(String, RestTemplate)} in the case where the
 * supplied host name is valid. Serves to test the default protocol and port.
 *//*from  w ww . ja  v a2  s .  c  o m*/
@Test
public final void testConstructValidHostNameOnly() {
    SpringApiClientImpl apiClient = new SpringApiClientImpl("api.test.brighttalk.net", new RestTemplate());
    assertThat(apiClient.getApiServiceProtocol(), is("https"));
    assertThat(apiClient.getApiServicePort(), is(443));
}

From source file:org.n52.tamis.rest.forward.processes.ProcessesRequestForwarder.java

/**
 * {@inheritDoc} <br/>//  ww w. j a v a  2 s  . c o  m
 * <br/>
 * Delegates an incoming processes (overview) request to the WPS proxy,
 * receives the extended processes document and creates an instance of
 * {@link Processes_Tamis}
 * 
 * @param parameterValueStore
 *            must contain the URL variable
 *            {@link URL_Constants_TAMIS#SERVICE_ID_VARIABLE_NAME} to
 *            identify the WPS instance
 * @return an instance of {@link Processes_Tamis}
 */
public final Processes_Tamis forwardRequestToWpsProxy(HttpServletRequest request, Object requestBody,
        ParameterValueStore parameterValueStore) {
    // assure that the URL variable "serviceId" is existent
    initializeRequestSpecificParameters(parameterValueStore);

    String processes_url_wpsProxy = createTargetURL_WpsProxy(request);

    RestTemplate processesTemplate = new RestTemplate();

    // fetch extended processesDoc from WPS proxy and deserialize it into
    // shortened processesDoc
    Processes_Tamis processesDoc = processesTemplate.getForObject(processes_url_wpsProxy,
            Processes_Tamis.class);

    /*
     * set the URL.
     * 
     * construct it via the requestURL from HttpServletRequest object and
     * append the process identifier.
     */
    setUrls(processesDoc, request.getRequestURL());

    return processesDoc;
}

From source file:at.ac.tuwien.dsg.cloud.utilities.gateway.registry.KongService.java

public KongPluginResponse enablePlugin(KongApiObject apiObject, KongPlugin plugin) {
    try {//w w  w.  java 2 s  .  c  o m
        RequestEntity<KongPlugin> requestEntity = RequestEntity
                .post(URI.create(this.kongUris.getKongPluginsForApiUri(apiObject.getApiName())))
                .contentType(MediaType.APPLICATION_JSON).accept(MediaType.ALL).body(plugin);

        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<KongPluginResponse> resp = restTemplate.exchange(requestEntity,
                KongPluginResponse.class);

        logger.trace("Response from Kong: {}", resp.getBody());
        return resp.getBody();
    } catch (HttpStatusCodeException e) {
        String serverResp = e.getResponseBodyAsString();
        logger.error(String.format("Exception from server! " + "Following body was responded %s", serverResp),
                e);
    }
    return null;
}

From source file:se.vgregion.alfrescoclient.service.AlfrescoService.java

/**
 * Initialises the RestTemplate./* w  w  w .  j  a  v  a 2s.com*/
 *
 * @return the RestTemplate
 */
private RestTemplate initJsonRestTemplate() {
    RestTemplate template = new RestTemplate();
    CommonsClientHttpRequestFactory requestFactory = new CommonsClientHttpRequestFactory();
    final int timeout = 5000; // Five seconds
    requestFactory.setReadTimeout(timeout);
    template.setRequestFactory(requestFactory);
    HttpMessageConverter<?>[] httpMessageConverters = new HttpMessageConverter<?>[] {
            new MappingJacksonHttpMessageConverter() };
    template.setMessageConverters(Arrays.asList(httpMessageConverters));

    return template;
}

From source file:com.example.ResourceApp.java

@Bean
RestTemplate restTemplate() {
    return new RestTemplate();
}

From source file:com.pepaproch.gtswsdlclient.TestBase.java

protected RestTemplate getRestAuthenticatedTemplate() {
    RestTemplate restTemplate = new RestTemplate();
    AuthHeaderInterceptor securityTokenInterceptor = new AuthHeaderInterceptor(getAuthTokenProvider());
    List<ClientHttpRequestInterceptor> interceptors = restTemplate.getInterceptors();
    if (interceptors == null) {
        interceptors = new ArrayList<>();
        restTemplate.setInterceptors(interceptors);
    }//from   w ww.jav  a  2  s  .  c o m
    interceptors.add(securityTokenInterceptor);
    List<HttpMessageConverter<?>> list = new ArrayList<>();
    list.add(new MappingJackson2HttpMessageConverter());
    restTemplate.setMessageConverters(list);
    return restTemplate;

}

From source file:com.angelmmg90.consumerservicespotify.configuration.SpringWebConfig.java

@Bean
public static RestTemplate getTemplate() throws IOException {
    if (template == null) {
        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(new AuthScope(PROXY_HOST, PROXY_PORT),
                new UsernamePasswordCredentials(PROXY_USER, PROXY_PASSWORD));

        Header[] h = new Header[3];
        h[0] = new BasicHeader(HttpHeaders.CONTENT_TYPE, "application/json");
        h[1] = new BasicHeader(HttpHeaders.AUTHORIZATION, "Bearer " + ACCESS_TOKEN);

        List<Header> headers = new ArrayList<>(Arrays.asList(h));

        HttpClientBuilder clientBuilder = HttpClientBuilder.create();

        clientBuilder.useSystemProperties();
        clientBuilder.setProxy(new HttpHost(PROXY_HOST, PROXY_PORT));
        clientBuilder.setDefaultCredentialsProvider(credentialsProvider);
        clientBuilder.setDefaultHeaders(headers).build();
        String SAMPLE_URL = "https://api.spotify.com/v1/users/yourUserName/playlists/7HHFd1tNiIFIwYwva5MTNv";

        HttpUriRequest request = RequestBuilder.get().setUri(SAMPLE_URL).build();

        clientBuilder.setProxyAuthenticationStrategy(new ProxyAuthenticationStrategy());

        CloseableHttpClient client = clientBuilder.build();
        client.execute(request);/*  w w w.  ja v  a2s  .co  m*/

        HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
        factory.setHttpClient(client);

        template = new RestTemplate();
        template.setRequestFactory(factory);
    }

    return template;
}

From source file:org.cloudfoundry.identity.uaa.login.RemoteUaaControllerMockMvcTests.java

@Test
public void testLoginWithRemoteUaaPrompts() throws Exception {
    RestTemplate restTemplate = new RestTemplate();
    RemoteUaaController controller = new RemoteUaaController(new MockEnvironment(), restTemplate);
    controller.setUaaBaseUrl("https://uaa.example.com");

    MockMvc mockMvc = getMockMvc(controller);

    MockRestServiceServer mockServer = MockRestServiceServer.createServer(restTemplate);
    mockServer.expect(requestTo("https://uaa.example.com/login")).andExpect(method(GET))
            .andExpect(header("Accept", APPLICATION_JSON_VALUE))
            .andRespond(withSuccess("{\n" + "    \"prompts\": {\n" + "        \"how\": [\n"
                    + "            \"text\",\n" + "            \"Made-up field.\"\n" + "        ],\n"
                    + "        \"passcode\": [\n" + "            \"password\",\n"
                    + "            \"Passcode should not be filtered out in API.\"\n" + "        ]\n"
                    + "    }\n" + "}", APPLICATION_JSON));

    mockMvc.perform(get("/login").accept(APPLICATION_JSON)).andExpect(status().isOk())
            .andExpect(view().name("login")).andExpect(model().attribute("prompts", hasKey("how")))
            .andExpect(model().attribute("prompts", hasKey("passcode")))
            .andExpect(model().attribute("prompts", not(hasKey("password"))));
}

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

/**
 * Create workspace on the Che server with given URL.
 * //from   w w  w  .j  av  a2 s  .  c  o 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:org.zalando.riptide.ActionsTest.java

public ActionsTest() {
    final RestTemplate template = new RestTemplate();
    template.setMessageConverters(singletonList(
            new MappingJackson2HttpMessageConverter(new ObjectMapper().findAndRegisterModules())));
    template.setErrorHandler(new PassThroughResponseErrorHandler());
    this.server = MockRestServiceServer.createServer(template);
    this.unit = Rest.create(template);
}