Java Code Examples for org.springframework.web.client.RestTemplate#getForEntity()

The following examples show how to use org.springframework.web.client.RestTemplate#getForEntity() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: OneRecordingServerTest.java    From kurento-java with Apache License 2.0 7 votes vote down vote up
protected void downloadFromURL(String urlToDownload, File downloadedFile) throws Exception {

    if (!downloadedFile.exists()) {
      downloadedFile.createNewFile();
    }

    log.debug(urlToDownload);

    RestTemplate client = new RestTemplate();
    ResponseEntity<byte[]> response = client.getForEntity(urlToDownload, byte[].class);

    assertEquals(HttpStatus.OK, response.getStatusCode());

    FileOutputStream os = new FileOutputStream(downloadedFile);
    os.write(response.getBody());
    os.close();
  }
 
Example 2
Source File: OidcUserManagementAutoConfiguration.java    From hawkbit with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public void logout(final HttpServletRequest request, final HttpServletResponse response,
        final Authentication authentication) {
    super.logout(request, response, authentication);

    final Object principal = authentication.getPrincipal();
    if (principal instanceof OidcUser) {
        final OidcUser user = (OidcUser) authentication.getPrincipal();
        final String endSessionEndpoint = user.getIssuer() + "/protocol/openid-connect/logout";

        final UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(endSessionEndpoint)
                .queryParam("id_token_hint", user.getIdToken().getTokenValue());

        final RestTemplate restTemplate = new RestTemplate();
        restTemplate.getForEntity(builder.toUriString(), String.class);
    }
}
 
Example 3
Source File: RepositoryRestTest.java    From kurento-java with Apache License 2.0 6 votes vote down vote up
protected void downloadFromURL(String urlToDownload, File downloadedFile) throws IOException {

    if (!downloadedFile.exists()) {
      downloadedFile.createNewFile();
    }

    log.debug(urlToDownload);

    RestTemplate client = new RestTemplate();
    ResponseEntity<byte[]> response = client.getForEntity(urlToDownload, byte[].class);

    assertEquals(HttpStatus.OK, response.getStatusCode());

    FileOutputStream os = new FileOutputStream(downloadedFile);
    os.write(response.getBody());
    os.close();
  }
 
Example 4
Source File: BasicSpringBoot1Test.java    From crnk-framework with Apache License 2.0 6 votes vote down vote up
@Test
public void testRelationshipInclusion() {
	Project project = new Project();
	ProjectRepository projectRepository = new ProjectRepository();
	projectRepository.save(project);

	Task task = new Task();
	task.setProject(project);
	TaskRepository taskRepository = new TaskRepository();
	taskRepository.save(task);

	RestTemplate testRestTemplate = new RestTemplate();
	ResponseEntity<String> response = testRestTemplate
			.getForEntity("http://localhost:" + this.port + "/api/tasks?include[tasks]=schedule,project", String.class);
	assertEquals(HttpStatus.OK, response.getStatusCode());

	JsonFluentAssert included = assertThatJson(response.getBody()).node("included");
	included.isArray().ofLength(1);
}
 
Example 5
Source File: TwintipCustomProfileApplicationIT.java    From booties with Apache License 2.0 6 votes vote down vote up
@Test
public void isConfigured() {

    String endpointUrl = "http://localhost:" + port + "/.well-known/schema-discovery";
    LOG.info("ENDPOINT_URL : {}", endpointUrl);

    RestTemplate template = new RestTemplate();
    ResponseEntity<String> entity = template.getForEntity(endpointUrl, String.class);
    HttpStatus statusCode = entity.getStatusCode();
    String body = entity.getBody();

    Assertions.assertThat(statusCode).isEqualTo(HttpStatus.OK);
    Assertions.assertThat(body).contains("swagger-unreleased");

    LOG.info("BODY : {}", body);

}
 
Example 6
Source File: ErrorHandlerIntegrationTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test // SPR-15560
public void emptyPathSegments() throws Exception {

	RestTemplate restTemplate = new RestTemplate();
	restTemplate.setErrorHandler(NO_OP_ERROR_HANDLER);

	URI url = new URI("http://localhost:" + port + "//");
	ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);

	assertEquals(HttpStatus.OK, response.getStatusCode());
}
 
Example 7
Source File: DiscordServiceImpl.java    From JuniperBot with GNU General Public License v3.0 5 votes vote down vote up
@Override
public String getUserId() {
    if (cachedUserId != null) {
        return cachedUserId;
    }

    int attempt = 0;
    RestTemplate restTemplate = new RestTemplate(new DiscordHttpRequestFactory(workerProperties.getDiscord().getToken()));
    while (cachedUserId == null && attempt++ < 5) {
        try {
            ResponseEntity<String> response = restTemplate.getForEntity(Requester.DISCORD_API_PREFIX + "/users/@me", String.class);
            if (!HttpStatus.OK.equals(response.getStatusCode())) {
                log.warn("Could not get userId, endpoint returned {}", response.getStatusCode());
                continue;
            }
            JSONObject object = new JSONObject(response.getBody());
            cachedUserId = object.getString("id");
            if (StringUtils.isNotEmpty(cachedUserId)) {
                break;
            }
        } catch (Exception e) {
            // fall down
        }
        log.error("Could not request my own userId from Discord, will retry a few times");
        try {
            Thread.sleep(5000);
        } catch (InterruptedException ignored) {
            Thread.currentThread().interrupt();
        }
    }

    if (cachedUserId == null) {
        throw new RuntimeException("Failed to retrieve my own userId from Discord");
    }
    return cachedUserId;
}
 
Example 8
Source File: CustomerClient.java    From microservice-consul with Apache License 2.0 5 votes vote down vote up
public boolean isValidCustomerId(long customerId) {
	RestTemplate restTemplate = new RestTemplate();
	try {
		ResponseEntity<String> entity = restTemplate.getForEntity(
				customerURL() + customerId, String.class);
		return entity.getStatusCode().is2xxSuccessful();
	} catch (final HttpClientErrorException e) {
		if (e.getStatusCode().value() == 404)
			return false;
		else
			throw e;
	}
}
 
Example 9
Source File: ZuulITest.java    From java-specialagent with Apache License 2.0 5 votes vote down vote up
@Bean
public CommandLineRunner commandLineRunner() {
  return new CommandLineRunner() {
    @Override
    public void run(final String ... args) {
      final RestTemplate restTemplate = new RestTemplate();
      final ResponseEntity<String> entity = restTemplate.getForEntity("http://localhost:8080", String.class);
      final int statusCode = entity.getStatusCode().value();
      if (200 != statusCode)
        throw new AssertionError("ERROR: response: " + statusCode);
    }
  };
}
 
Example 10
Source File: BaseRepositoryTest.java    From kurento-java with Apache License 2.0 5 votes vote down vote up
protected void downloadFromURL(String urlToDownload, File downloadedFile) throws Exception {

    RestTemplate template = getRestTemplate();
    ResponseEntity<byte[]> entity = template.getForEntity(urlToDownload, byte[].class);

    assertEquals(HttpStatus.OK, entity.getStatusCode());

    FileOutputStream os = new FileOutputStream(downloadedFile);
    os.write(entity.getBody());
    os.close();
  }
 
Example 11
Source File: GetController.java    From Spring-Boot-Book with Apache License 2.0 5 votes vote down vote up
@RequestMapping("/nparameters")
//返回String,不带参数
public String nparameters() {
    RestTemplate client= restTemplateBuilder.build();
    ResponseEntity<String> responseEntity = client.getForEntity("http://localhost:8080/getuser1", String.class);
    return responseEntity.getBody();
}
 
Example 12
Source File: WebSocketDocsTest.java    From chassis with Apache License 2.0 5 votes vote down vote up
@Test
public void testProtobufMessagesSchema() throws Exception {
	Map<String, Object> properties = new HashMap<String, Object>();
	properties.put("admin.enabled", "true");
	properties.put("admin.port", "" + SocketUtils.findAvailableTcpPort());
	properties.put("admin.hostname", "localhost");
	
	properties.put("websocket.enabled", "true");
	properties.put("websocket.port", "" + SocketUtils.findAvailableTcpPort());
	properties.put("websocket.hostname", "localhost");

	properties.put("http.enabled", "false");
	
	AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
	StandardEnvironment environment = new StandardEnvironment();
	environment.getPropertySources().addFirst(new MapPropertySource("default", properties));
	context.setEnvironment(environment);
	context.register(PropertySourcesPlaceholderConfigurer.class);
	context.register(TransportConfiguration.class);

	RestTemplate httpClient = new RestTemplate();
	
	try {
		context.refresh();

		httpClient.setInterceptors(Lists.newArrayList(LOGGING_INTERCEPTOR));

		ResponseEntity<String> response = httpClient.getForEntity(
				new URI("http://localhost:" + properties.get("admin.port") + "/schema/messages/protobuf"), String.class);
		
		logger.info("Got response: [{}]", response);
		
		Assert.assertEquals(response.getStatusCode().value(), HttpStatus.OK.value());
		Assert.assertTrue(response.getBody().contains("message error"));
	} finally {
		context.close();
	}
}
 
Example 13
Source File: InfoEndpointApplicationIT.java    From booties with Apache License 2.0 5 votes vote down vote up
@Test
public void fetchInfo(){
	RestTemplate rest = new RestTemplate();
	ResponseEntity<String> response = rest.getForEntity("http://localhost:" + port + "/info", String.class);
	Assertions.assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
	Assertions.assertThat(response.getBody()).contains("\"version\":\"0.9.0-SNAPSHOT\"");
}
 
Example 14
Source File: TracingRestTemplateTest.java    From java-spring-web with Apache License 2.0 5 votes vote down vote up
public TracingRestTemplateTest() {
    super(tracer -> {
        final RestTemplate restTemplate = new RestTemplate();
        restTemplate.setInterceptors(Collections.singletonList(
                new TracingRestTemplateInterceptor(tracer)));

        return new Client() {
            @Override
            public <T> ResponseEntity<T> getForEntity(String url, Class<T> clazz) {
                return restTemplate.getForEntity(url, clazz);
            }
        };
    }, RestTemplateSpanDecorator.StandardTags.COMPONENT_NAME);
}
 
Example 15
Source File: BasicSpringBoot2Test.java    From crnk-framework with Apache License 2.0 5 votes vote down vote up
@Test
public void testTestEndpointWithQueryParams() {
	RestTemplate testRestTemplate = new RestTemplate();
	ResponseEntity<String> response = testRestTemplate
			.getForEntity("http://localhost:" + this.port + "/api/tasks?filter[tasks][name]=John", String.class);
	assertEquals(HttpStatus.OK, response.getStatusCode());
	assertThatJson(response.getBody()).node("data").isPresent();
}
 
Example 16
Source File: EndpointAutoConfigurationTest.java    From activiti6-boot2 with Apache License 2.0 5 votes vote down vote up
@Test
public void mvcEndpoint() throws Throwable {

    AnnotationConfigEmbeddedWebApplicationContext applicationContext = 
        new AnnotationConfigEmbeddedWebApplicationContext(CallbackEmbeddedContainerCustomizer.class, EmbeddedContainerConfiguration.class, EndpointConfiguration.class);

    ProcessEngine processEngine = applicationContext.getBean(ProcessEngine.class);
    org.junit.Assert.assertNotNull("the processEngine should not be null", processEngine);

    ProcessEngineEndpoint processEngineEndpoint =
            applicationContext.getBean(ProcessEngineEndpoint.class);
    org.junit.Assert.assertNotNull("the processEngineEndpoint should not be null", processEngineEndpoint);

    RestTemplate restTemplate = applicationContext.getBean(RestTemplate.class);

    ResponseEntity<Map> mapResponseEntity =
            restTemplate.getForEntity("http://localhost:9091/activiti/", Map.class);

    Map map = mapResponseEntity.getBody();

    String[] criticalKeys = {"completedTaskCount", "openTaskCount", "cachedProcessDefinitionCount"};

    Map<?, ?> invokedResults = processEngineEndpoint.invoke();
    for (String k : criticalKeys) {
        org.junit.Assert.assertTrue(map.containsKey(k));
        org.junit.Assert.assertEquals(((Number) map.get(k)).longValue(), ((Number) invokedResults.get(k)).longValue());
    }
}
 
Example 17
Source File: RestTemplateTest.java    From spring-tutorials with Apache License 2.0 5 votes vote down vote up
@Test
public void test_GetStatus() {
    RestTemplate restTemplate = new RestTemplate();
    ResponseEntity<String> response = restTemplate.getForEntity(baseUrl, String.class);
    HttpStatus status = response.getStatusCode();

    isTrue(status == HttpStatus.OK);
}
 
Example 18
Source File: DataTest.java    From n2o-framework with Apache License 2.0 5 votes vote down vote up
@Test
public void javaSpringQuery4() {
    RestTemplate restTemplate = new RestTemplate();
    String queryPath = "/n2o/data/test/java/spring/v4";
    // String fooResourceUrl = "http://localhost:" + port + queryPath + "?size=10&page=1&sorting.value=desc";
    String fooResourceUrl = "http://localhost:" + port + queryPath;
    ResponseEntity<GetDataResponse> response = restTemplate.getForEntity(fooResourceUrl, GetDataResponse.class);
    assertThat(response.getStatusCode(), is(HttpStatus.OK));
    GetDataResponse result = response.getBody();
    assertThat(result.getCount(), is(10));
    assertThat(result.getSize(), is(10));
    assertThat(result.getPage(), is(1));
    assertThat(result.getList().size(), is(10));
    assertThat((result.getList()).get(0).get("value"), is("value0"));
}
 
Example 19
Source File: Backend2BackendService.java    From Gatekeeper with Apache License 2.0 4 votes vote down vote up
public <T> ResponseEntity<T> makeGetCallWithResponse(String url, String service, boolean useHttps, Class<T> clazz){
    RestTemplate restTemplate = new RestTemplate();
    return restTemplate.getForEntity(url(url, service, useHttps), clazz);
}
 
Example 20
Source File: SharedTest.java    From chassis with Apache License 2.0 4 votes vote down vote up
@Test
public void testSwagger() throws Exception {
	Map<String, Object> properties = new HashMap<String, Object>();
	properties.put("admin.enabled", "true");
	properties.put("admin.port", "" + SocketUtils.findAvailableTcpPort());
	properties.put("admin.hostname", "localhost");
	
	properties.put("websocket.enabled", "true");
	properties.put("websocket.port", "" + SocketUtils.findAvailableTcpPort());
	properties.put("websocket.hostname", "localhost");

	properties.put("http.enabled", "true");
	properties.put("http.port", "" + SocketUtils.findAvailableTcpPort());
	properties.put("http.hostname", "localhost");
	
	AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
	StandardEnvironment environment = new StandardEnvironment();
	environment.getPropertySources().addFirst(new MapPropertySource("default", properties));
	context.setEnvironment(environment);
	context.register(PropertySourcesPlaceholderConfigurer.class);
	context.register(TransportConfiguration.class);
	context.register(MetricsConfiguration.class);

	RestTemplate httpClient = new RestTemplate();
	
	try {
		context.refresh();

		httpClient.setInterceptors(Lists.newArrayList(LOGGING_INTERCEPTOR));
		List<HttpMessageConverter<?>> messageConverters = new ArrayList<>();
		for (MessageSerDe messageSerDe : context.getBeansOfType(MessageSerDe.class).values()) {
			messageConverters.add(new SerDeHttpMessageConverter(messageSerDe));
		}
		messageConverters.add(new StringHttpMessageConverter(StandardCharsets.UTF_8));
		httpClient.setMessageConverters(messageConverters);

		ResponseEntity<String> response = httpClient.getForEntity(new URI("http://localhost:" + properties.get("http.port") + "/swagger/index.html"), String.class);
		
		logger.info("Got response: [{}]", response);
		
		Assert.assertEquals(response.getStatusCode().value(), HttpStatus.OK.value());
		Assert.assertTrue(response.getBody().contains("<title>Swagger UI</title>"));
	} finally {
		context.close();
	}
}