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: websocket-poc   File: App.java   Source Code and License 9 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 2
Project: twitch4j   File: TMIEndpoint.java   Source Code and License 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 3
Project: REST-Web-Services   File: SettingsController.java   Source Code and License 8 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 4
Project: incubator-servicecomb-java-chassis   File: JaxrsClient.java   Source Code and License 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 5
Project: twitch4j   File: StreamEndpoint.java   Source Code and License 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 6
Project: waggle-dance   File: WaggleDanceIntegrationTest.java   Source Code and License 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 7
Project: java-spring-web   File: TracingRestTemplateTest.java   Source Code and License 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 8
Project: xitikit-blue   File: SimpleB2CAuthenticationService.java   Source Code and License 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 9
Project: spring-cloud-master   File: RetryApplication.java   Source Code and License 6 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 10
Project: twitch4j   File: StreamEndpoint.java   Source Code and License 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 11
Project: esup-ecandidat   File: LimeSurveyRest.java   Source Code and License 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 12
Project: twitch4j   File: KrakenEndpoint.java   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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   Source Code and License 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: referenceapp   File: ApplicationTests.java   Source Code and License 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 28
Project: c4sg-services   File: GithubUtil.java   Source Code and License 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 29
Project: xitikit-blue   File: AzureGraphApiClient.java   Source Code and License 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 30
Project: xm-uaa   File: TwitterTemplate.java   Source Code and License 5 votes vote down vote up
@Override
public RestTemplate getRestTemplate() {
    if (clientRestTemplate != null) {
        return clientRestTemplate;
    }
    return super.getRestTemplate();
}
 
Example 31
Project: loom   File: PagingBase.java   Source Code and License 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 32
Project: amazon-ecs-java-microservices   File: OwnerController.java   Source Code and License 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 33
Project: crnk-framework   File: BasicSpringBootTest.java   Source Code and License 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 34
Project: microservice-cloudfoundry   File: CustomerClient.java   Source Code and License 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 35
Project: cas-5.1.0   File: RestGoogleAuthenticatorTokenCredentialRepository.java   Source Code and License 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 36
Project: spring-credhub   File: CredHubClient.java   Source Code and License 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 37
Project: keti   File: PolicyEvaluationWithAttributeConnectorIT.java   Source Code and License 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 38
Project: Sound.je   File: FacebookReader.java   Source Code and License 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;
}
 
Example 39
Project: xm-ms-balance   File: MicroserviceSecurityConfiguration.java   Source Code and License 5 votes vote down vote up
@Bean
public JwtAccessTokenConverter jwtAccessTokenConverter(
        @Qualifier("loadBalancedRestTemplate") RestTemplate keyUriRestTemplate) throws CertificateException {

    JwtAccessTokenConverter converter = new DomainJwtAccessTokenConverter();
    converter.setVerifierKey(getKeyFromAuthorizationServer(keyUriRestTemplate));
    return converter;
}
 
Example 40
Project: be.liege.cti.ged   File: SearchBuilderImpl.java   Source Code and License 5 votes vote down vote up
public SearchBuilderImpl(final NodeReferenceBuilder nodeReferenceBuilder,
                         final String url,
                         final RestTemplate restTemplate) {
    this.nodeReferenceBuilder = nodeReferenceBuilder;
    this.url = url;
    this.restTemplate = restTemplate;
}
 
Example 41
Project: loom   File: NeutronSubnetsImpl.java   Source Code and License 5 votes vote down vote up
@Override
public JsonSubnets createSubnets(final JsonSubnets subnets) {
    String url = getUri();
    RestTemplate rt = getRestTemplate(jsonEndpoint.getProjectId());
    ResponseEntity<JsonSubnets> result = rt.postForEntity(url, subnets, JsonSubnets.class);

    return result.getBody();
}
 
Example 42
Project: sentry   File: GameQueryService.java   Source Code and License 5 votes vote down vote up
@Autowired
public GameQueryService(SteamWebApiClient steamWebApiClient, SettingService settingService, RestTemplate restTemplate) {
    this.steamWebApiClient = steamWebApiClient;
    this.settingService = settingService;
    this.restTemplate = restTemplate;
    this.steamApps = new SteamApps(steamWebApiClient);
    this.steamUser = new SteamUser(steamWebApiClient);
    this.sourceQueryClient = new SourceQueryClient();
    this.sourceRconClient = new SourceRconClient();
}
 
Example 43
Project: microservice-kubernetes   File: CustomerClient.java   Source Code and License 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 44
Project: che-starter   File: WorkspaceClient.java   Source Code and License 5 votes vote down vote up
/**
 * Create workspace on the Che server with given URL.
 * 
 * @param cheServerUrl
 * @param keycloakToken
 * @param name
 * @param stackId
 * @param repo
 * @param branch
 * @return
 * @throws StackNotFoundException
 * @throws IOException
 * @throws URISyntaxException 
 */
public Workspace createWorkspace(String cheServerURL, String keycloakToken, String stackId, String repo,
        String branch, String description) throws StackNotFoundException, IOException, URISyntaxException {
    String url = CheRestEndpoints.CREATE_WORKSPACE.generateUrl(cheServerURL);
    WorkspaceConfig wsConfig = stackClient.getStack(cheServerURL, stackId, keycloakToken).getWorkspaceConfig();

    String projectName = projectHelper.getProjectNameFromGitRepository(repo);
    String projectType = stackClient.getProjectTypeByStackId(stackId);

    LOG.info("Stack: {}", stackId);
    LOG.info("Project type: {}", projectType);

    Project project = projectHelper.initProject(projectName, repo, branch, projectType);

    wsConfig.setProjects(Collections.singletonList(project));
    wsConfig.setName(workspaceHelper.generateName(projectName));
    wsConfig.setDescription(description);

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

    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;
}
 
Example 45
Project: twitch4j   File: UserEndpoint.java   Source Code and License 5 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 46
Project: sentry   File: ApplicationTemplate.java   Source Code and License 4 votes vote down vote up
public ApplicationTemplate(RestTemplate restTemplate, boolean isAuthorized) {
    super(restTemplate, isAuthorized);
}
 
Example 47
Project: JRockets   File: Authentication.java   Source Code and License 4 votes vote down vote up
public Authentication() {
    restTemplate = new RestTemplate();
    this.token = null;
}
 
Example 48
Project: geocoder-microservices   File: DiscoveryTest.java   Source Code and License 4 votes vote down vote up
@Test
public void dicoverEurekaTest() throws Exception {
	RestTemplate restTemplate = new RestTemplate();
	String retour = restTemplate.getForObject("http://localhost:8761/env", String.class);
	assertTrue(retour.contains("{\"local.server.port\":8761}"));
}
 
Example 49
Project: loom   File: PagingBase.java   Source Code and License 4 votes vote down vote up
protected RestTemplate getRestTemplate(final String projectId) {
    return openstackApp.getRestTemplateWithScopedToken(projectId);
}
 
Example 50
Project: spring-cloud-dashboard   File: ConfigCommands.java   Source Code and License 4 votes vote down vote up
@Bean
public RestTemplate restTemplate(Environment ev) {
	return DataFlowTemplate.getDefaultDataflowRestTemplate();
}
 
Example 51
Project: spring-cloud-skipper   File: TargetHolder.java   Source Code and License 4 votes vote down vote up
public TargetHolder(RestTemplate restTemplate) {
	this.restTemplate = restTemplate;
}
 
Example 52
Project: edoras-one-initializr   File: DefaultInitializrMetadataProvider.java   Source Code and License 4 votes vote down vote up
public DefaultInitializrMetadataProvider(InitializrMetadata metadata,
		RestTemplate restTemplate) {
	this.metadata = metadata;
	this.restTemplate = restTemplate;
}
 
Example 53
Project: edoras-one-initializr   File: EdorasoneMetadataReader.java   Source Code and License 4 votes vote down vote up
/**
 * Parse the content of the metadata at the specified url
 */
public EdorasoneMetadataReader(RestTemplate restTemplate, String url) {
	this.content = new JSONObject(restTemplate.getForObject(url, String.class));
}
 
Example 54
Project: incubator-servicecomb-java-chassis   File: CodeFirstRestTemplate.java   Source Code and License 4 votes vote down vote up
protected void testRawJson(RestTemplate template, String cseUrlPrefix) {
  String input = "{\"name\" : \"zyy\"}";
  String output = template.postForObject(cseUrlPrefix + "rawJsonAnnotation", input, String.class);
  TestMgr.check("hello zyy", output);
}
 
Example 55
Project: playground-scenario-generator   File: ScenarioGeneratorApplication.java   Source Code and License 4 votes vote down vote up
@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder) {
    return builder.errorHandler(new RestTemplateErrorHandler()).build();
}
 
Example 56
Project: xm-ms-balance   File: MicroserviceSecurityConfiguration.java   Source Code and License 4 votes vote down vote up
@Bean
public RestTemplate loadBalancedRestTemplate(RestTemplateCustomizer customizer) {
    RestTemplate restTemplate = new RestTemplate();
    customizer.customize(restTemplate);
    return restTemplate;
}
 
Example 57
Project: quickmon   File: PlayWithSpel.java   Source Code and License 4 votes vote down vote up
public static void main(String[] args) throws Exception {
        RestTemplate rt = new RestTemplate();
        ResponseEntity<String> response = rt.getForEntity("http://aft.users-api.test.paas/health", String.class);

        StandardEvaluationContext ctx = new StandardEvaluationContext(response);
        ctx.registerFunction("extractFromJson", SpelExtensions.class.getMethod("extractFromJson", String.class, String.class));

        System.out.println(evaluate(ctx, "#root.statusCodeValue == 200"));
        System.out.println(evaluate(ctx, "#extractFromJson(#root.body, 'status') == 'UP'"));
        System.out.println(evaluate(ctx, "#root.headers['X-RID'] != null"));




//        System.out.println(read);
    }
 
Example 58
Project: Mastering-Microservices-with-Java-9-Second-Edition   File: ApiApp.java   Source Code and License 4 votes vote down vote up
@LoadBalanced
@Bean
RestTemplate restTemplate() {
    return new RestTemplate();
}
 
Example 59
Project: concurrency-demo   File: Controller.java   Source Code and License 4 votes vote down vote up
public Controller(RestTemplate restTemplate) {
  this.restTemplate = restTemplate;
}
 
Example 60
Project: apollo-custom   File: ItemSetControllerTest.java   Source Code and License 4 votes vote down vote up
@Test
@Sql(scripts = "/controller/test-itemset.sql", executionPhase = ExecutionPhase.BEFORE_TEST_METHOD)
@Sql(scripts = "/controller/cleanup.sql", executionPhase = ExecutionPhase.AFTER_TEST_METHOD)
public void testItemSetUpdated() {
  String appId = "someAppId";
  AppDTO app =
      restTemplate.getForObject("http://localhost:" + port + "/apps/" + appId, AppDTO.class);

  ClusterDTO cluster = restTemplate.getForObject(
      "http://localhost:" + port + "/apps/" + app.getAppId() + "/clusters/default",
      ClusterDTO.class);

  NamespaceDTO namespace =
      restTemplate.getForObject("http://localhost:" + port + "/apps/" + app.getAppId()
          + "/clusters/" + cluster.getName() + "/namespaces/application", NamespaceDTO.class);

  Assert.assertEquals("someAppId", app.getAppId());
  Assert.assertEquals("default", cluster.getName());
  Assert.assertEquals("application", namespace.getNamespaceName());

  ItemChangeSets createChangeSet = new ItemChangeSets();
  createChangeSet.setDataChangeLastModifiedBy("created");
  RestTemplate createdRestTemplate = new TestRestTemplate("created", "");
  createdRestTemplate.setMessageConverters(restTemplate.getMessageConverters());
  
  int createdSize = 3;
  for (int i = 0; i < createdSize; i++) {
    ItemDTO item = new ItemDTO();
    item.setNamespaceId(namespace.getId());
    item.setKey("key_" + i);
    item.setValue("created_value_" + i);
    createChangeSet.addCreateItem(item);
  }

  ResponseEntity<Void> response = createdRestTemplate.postForEntity(
      "http://localhost:" + port + "/apps/" + app.getAppId() + "/clusters/" + cluster.getName()
          + "/namespaces/" + namespace.getNamespaceName() + "/itemset",
      createChangeSet, Void.class);
  Assert.assertEquals(HttpStatus.OK, response.getStatusCode());

  ItemDTO[] items =
      createdRestTemplate.getForObject(
          "http://localhost:" + port + "/apps/" + app.getAppId() + "/clusters/"
              + cluster.getName() + "/namespaces/" + namespace.getNamespaceName() + "/items",
          ItemDTO[].class);

  ItemChangeSets updateChangeSet = new ItemChangeSets();
  updateChangeSet.setDataChangeLastModifiedBy("updated");

  RestTemplate updatedRestTemplate = new TestRestTemplate("updated", "");
  updatedRestTemplate.setMessageConverters(restTemplate.getMessageConverters());
  
  int updatedSize = 2;
  for (int i = 0; i < updatedSize; i++) {
    items[i].setValue("updated_value_" + i);
    updateChangeSet.addUpdateItem(items[i]);
  }

  response = updatedRestTemplate.postForEntity(
      "http://localhost:" + port + "/apps/" + app.getAppId() + "/clusters/" + cluster.getName()
          + "/namespaces/" + namespace.getNamespaceName() + "/itemset",
      updateChangeSet, Void.class);
  Assert.assertEquals(HttpStatus.OK, response.getStatusCode());
  List<Item> savedItems = itemRepository.findByNamespaceIdOrderByLineNumAsc(namespace.getId());
  Assert.assertEquals(createdSize, savedItems.size());
  Item item0 = savedItems.get(0);
  Assert.assertEquals("key_0", item0.getKey());
  Assert.assertEquals("updated_value_0", item0.getValue());
  Assert.assertEquals("created", item0.getDataChangeCreatedBy());
  Assert.assertEquals("updated", item0.getDataChangeLastModifiedBy());
  Assert.assertNotNull(item0.getDataChangeCreatedTime());
  Assert.assertNotNull(item0.getDataChangeLastModifiedTime());
}