Java Code Examples for org.springframework.web.client.RestTemplate

The following are top voted examples for showing how to use org.springframework.web.client.RestTemplate. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: twitch4j   File: TMIEndpoint.java   View source code 8 votes vote down vote up
/**
 * Gets all user's present in the twitch chat of a channel.
 *
 * @param channelName Channel to fetch the information for.
 * @return All chatters in a channel, separated into groups like admins, moderators and viewers.
 */
public Chatter getChatters(String channelName) {
	// Endpoint
	String requestUrl = String.format("%s/group/user/%s/chatters", Endpoints.TMI.getURL(), channelName);
	RestTemplate restTemplate = getTwitchClient().getRestClient().getRestTemplate();

	// REST Request
	try {
		if (!restObjectCache.containsKey(requestUrl)) {
			Logger.trace(this, "Rest Request to [%s]", requestUrl);
			ChatterResult responseObject = restTemplate.getForObject(requestUrl, ChatterResult.class);
			restObjectCache.put(requestUrl, responseObject, ExpirationPolicy.CREATED, 60, TimeUnit.SECONDS);
		}

		return ((ChatterResult) restObjectCache.get(requestUrl)).getChatters();

	} catch (RestException restException) {
		Logger.error(this, "RestException: " + restException.getRestError().toString());
	} catch (Exception ex) {
		Logger.error(this, "Request failed: " + ex.getMessage());
		Logger.trace(this, ExceptionUtils.getStackTrace(ex));
	}

	// OnError: Return empty result
	return new Chatter();
}
 
Example 2
Project: websocket-poc   File: App.java   View source code 8 votes vote down vote up
@Bean
public RestTemplate restTemplate() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {

    SSLContext sslContext = SSLContexts.custom()
            .loadTrustMaterial(null, new TrustSelfSignedStrategy())
            .build();

    SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);
    CloseableHttpClient httpClient = HttpClients.custom()
            .setSSLSocketFactory(sslConnectionSocketFactory)
            .build();

    HttpComponentsClientHttpRequestFactory requestFactory =
            new HttpComponentsClientHttpRequestFactory();

    requestFactory.setHttpClient(httpClient);

    return new RestTemplate(requestFactory);
}
 
Example 3
Project: incubator-servicecomb-java-chassis   File: JaxrsClient.java   View source code 7 votes vote down vote up
private static void testExchange(RestTemplate template, String cseUrlPrefix) {
  HttpHeaders headers = new HttpHeaders();
  headers.add("Accept", MediaType.APPLICATION_JSON);
  Person person = new Person();
  person.setName("world");
  HttpEntity<Person> requestEntity = new HttpEntity<>(person, headers);
  ResponseEntity<Person> resEntity = template.exchange(cseUrlPrefix + "/compute/sayhello",
      HttpMethod.POST,
      requestEntity,
      Person.class);
  TestMgr.check("hello world", resEntity.getBody());

  ResponseEntity<String> resEntity2 =
      template.exchange(cseUrlPrefix + "/compute/addstring?s=abc&s=def", HttpMethod.DELETE, null, String.class);
  TestMgr.check("abcdef", resEntity2.getBody());
}
 
Example 4
Project: twitch4j   File: StreamEndpoint.java   View source code 7 votes vote down vote up
/**
 * Get Featured Streams
 * <p>
 * Gets a list of all featured live streams.
 * Requires Scope: none
 *
 * @param limit  Maximum number of most-recent objects to return. Default: 25. Maximum: 100.
 * @param offset Object offset for pagination of results. Default: 0.
 * @return The requested range/amount of featured streams.
 */
public List<StreamFeatured> getFeatured(Optional<Long> limit, Optional<Long> offset) {
	// Endpoint
	String requestUrl = String.format("%s/streams/featured", Endpoints.API.getURL());
	RestTemplate restTemplate = getTwitchClient().getRestClient().getRestTemplate();

	// Parameters
	restTemplate.getInterceptors().add(new QueryRequestInterceptor("limit", limit.orElse(25l).toString()));
	restTemplate.getInterceptors().add(new QueryRequestInterceptor("offset", offset.orElse(0l).toString()));

	// REST Request
	try {
		StreamFeaturedList responseObject = restTemplate.getForObject(requestUrl, StreamFeaturedList.class);

		return responseObject.getFeatured();
	} catch (Exception ex) {
		Logger.error(this, "Request failed: " + ex.getMessage());
		Logger.trace(this, ExceptionUtils.getStackTrace(ex));
	}

	return new ArrayList<StreamFeatured>();
}
 
Example 5
Project: waggle-dance   File: WaggleDanceIntegrationTest.java   View source code 6 votes vote down vote up
@Test
public void restApiGetStatus() throws Exception {
  exit.expectSystemExitWithStatus(0);

  runner = WaggleDanceRunner
      .builder(configLocation)
      .primary("primary", localServer.getThriftConnectionUri(), READ_ONLY)
      .federate("waggle_remote", remoteServer.getThriftConnectionUri(), REMOTE_DATABASE)
      .build();

  runWaggleDance(runner);

  RestTemplate rest = new RestTemplateBuilder().build();
  PrimaryMetaStore primaryMetastore = rest.getForObject("http://localhost:18000/api/admin/federations/primary",
      PrimaryMetaStore.class);
  assertThat(primaryMetastore.getStatus(), is(MetaStoreStatus.AVAILABLE));
  FederatedMetaStore federatedMetastore = rest
      .getForObject("http://localhost:18000/api/admin/federations/waggle_remote", FederatedMetaStore.class);
  assertThat(federatedMetastore.getStatus(), is(MetaStoreStatus.AVAILABLE));
}
 
Example 6
Project: java-spring-web   File: TracingRestTemplateTest.java   View source code 6 votes vote down vote up
public TracingRestTemplateTest() {
    final RestTemplate restTemplate = new RestTemplate();
    restTemplate.setInterceptors(Collections.<ClientHttpRequestInterceptor>singletonList(
            new TracingRestTemplateInterceptor(mockTracer)));

    client = new Client<RestTemplate>() {
        @Override
        public <T> ResponseEntity<T> getForEntity(String url, Class<T> clazz) {
            return restTemplate.getForEntity(url, clazz);
        }

        @Override
        public RestTemplate template() {
            return restTemplate;
        }
    };

    mockServer = MockRestServiceServer.bindTo(client.template()).build();
}
 
Example 7
Project: xitikit-blue   File: SimpleB2CAuthenticationService.java   View source code 6 votes vote down vote up
public SimpleB2CAuthenticationService(
  final ClaimValidationService claimValidationService,
  final NonceService nonceService,
  final UrlService urlService,
  final RestTemplate restTemplate){

    Assert.notNull(
      claimValidationService,
      "Missing required parameter 'claimValidationService' " +
        "(org.xitikit.blue.noitacitnehtua.api.v2dot0.SimpleB2CAuthenticationService::new)");
    Assert.notNull(nonceService, "Missing required parameter 'nonceService' (org.xitikit.blue.noitacitnehtua.api.v2dot0.SimpleB2CAuthenticationService::new)");
    Assert.notNull(urlService, "Missing required parameter 'blueUrlService' (org.xitikit.blue.noitacitnehtua.api.v2dot0.SimpleB2CAuthenticationService::new)");
    Assert.notNull(restTemplate, "Missing required parameter 'restTemplate' (org.xitikit.blue.noitacitnehtua.api.v2dot0.SimpleB2CAuthenticationService::new)");

    this.claimValidationService = claimValidationService;
    this.nonceService = nonceService;
    this.urlService = urlService;
    this.restTemplate = restTemplate;
}
 
Example 8
Project: twitch4j   File: StreamEndpoint.java   View source code 6 votes vote down vote up
/**
 * Get Followed Streams
 * <p>
 * Gets the list of online streams a user follows based on the OAuthTwitch token provided.
 * Requires Scope: user_read
 *
 * @param credential The user.
 * @return All streams as user follows.
 */
public List<Stream> getFollowed(OAuthCredential credential) {
	// Endpoint
	String requestUrl = String.format("%s/streams/followed", Endpoints.API.getURL());
	RestTemplate restTemplate = getTwitchClient().getRestClient().getPrivilegedRestTemplate(credential);

	// REST Request
	try {
		StreamList responseObject = restTemplate.getForObject(requestUrl, StreamList.class);

		return responseObject.getStreams();
	} catch (Exception ex) {
		Logger.error(this, "Request failed: " + ex.getMessage());
		Logger.trace(this, ExceptionUtils.getStackTrace(ex));
	}

	return new ArrayList<Stream>();
}
 
Example 9
Project: esup-ecandidat   File: LimeSurveyRest.java   View source code 6 votes vote down vote up
/** Execute un WS sur LimeSurvey
 * @param obj
 * @return la ResponseEntity
 */
private ResponseEntity<String> executeWS(LimeSurveyRestObject obj){
	try {
		HttpHeaders headers = new HttpHeaders();
		headers.setContentType(MediaType.APPLICATION_JSON);						
		String serialized;
		ObjectMapper mapper = new ObjectMapper();
		serialized = mapper.writeValueAsString(obj);
		HttpEntity<String> requestEntity=new HttpEntity<String>(serialized,headers);
		RestTemplate restTemplate = new RestTemplate();
		ResponseEntity<String> response = restTemplate.exchange(URL,HttpMethod.POST,requestEntity,String.class);
		return response;
	} catch (Exception e) {
		logger.error("Erreur d'appel du web service "+obj.getMethod()+" sur LimeSurvey",e);
		return null;
	}
}
 
Example 10
Project: REST-Web-Services   File: SettingsController.java   View source code 6 votes vote down vote up
/**
 * This method activates the e-mail change using a token
 * @param token E-mail change activation token
 * @param uriComponentsBuilder {@link UriComponentsBuilder}
 * @return The ModelAndView for sign in
 */
@PreAuthorize("permitAll()")
@GetMapping(value = "changeEmail/thanks")
public
ModelAndView confirmEmail(
        @RequestParam final String token,
        final UriComponentsBuilder uriComponentsBuilder
) {
    SSLContextHelper.disable();

    final RestTemplate restTemplate = new RestTemplate();
    final HttpEntity<Object> entity = new HttpEntity<>(new HttpHeaders());

    final UriComponents uriComponents
            = uriComponentsBuilder.path("/api/v1.0/settings/changeEmail/token/{token}").buildAndExpand(token);

    ResponseEntity<Void> response;

    try {
        response = restTemplate
                .exchange(uriComponents.toUri(),
                          HttpMethod.PUT,
                          entity,
                          Void.class);
    } catch (HttpClientErrorException e) /* IF 404 */ {
        return new ModelAndView("tokenNotFound");
    }

    /* IF 200 */
    return new ModelAndView("redirect:/signIn");
}
 
Example 11
Project: twitch4j   File: UserEndpoint.java   View source code 6 votes vote down vote up
/**
 * Endpoint to get the UserId from the UserName
 * <p>
 * https://api.twitch.tv/kraken/users?login=USERNAME
 *
 * @param userName todo
 * @return todo
 */
public Optional<Long> getUserIdByUserName(String userName) {
	// Validate Arguments
	Assert.hasLength(userName, "Please provide a Username!");

	// REST Request
	String requestUrl = String.format("%s/users?login=%s", Endpoints.API.getURL(), userName);
	RestTemplate restTemplate = getTwitchClient().getRestClient().getRestTemplate();

	// REST Request
	if (!restObjectCache.containsKey(requestUrl)) {
		try {
			UserList responseObject = restTemplate.getForObject(requestUrl, UserList.class);
			restObjectCache.put(requestUrl, responseObject, 15, TimeUnit.MINUTES);
		} catch (RestException restException) {
			Logger.error(this, "RestException: " + restException.getRestError().toString());
		} catch (Exception ex) {
			Logger.error(this, "Request failed: " + ex.getMessage());
			Logger.trace(this, ExceptionUtils.getStackTrace(ex));
			return Optional.empty();
		}
	}

	List<User> userList = ((UserList) restObjectCache.get(requestUrl)).getUsers();

	// User found?
	if (userList.size() == 1) {
		return Optional.ofNullable(userList.get(0).getId());
	} else {
		return Optional.empty();
	}
}
 
Example 12
Project: twitch4j   File: KrakenEndpoint.java   View source code 6 votes vote down vote up
/**
 * Endpoint: Get OAuth Token Information
 * Gets information about the provided oAuthToken
 * Requires Scope: none
 *
 * @param credential The credential the information should be fetched for.
 * @return Information about the user, that issued the token - also provides info about scopes/valid/etc.
 * @see Token
 */
public Token getToken(OAuthCredential credential) {
	// Endpoint
	String requestUrl = String.format("%s", Endpoints.API.getURL());
	RestTemplate restTemplate = getTwitchClient().getRestClient().getPrivilegedRestTemplate(credential);

	// REST Request
	try {
		TokenResponse responseObject = restTemplate.getForObject(requestUrl, TokenResponse.class);

		return responseObject.getToken();
	} catch (RestException restException) {
		Logger.error(this, "RestException: " + restException.getRestError().toString());
	} catch (Exception ex) {
		Logger.error(this, "Request failed: " + ex.getMessage());
		Logger.trace(this, ExceptionUtils.getStackTrace(ex));
	}

	// Default Response: Invalid Token
	return new Token();
}
 
Example 13
Project: shoucang   File: MailService.java   View source code 5 votes vote down vote up
public void sendViaMailgunApi(EmailParams emailParams) {
    String apiUrl = jHipsterProperties.getMailgun().getApiUrl();
    String apiKey = jHipsterProperties.getMailgun().getApiKey();

    MultiValueMap<String, Object> vars = new LinkedMultiValueMap<>();
    vars.add("from", jHipsterProperties.getMailgun().getFrom());
    vars.add("to", emailParams.getTo());
    vars.add("subject", emailParams.getSubject());
    vars.add("html", emailParams.getContent());

    RestTemplate restTemplate = new BasicAuthRestTemplate(MAILGUN_USER_NAME, apiKey);
    restTemplate.postForLocation(apiUrl, vars);

    log.debug("Email sent successfully.");
}
 
Example 14
Project: csap-core   File: HttpCollector.java   View source code 5 votes vote down vote up
private RestTemplate getRestTemplate ( long maxConnectionInMs, JsonNode user, JsonNode pass, String desc ) {

		logger.debug( "maxConnectionInMs: {} , user: {} , Pass: {} ", maxConnectionInMs, user, pass );

		HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();

		// "user" : "$csapUser1", "pass" : "$csapPass1"
		if ( user != null && pass != null ) {
			CredentialsProvider credsProvider = new BasicCredentialsProvider();
			credsProvider.setCredentials(
				new AuthScope( null, -1 ),
				new UsernamePasswordCredentials(
					user.asText(),
					csapApplication.decode( pass.asText(), desc ) ) );

			HttpClient httpClient = HttpClients
				.custom()
				.setDefaultCredentialsProvider( credsProvider )
				.build();
			factory.setHttpClient( httpClient );
			// factory = new HttpComponentsClientHttpRequestFactory(httpClient);
		}

		factory.setConnectTimeout( (int) maxConnectionInMs );
		factory.setReadTimeout( (int) maxConnectionInMs );

		RestTemplate restTemplate = new RestTemplate( factory );

		return restTemplate;
	}
 
Example 15
Project: loom   File: SwiftContainersImpl.java   View source code 5 votes vote down vote up
private List<JsonContainer> getMore(final RestTemplate rt, final String url, final JsonContainer last)
        throws URISyntaxException, UnsupportedEncodingException {
    String params = url.contains("?") ? "&" : "?";
    String newUrl = url + params + "marker=" + URLEncoder.encode(last.getName(), "UTF-8");
    URI keystoneURI = new URI(newUrl);
    JsonContainer[] data = getResourcesFromGet(rt, keystoneURI);
    List<JsonContainer> list = new ArrayList<>();
    list.addAll(Arrays.asList(data));
    if (data.length != 0) {
        // check for more
        List<JsonContainer> extra = getMore(rt, url, data[data.length - 1]);
        list.addAll(extra);
    }
    return list;
}
 
Example 16
Project: spring-cloud-skipper   File: DefaultSkipperClientTests.java   View source code 5 votes vote down vote up
@Test
public void testStatusReleaseNameFound() {
	RestTemplate restTemplate = new RestTemplate();
	SkipperClient skipperClient = new DefaultSkipperClient("", restTemplate);

	MockRestServiceServer mockServer = MockRestServiceServer.bindTo(restTemplate).build();
	mockServer.expect(requestTo("/release/status/mylog")).andRespond(withSuccess("{}", MediaType.APPLICATION_JSON));

	Info status = skipperClient.status("mylog");
	mockServer.verify();

	assertThat(status).isNotNull();
	assertThat(status).isInstanceOf(Info.class);
}
 
Example 17
Project: keti   File: AccessControlServiceIT.java   View source code 5 votes vote down vote up
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();
}
 
Example 18
Project: incubator-servicecomb-java-chassis   File: RestTemplateWrapper.java   View source code 5 votes vote down vote up
RestTemplate getRestTemplate(String url) {
  for (AcceptableRestTemplate template : acceptableRestTemplates) {
    if (template.isAcceptable(url)) {
      return template;
    }
  }
  return defaultRestTemplate;
}
 
Example 19
Project: incubator-servicecomb-java-chassis   File: CodeFirstRestTemplateSpringmvc.java   View source code 5 votes vote down vote up
private void testUpload(RestTemplate template, String cseUrlPrefix) throws IOException {
  String file1Content = "hello world";
  File file1 = File.createTempFile("upload1", ".txt");
  FileUtils.writeStringToFile(file1, file1Content);

  String file2Content = " bonjour";
  File someFile = File.createTempFile("upload2", ".txt");
  FileUtils.writeStringToFile(someFile, file2Content);

  String expect = String.format("%s:%s:%s\n"
      + "%s:%s:%s",
      file1.getName(),
      MediaType.TEXT_PLAIN_VALUE,
      file1Content,
      someFile.getName(),
      MediaType.TEXT_PLAIN_VALUE,
      file2Content);

  String result = testRestTemplateUpload(template, cseUrlPrefix, file1, someFile);
  TestMgr.check(expect, result);

  result = uploadPartAndFile.fileUpload(new FilePart(null, file1), someFile);
  TestMgr.check(expect, result);

  expect = String.format("null:%s:%s\n"
      + "%s:%s:%s",
      MediaType.APPLICATION_OCTET_STREAM_VALUE,
      file1Content,
      someFile.getName(),
      MediaType.TEXT_PLAIN_VALUE,
      file2Content);
  result = uploadStreamAndResource
      .fileUpload(new ByteArrayInputStream(file1Content.getBytes(StandardCharsets.UTF_8)),
          new PathResource(someFile.getAbsolutePath()));
  TestMgr.check(expect, result);
}
 
Example 20
Project: poppynotes   File: TestConfig.java   View source code 5 votes vote down vote up
@Primary
@Bean(name="testRestTemplate")
RestTemplate restTemplate() {
	RestTemplate template = new RestTemplate();
	template.setErrorHandler(getResponseErrorHandler());

	return template;
}
 
Example 21
Project: spring-cloud-master   File: TestController.java   View source code 5 votes vote down vote up
/**
 * 采用 RestTemplate 方式调用(HTTP方式调用,与 Spring Cloud 调用服务没有一点关系)
 * 
 * @param name
 * @return
 */
@RequestMapping(value = "callByHttpUrl", method = RequestMethod.GET)
public String callByHttpUrl(String name) {
	RestTemplate restTemplate = new RestTemplate();
	ResponseEntity<String> response = restTemplate.getForEntity("http://localhost:8001/sayHello?name=" + name,
			String.class);
	return response.getBody();
}
 
Example 22
Project: resilient-transport-service   File: AddressCommand.java   View source code 5 votes vote down vote up
public AddressCommand(AddressDTO addressDTO, RestTemplate restTemplate, boolean secondTry) {
    super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("AddressServiceClientGroup"))
        .andCommandKey(HystrixCommandKey.Factory.asKey("AddressServiceClient")));

    this.addressDTO = addressDTO;
    this.restTemplate = restTemplate;
    this.secondTry = secondTry;
}
 
Example 23
Project: loom   File: NeutronNetworksImpl.java   View source code 5 votes vote down vote up
@Override
public JsonNetworks createNetworks(final JsonNetworks networks) {
    String url = getUri();
    RestTemplate rt = getRestTemplate(jsonEndpoint.getProjectId());
    ResponseEntity<JsonNetworks> result = rt.postForEntity(url, networks, JsonNetworks.class);

    return result.getBody();
}
 
Example 24
Project: cas-5.1.0   File: RestMultifactorAuthenticationTrustStorage.java   View source code 5 votes vote down vote up
@Override
protected MultifactorAuthenticationTrustRecord setInternal(final MultifactorAuthenticationTrustRecord record) {
    final RestTemplate restTemplate = new RestTemplate();
    final ResponseEntity<Object> response = restTemplate.postForEntity(this.endpoint, record, Object.class);
    if (response != null && response.getStatusCode() == HttpStatus.OK) {
        return record;
    }
    return null;
}
 
Example 25
Project: mirrorgate-jira-stories-collector   File: Config.java   View source code 5 votes vote down vote up
@Bean(MIRRORGATE_REST_TEMPLATE)
public RestTemplate getRestTemplate() {
    RestTemplate restTemplate = new RestTemplate();
    MappingJackson2HttpMessageConverter jsonHttpMessageConverter = new MappingJackson2HttpMessageConverter();
    restTemplate.getMessageConverters().add(jsonHttpMessageConverter);
    if(mirrorGateUserName.isPresent() && !mirrorGateUserName.get().isEmpty()) {
        restTemplate.getInterceptors().add(
                new BasicAuthorizationInterceptor(mirrorGateUserName.get(), mirrorGatePassword.get()));
    }

    return restTemplate;
}
 
Example 26
Project: twitch4j   File: ChannelEndpoint.java   View source code 5 votes vote down vote up
/**
 * Endpoint: Get Channel Editors
 * Gets a list of users who are editors for a specified channel.
 * Requires Scope: channel_read
 *
 * @return todo
 */
public List<User> getEditors() {
	// Check Scope
	Optional<OAuthCredential> twitchCredential = getTwitchClient().getCredentialManager().getTwitchCredentialsForChannel(getChannelId());
	if (twitchCredential.isPresent()) {
		Set<String> requiredScopes = new HashSet<String>();
		requiredScopes.add(TwitchScopes.CHANNEL_READ.getKey());

		checkScopePermission(twitchCredential.get().getOAuthScopes(), requiredScopes);
	} else {
		throw new ChannelCredentialMissingException(getChannelId());
	}

	// Endpoint
	String requestUrl = String.format("%s/channels/%s/editors", Endpoints.API.getURL(), getChannelId());
	RestTemplate restTemplate = getTwitchClient().getRestClient().getRestTemplate();

	// REST Request
	try {
		UserList responseObject = restTemplate.getForObject(requestUrl, UserList.class);

		return responseObject.getUsers();
	} catch (Exception ex) {
		Logger.error(this, "Request failed: " + ex.getMessage());
		Logger.trace(this, ExceptionUtils.getStackTrace(ex));
		return null;
	}
}
 
Example 27
Project: java-spring-web   File: AbstractTracingClientTest.java   View source code 5 votes vote down vote up
@Test
public void testErrorUnknownHostException() {
    String url = "http://nonexisting.example.com";
    try {
        RestTemplate restTemplate = new RestTemplate();
        restTemplate.setInterceptors(Collections.<ClientHttpRequestInterceptor>singletonList(
                new TracingRestTemplateInterceptor(mockTracer)));
        restTemplate.getForEntity(url, String.class);
    } catch (ResourceAccessException ex) {
        //ok UnknownHostException
    }

    List<MockSpan> mockSpans = mockTracer.finishedSpans();
    Assert.assertEquals(1, mockSpans.size());

    MockSpan mockSpan = mockSpans.get(0);
    Assert.assertEquals("GET", mockSpan.operationName());
    Assert.assertEquals(5, mockSpan.tags().size());
    Assert.assertEquals(RestTemplateSpanDecorator.StandardTags.COMPONENT_NAME,
            mockSpan.tags().get(Tags.COMPONENT.getKey()));
    Assert.assertEquals(Tags.SPAN_KIND_CLIENT, mockSpan.tags().get(Tags.SPAN_KIND.getKey()));
    Assert.assertEquals("GET", mockSpan.tags().get(Tags.HTTP_METHOD.getKey()));
    Assert.assertEquals(url, mockSpan.tags().get(Tags.HTTP_URL.getKey()));
    Assert.assertEquals(Boolean.TRUE, mockSpan.tags().get(Tags.ERROR.getKey()));

    Assert.assertEquals(1, mockSpan.logEntries().size());
    Assert.assertEquals(2, mockSpan.logEntries().get(0).fields().size());
    Assert.assertEquals(Tags.ERROR.getKey(), mockSpan.logEntries().get(0).fields().get("event"));
    Assert.assertNotNull(mockSpan.logEntries().get(0).fields().get("error.object"));
}
 
Example 28
Project: referenceapp   File: ApplicationTests.java   View source code 5 votes vote down vote up
@Test
public void loginSucceeds() {
    RestTemplate template = new TestRestTemplate("user", "foo");
    ResponseEntity<String> response = template.getForEntity("http://localhost:" + port
            + "/user", String.class);
    assertEquals(HttpStatus.OK, response.getStatusCode());
}
 
Example 29
Project: c4sg-services   File: GithubUtil.java   View source code 5 votes vote down vote up
public static List<Stat.Author> getContributorsByCommitsDesc() throws IOException {
    RestTemplate restTemplate = new RestTemplate();
    ResponseEntity<Stat[]> exchange = restTemplate.
            exchange("https://api.github.com/repos/"
                    + githubUsername + "/" + githubReponame + "/stats/contributors", HttpMethod.GET, null, Stat[].class);
    Stat[] stats = exchange.getBody();
    List<Stat.Author> contributors = new ArrayList<>(stats.length);
    for (Stat s : stats) {
        Stat.Author author = s.getAuthor();
        author.setCommits(s.getTotal());
        contributors.add(0, author);
    }
    return contributors;
}
 
Example 30
Project: xitikit-blue   File: AzureGraphApiClient.java   View source code 5 votes vote down vote up
public AzureGraphApiClient(
    final RestTemplate restTemplate,
    final IAzureCustomAttributeCacheService azureCustomAttributeCacheService,
    final GraphApiClientProperties graphApiClientProperties){

    this.restTemplate = restTemplate;
    this.azureCustomAttributeCacheService = azureCustomAttributeCacheService;
    this.graphApiClientProperties = graphApiClientProperties;
}
 
Example 31
Project: xm-uaa   File: TwitterTemplate.java   View source code 5 votes vote down vote up
@Override
public RestTemplate getRestTemplate() {
    if (clientRestTemplate != null) {
        return clientRestTemplate;
    }
    return super.getRestTemplate();
}
 
Example 32
Project: loom   File: PagingBase.java   View source code 5 votes vote down vote up
protected void processNext(final R result, final RestTemplate rt) {
    String nextUrl = getNext(result);
    if (nextUrl != null) {
        R nextResults = getJsonResources(rt, nextUrl);
        addToResult(result, nextResults);
    }
}
 
Example 33
Project: amazon-ecs-java-microservices   File: OwnerController.java   View source code 5 votes vote down vote up
private List<Visit> getPetVisits(int petId){
    List<Visit> visitList = new ArrayList<Visit>();
    RestTemplate restTemplate = new RestTemplate();
    Pet pet = restTemplate.getForObject("http://"+serviceEndpoint+"/pet/"+petId, Pet.class);
    logger.info(pet.getVisits().toString());
    return pet.getVisits();
}
 
Example 34
Project: crnk-framework   File: BasicSpringBootTest.java   View source code 5 votes vote down vote up
@Test
public void testTestCustomEndpoint() {
	RestTemplate testRestTemplate = new RestTemplate();
	ResponseEntity<String> response = testRestTemplate
			.getForEntity("http://localhost:" + this.port + "/api/custom", String.class);
	assertEquals(HttpStatus.OK, response.getStatusCode());
	assertEquals(response.getBody(), "hello");
}
 
Example 35
Project: microservice-cloudfoundry   File: CustomerClient.java   View source code 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 36
Project: cas-5.1.0   File: RestGoogleAuthenticatorTokenCredentialRepository.java   View source code 5 votes vote down vote up
public RestGoogleAuthenticatorTokenCredentialRepository(final IGoogleAuthenticator googleAuthenticator,
                                                        final RestTemplate restTemplate,
                                                        final MultifactorAuthenticationProperties.GAuth gauth) {
    this.googleAuthenticator = googleAuthenticator;
    this.restTemplate = restTemplate;
    this.gauth = gauth;
}
 
Example 37
Project: spring-cloud-master   File: RetryApplication.java   View source code 5 votes vote down vote up
@Bean
@LoadBalanced // 自动负载均衡:他的机制是(通过)Application Name去寻找服务发现,然后去做负载均衡策略的
public RestTemplate restTemplate() {
    // HttpComponentsClientHttpRequestFactory httpRequestFactory = new
    // HttpComponentsClientHttpRequestFactory();
    // httpRequestFactory.setConnectionRequestTimeout(1000);
    // httpRequestFactory.setConnectTimeout(1000);
    // httpRequestFactory.setReadTimeout(3000);
    return new RestTemplate(httpRequestFactory());
}
 
Example 38
Project: spring-credhub   File: CredHubClient.java   View source code 5 votes vote down vote up
/**
 * Create a {@link RestTemplate} configured for communication with a CredHub server.
 *
 * @param baseUri the base URI for the CredHub server
 * @param clientHttpRequestFactory the {@link ClientHttpRequestFactory} to use when
 * creating new connections
 * @return a configured {@link RestTemplate}
 */
public static RestTemplate createRestTemplate(String baseUri,
		ClientHttpRequestFactory clientHttpRequestFactory) {
	RestTemplate restTemplate = new RestTemplate();

	configureRestTemplate(restTemplate, baseUri, clientHttpRequestFactory);

	return restTemplate;
}
 
Example 39
Project: keti   File: PolicyEvaluationWithAttributeConnectorIT.java   View source code 5 votes vote down vote up
private void setRestTemplateInterceptor(final RestTemplate restTemplate) {
    restTemplate.setInterceptors(Collections.singletonList(
            new TraceRestTemplateInterceptor(this.tracer, new ZipkinHttpSpanInjector(),
                    new HttpTraceKeysInjector(this.tracer, new TraceKeys()))));
}
 
Example 40
Project: Sound.je   File: FacebookReader.java   View source code 5 votes vote down vote up
/**
 * This is the method that actually makes the http request
 *
 * @param url              request url
 * @param deconstructClass class of request object
 * @param <T>              type of request object this is
 * @return request object
 */
private <T> T request(final String url, final Class<T> deconstructClass) {
    final RestTemplate restTemplate = new RestTemplate();
    T deconstructedResponse = null;

    try {
        deconstructedResponse = restTemplate.getForObject(url, deconstructClass);
    } catch (HttpClientErrorException err) {
        logger.info("[FacebookReader] [request] Failure To Retrieve Facebook Resource (" + url + ")", err);
    }

    return deconstructedResponse;
}