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

The following examples show how to use org.springframework.web.client.RestTemplate. These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: Refactoring-Bot   Source File: GithubDataGrabber.java    License: MIT License 6 votes vote down vote up
/**
 * This method replies to a comment on Github.
 * 
 * @param comment
 * @param gitConfig
 * @param requestNumber
 * @throws URISyntaxException
 * @throws GitHubAPIException
 */
public void responseToBotComment(ReplyComment comment, GitConfiguration gitConfig, Integer requestNumber)
		throws URISyntaxException, GitHubAPIException {

	URI configUri = createURIFromApiLink(gitConfig.getRepoApiLink());

	// Build URI
	UriComponentsBuilder apiUriBuilder = UriComponentsBuilder.newInstance().scheme(configUri.getScheme())
			.host(configUri.getHost()).path(configUri.getPath() + "/pulls/" + requestNumber + "/comments");

	apiUriBuilder.queryParam("access_token", gitConfig.getBotToken());

	URI pullsUri = apiUriBuilder.build().encode().toUri();

	RestTemplate rest = new RestTemplate();

	try {
		// Send request to Github-API
		rest.exchange(pullsUri, HttpMethod.POST, new HttpEntity<>(comment), String.class);
	} catch (RestClientException e) {
		throw new GitHubAPIException("Could not reply to Github comment!", e);
	}
}
 
Example 2
Source Project: oneops   Source File: CMSClientTest.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void checkDeploymentTestWithRestTemplateThrowExceptionShouldSucced() throws Exception{
	DelegateExecution delegateExecution = mock(DelegateExecution.class);
	CmsDeployment cmsDeployment = new CmsDeployment();
	cmsDeployment.setCreatedBy("created-by-mock");
	when(delegateExecution.getVariable("dpmt")).thenReturn(cmsDeployment);

	RestTemplate restTemplate = mock(RestTemplate.class);
	//when(restTemplate.getForObject(anyString(), any(Class.class) , anyLong())).thenThrow(new RestClientException("test")).thenReturn(cmsDeployment);
	when(restTemplate.getForObject(anyString(), any(Class.class), anyLong())).thenThrow(new RestClientException("test")).thenThrow(new RestClientException("test")).thenReturn(cmsDeployment);
	cc.setRestTemplate(restTemplate);
	try {
		cc.setRetryTemplate(cc.getRetryTemplate(3,2000,1000));
		cc.checkDpmt(delegateExecution);
		CmsDeployment cmsDeploymentPost = (CmsDeployment) delegateExecution.getVariable("dpmt");
		assertEquals(cmsDeploymentPost.getCreatedBy(), "created-by-mock", "object mutated unexpectedly");

	} catch (GeneralSecurityException e) {
		logger.warn("unexpected to catch here",e) ;
		throw e;
	}
}
 
Example 3
Source Project: tutorials   Source File: LoginController.java    License: MIT License 6 votes vote down vote up
@GetMapping("/loginSuccess")
public String getLoginInfo(Model model, OAuth2AuthenticationToken authentication) {

    OAuth2AuthorizedClient client = authorizedClientService.loadAuthorizedClient(authentication.getAuthorizedClientRegistrationId(), authentication.getName());

    String userInfoEndpointUri = client.getClientRegistration()
        .getProviderDetails()
        .getUserInfoEndpoint()
        .getUri();

    if (!StringUtils.isEmpty(userInfoEndpointUri)) {
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.AUTHORIZATION, "Bearer " + client.getAccessToken()
            .getTokenValue());

        HttpEntity<String> entity = new HttpEntity<String>("", headers);

        ResponseEntity<Map> response = restTemplate.exchange(userInfoEndpointUri, HttpMethod.GET, entity, Map.class);
        Map userAttributes = response.getBody();
        model.addAttribute("name", userAttributes.get("name"));
    }

    return "loginSuccess";
}
 
Example 4
Source Project: h2o-2   Source File: h2oService.java    License: Apache License 2.0 6 votes vote down vote up
public String PredictGBM( String model, String new_data_key )  {

        //http://localhost:54321/2/Predict.html?model=gbmmodelDestinationKey&data=prostate_csv.hex&prediction=predict_1
        String status ;
        String inspect_status;
        String prediction_name = "Predict_GBM";
        String h2oUrlPredictEndPoint = H2O_HOST_URL + H2O_GBM_MODEL_PREDICT_URL + "model=" + model + "&data=" + new_data_key + "&prediction=" + prediction_name;
        System.out.println(h2oUrlPredictEndPoint);
        log.debug("@@@ Calling endpoint {}", h2oUrlPredictEndPoint);
        try {
            RestTemplate restTemplate = new RestTemplate();
            String responseBody = restTemplate.getForObject(h2oUrlPredictEndPoint, String.class);
            JSONObject jsonobject = new JSONObject(responseBody);
            JSONObject response_info = (JSONObject)jsonobject.get("response_info");
            status = (String)response_info.get("status");
            System.out.println("PREDICT GBM status: " + status);
            inspect_status = PredictGBMStatus(prediction_name);

        }catch(Exception ex){
            log.debug("!!!!!! Error Occurred while getting job status  {}", ex);
            ex.printStackTrace();
            return null;
        }
        return inspect_status;
    }
 
Example 5
private RestTemplate getSecureRestTemplate(ConfigClientProperties client) {
	SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
	if (client.getRequestReadTimeout() < 0) {
		throw new IllegalStateException("Invalid Value for Read Timeout set.");
	}
	if (client.getRequestConnectTimeout() < 0) {
		throw new IllegalStateException("Invalid Value for Connect Timeout set.");
	}
	requestFactory.setReadTimeout(client.getRequestReadTimeout());
	requestFactory.setConnectTimeout(client.getRequestConnectTimeout());
	RestTemplate template = new RestTemplate(requestFactory);
	Map<String, String> headers = new HashMap<>(client.getHeaders());
	if (headers.containsKey(AUTHORIZATION)) {
		headers.remove(AUTHORIZATION); // To avoid redundant addition of header
	}
	if (!headers.isEmpty()) {
		template.setInterceptors(Arrays.<ClientHttpRequestInterceptor>asList(
				new GenericRequestHeaderInterceptor(headers)));
	}

	return template;
}
 
Example 6
Source Project: WeEvent   Source File: Rest.java    License: Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) {
    System.out.println("This is WeEvent restful sample.");
    try {
        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
        RestTemplate rest = new RestTemplate(requestFactory);

        // ensure topic exist "com.weevent.test"
        String topic = "com.weevent.test";
        ResponseEntity<BaseResponse<Boolean>> rsp = rest.exchange("http://localhost:7000/weevent-broker/rest/open?topic={topic}&groupId={groupId}", HttpMethod.GET, null, new ParameterizedTypeReference<BaseResponse<Boolean>>() {
        }, topic, WeEvent.DEFAULT_GROUP_ID);
        System.out.println(rsp.getBody().getData());

        // publish event to topic "com.weevent.test"
        SendResult sendResult = rest.getForEntity("http://localhost:7000/weevent-broker/rest/publish?topic={topic}&groupId={groupId}&content={content}",
                SendResult.class,
                topic,
                WeEvent.DEFAULT_GROUP_ID,
                "hello WeEvent".getBytes(StandardCharsets.UTF_8)).getBody();
        System.out.println(sendResult);
    } catch (RestClientException e) {
        e.printStackTrace();
    }
}
 
Example 7
Source Project: servicecomb-java-chassis   Source File: JaxrsClient.java    License: Apache License 2.0 6 votes vote down vote up
private static void testSpringMvcDefaultValuesJavaPrimitiveRest(RestTemplate template) {
  String microserviceName = "jaxrs";
  String cseUrlPrefix = "cse://" + microserviceName + "/JaxRSDefaultValues/";

  HttpHeaders headers = new HttpHeaders();
  headers.setContentType(org.springframework.http.MediaType.APPLICATION_FORM_URLENCODED);
  MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
  HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers);

  //default values with primitive
  String result = template.postForObject(cseUrlPrefix + "/javaprimitiveint", request, String.class);
  TestMgr.check("Hello 0bobo", result);

  result = template.postForObject(cseUrlPrefix + "/javaprimitivenumber", request, String.class);
  TestMgr.check("Hello 0.0false", result);

  result = template.postForObject(cseUrlPrefix + "/javaprimitivestr", request, String.class);
  TestMgr.check("Hello", result);

  result = template.postForObject(cseUrlPrefix + "/javaprimitivecomb", request, String.class);
  TestMgr.check("Hello nullnull", result);

  result = template.postForObject(cseUrlPrefix + "/allprimitivetypes", null, String.class);
  TestMgr.check("Hello false,\0,0,0,0,0,0.0,0.0,null", result);
}
 
Example 8
Source Project: waggle-dance   Source File: WaggleDanceIntegrationTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void restApiGetStatus() throws Exception {
  runner = WaggleDanceRunner
      .builder(configLocation)
      .primary("primary", localServer.getThriftConnectionUri(), READ_ONLY)
      .federate(SECONDARY_METASTORE_NAME, remoteServer.getThriftConnectionUri(), REMOTE_DATABASE)
      .build();

  runWaggleDance(runner);

  RestTemplate rest = new RestTemplateBuilder().build();
  PrimaryMetaStore primaryMetastore = rest
      .getForObject("http://localhost:" + runner.getRestApiPort() + "/api/admin/federations/primary",
          PrimaryMetaStore.class);
  assertThat(primaryMetastore.getStatus(), is(MetaStoreStatus.AVAILABLE));
  FederatedMetaStore federatedMetastore = rest
      .getForObject(
          "http://localhost:" + runner.getRestApiPort() + "/api/admin/federations/" + SECONDARY_METASTORE_NAME,
          FederatedMetaStore.class);
  assertThat(federatedMetastore.getStatus(), is(MetaStoreStatus.AVAILABLE));
}
 
Example 9
Source Project: cubeai   Source File: UaaSignatureVerifierClient.java    License: Apache License 2.0 5 votes vote down vote up
public UaaSignatureVerifierClient(DiscoveryClient discoveryClient, @Qualifier("loadBalancedRestTemplate") RestTemplate restTemplate,
                              OAuth2Properties oAuth2Properties) {
    this.restTemplate = restTemplate;
    this.oAuth2Properties = oAuth2Properties;
    // Load available UAA servers
    discoveryClient.getServices();
}
 
Example 10
Source Project: bearchoke   Source File: QuotesWebSocketIntegrationTest.java    License: Apache License 2.0 5 votes vote down vote up
private static void loginAndSaveXAuthToken(final String user, final String password,
										   final HttpHeaders headersToUpdate) {

	log.info("Authenticating user before subscribing to web socket");

	String url = "http://dev.bearchoke.com:" + port + "/api/authenticate";

	try {
		new RestTemplate().execute(url, HttpMethod.POST,

				request -> {
					MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
					map.add("username", user);
					map.add("password", password);
					new FormHttpMessageConverter().write(map, MediaType.APPLICATION_FORM_URLENCODED, request);
				},

				response -> {
					String xAuthToken = response.getHeaders().getFirst(ServerConstants.X_AUTH_TOKEN);
					log.info("Retrieved x-auth-token: " + xAuthToken);
					headersToUpdate.add(ServerConstants.X_AUTH_TOKEN, xAuthToken);
					return null;
				});
	} catch (Exception ex) {
		log.error(ex.getMessage(), ex);
	}
}
 
Example 11
Source Project: Spring-Boot-Book   Source File: GetController.java    License: Apache License 2.0 5 votes vote down vote up
@RequestMapping("/withparameters1")
//返回String,带参数
public String withparameters1() {
    RestTemplate client= restTemplateBuilder.build();
    ResponseEntity<String> responseEntity = client.getForEntity("http://localhost:8080/getparameter?name={1}&id={2}", String.class, "hua",2);
    return responseEntity.getBody();
}
 
Example 12
Source Project: ddd-with-spring   Source File: CreditAgencyPoller.java    License: Apache License 2.0 5 votes vote down vote up
@Autowired
public CreditAgencyPoller(RestTemplate restTemplate, ScoringApplicationService scoringApplicationService) {
	this.lastModified = new Date();
	this.restTemplate = restTemplate;
	this.scoringApplicationService = scoringApplicationService;

}
 
Example 13
@Test
public void should_sample_non_actuator_endpoint() {
	new RestTemplate().getForObject("http://localhost:" + this.port + "/something",
			String.class);

	then(this.tracer.currentSpan()).isNull();
	then(this.spans).hasSize(1);
}
 
Example 14
@Test
public void testPrepareRestTemplateWithRestTemplateThatHasNoMessageConverters() {
	final RestTemplate providedRestTemplate = new RestTemplate();
	providedRestTemplate.getMessageConverters().clear();

	try {
		DataFlowTemplate.prepareRestTemplate(providedRestTemplate);
	}
	catch (IllegalArgumentException e) {
		assertEquals("'messageConverters' must not be empty", e.getMessage());
		return;
	}

	fail("Expected an IllegalArgumentException to be thrown.");
}
 
Example 15
Source Project: servicecomb-java-chassis   Source File: JaxrsClient.java    License: Apache License 2.0 5 votes vote down vote up
private static void testValidatorAddSuccess(RestTemplate template, String cseUrlPrefix) {
  Map<String, String> params = new HashMap<>();
  params.put("a", "5");
  params.put("b", "20");
  int result = template.postForObject(cseUrlPrefix + "add", params, Integer.class);
  TestMgr.check(25, result);
}
 
Example 16
Source Project: n2o-framework   Source File: DemoApplicationTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void pageWelcome() {
    RestTemplate restTemplate = new RestTemplate();
    Map<?, ?> result = restTemplate.getForObject("http://localhost:" + port + "/n2o/data/?size=10&page=1&sorting.birthday=ASC", Map.class);
    assertThat(result.get("list"), notNullValue());
    assertThat((Integer) result.get("count"), greaterThan(1));
    List<Map<?, ?>> list = (List<Map<?, ?>>) result.get("list");
    assertThat(list.size(), greaterThan(0));

    result = restTemplate.getForObject("http://localhost:" + port + "/n2o/data/1/contacts?size=10&page=1&individualId=1", Map.class);
    assertThat(result.get("list"), notNullValue());
    assertThat((Integer) result.get("count"), greaterThan(1));
    list = (List<Map<?, ?>>) result.get("list");
    assertThat(list.size(), lessThan(10));
}
 
Example 17
Source Project: NBANDROID-V2   Source File: BintraySearchProviderImpl.java    License: Apache License 2.0 5 votes vote down vote up
private void setTimeout(RestTemplate restTemplate, int connectTimeout, int readTimeout) {
    restTemplate.setRequestFactory(new SimpleClientHttpRequestFactory());
    SimpleClientHttpRequestFactory rf = (SimpleClientHttpRequestFactory) restTemplate
            .getRequestFactory();
    rf.setReadTimeout(readTimeout);
    rf.setConnectTimeout(connectTimeout);
}
 
Example 18
@Test
public void should_not_sample_actuator_endpoint() {
	new RestTemplate().getForObject(
			"http://localhost:" + this.port + "/actuator/health", String.class);

	then(this.tracer.currentSpan()).isNull();
	then(this.spans).hasSize(0);
}
 
Example 19
@Bean
public GrayClientHttpRequestIntercptor grayClientHttpRequestIntercptor(
        @Autowired(required = false) @LoadBalanced List<RestTemplate> restTemplates) {
    GrayClientHttpRequestIntercptor intercptor = new GrayClientHttpRequestIntercptor(
            grayRequestProperties, routingConnectionPoint);
    if (restTemplates != null) {
        restTemplates.forEach(restTemplate -> restTemplate.getInterceptors().add(intercptor));
    }
    return intercptor;
}
 
Example 20
@Before
public void setup() {
    RestTemplate restTemplate = new RestTemplate();
    mockServer = MockRestServiceServer.createServer(restTemplate);
    service = new ClusterProxyRegistrationClient(restTemplate);

    ClusterProxyConfiguration proxyConfig = spy(ClusterProxyConfiguration.class);
    ReflectionTestUtils.setField(proxyConfig, "clusterProxyUrl", CLUSTER_PROXY_URL);
    ReflectionTestUtils.setField(proxyConfig, "registerConfigPath", REGISTER_CONFIG_PATH);
    ReflectionTestUtils.setField(proxyConfig, "updateConfigPath", UPDATE_CONFIG_PATH);
    ReflectionTestUtils.setField(proxyConfig, "removeConfigPath", REMOVE_CONFIG_PATH);

    ReflectionTestUtils.setField(service, "clusterProxyConfiguration", proxyConfig);
}
 
Example 21
Source Project: ogham   Source File: SpringWebBeanResolutionTest.java    License: Apache License 2.0 5 votes vote down vote up
private ErrorDto getError() {
	RestTemplate rt = new RestTemplate();
	// @formatter:off
	UriComponentsBuilder builder = UriComponentsBuilder.fromPath("async/error")
			.scheme("http")
			.host("localhost")
			.port(port);
	// @formatter:on
	return rt.postForEntity(builder.toUriString(), new HttpEntity<>(""), ErrorDto.class).getBody();		
}
 
Example 22
@LoadBalanced
@Bean
public RestTemplate restTemplate() {
	SimpleClientHttpRequestFactory clientHttpRequestFactory = new SimpleClientHttpRequestFactory();
	clientHttpRequestFactory.setReadTimeout(1);
	clientHttpRequestFactory.setConnectTimeout(1);
	return new RestTemplate(clientHttpRequestFactory);
}
 
Example 23
public UaaAuthorizationHeaderUtil(ClientRegistrationRepository clientRegistrationRepository,
                                  OAuth2AuthorizedClientService clientRegistrationService,
                                  RestTemplate uaaRestTemplate) {
    this.uaaRestTemplate = uaaRestTemplate;
    this.clientRegistrationRepository = clientRegistrationRepository;
    this.clientRegistrationService = clientRegistrationService;
}
 
Example 24
@Before
public void setup() {
	List<HttpMessageConverter<?>> converters = new ArrayList<>();
	converters.add(new StringHttpMessageConverter());
	converters.add(new MappingJackson2HttpMessageConverter());

	this.restTemplate = new RestTemplate();
	this.restTemplate.setMessageConverters(converters);

	this.mockServer = MockRestServiceServer.createServer(this.restTemplate);
}
 
Example 25
public DataValueSynchronization( DataValueService dataValueService, DataValueSetService dataValueSetService,
    SystemSettingManager systemSettingManager, RestTemplate restTemplate )
{
    checkNotNull( dataValueService );
    checkNotNull( dataValueSetService );
    checkNotNull( systemSettingManager );
    checkNotNull( restTemplate );

    this.dataValueService = dataValueService;
    this.dataValueSetService = dataValueSetService;
    this.systemSettingManager = systemSettingManager;
    this.restTemplate = restTemplate;
}
 
Example 26
Source Project: Refactoring-Bot   Source File: GitlabDataGrabber.java    License: MIT License 5 votes vote down vote up
/**
 * This method returns all comments of a specific pull request from GitLab.
 * 
 * @param commentUri
 * @param gitConfig
 * @return allComments
 * @throws GitLabAPIException
 * @throws IOException
 */
public GitLabDiscussions getAllPullRequestDiscussions(URI commentUri, GitConfiguration gitConfig)
		throws GitLabAPIException, IOException {
	RestTemplate rest = new RestTemplate();
	HttpHeaders headers = new HttpHeaders();
	headers.set("User-Agent", USER_AGENT);
	headers.set(TOKEN_HEADER, gitConfig.getBotToken());
	HttpEntity<String> entity = new HttpEntity<>("parameters", headers);

	String json = null;
	try {
		// Send request to the GitLab-API
		json = rest.exchange(commentUri, HttpMethod.GET, entity, String.class).getBody();
	} catch (RestClientException r) {
		throw new GitLabAPIException("Could not get pull request comments from GitLab!", r);
	}

	try {
		// map json to object
		GitLabDiscussions allDiscussions = new GitLabDiscussions();
		List<GitLabDiscussion> discussionList = mapper.readValue(json,
				mapper.getTypeFactory().constructCollectionType(List.class, GitLabDiscussion.class));
		allDiscussions.setDiscussions(discussionList);
		return allDiscussions;
	} catch (IOException e) {
		logger.error(e.getMessage(), e);
		throw new IOException("Could not create object from GitLab-Comment json!", e);
	}
}
 
Example 27
Source Project: jVoiD   Source File: UserAuthenticationProvider.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
	
	// Make an API Call to the Customer WAR to get the user data based on this email address.
	//JSONObject user = userservice.getCustomerByEmail(username);
	RestTemplate restTemplate = new RestTemplate();
	HttpHeaders headers = new HttpHeaders();
	headers.set("Accept", MediaType.APPLICATION_JSON_VALUE);
	
	UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(ServerUris.CUSTOMER_SERVER_URI+URIConstants.GET_CUSTOMER_BY_EMAIL)
	        .queryParam("params", "{email: " + username + "}");	
	HttpEntity<?> entity = new HttpEntity<>(headers);
	HttpEntity<String> returnString = restTemplate.exchange(builder.build().toUri(), HttpMethod.GET, entity, String.class);
	
	SerializableJSONObject user = null;
	try {
		JSONObject temp = new JSONObject(returnString.getBody());
		user = new SerializableJSONObject(temp);
		System.out.println("User: " + user.toString());
	} catch (JSONException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	
	if(user == null) {
		throw new UsernameNotFoundException(String.format("User %s not exist!", username));
	}
	
	return new UserRepositoryUserDetails(user);
}
 
Example 28
Source Project: MicroCommunity   Source File: DeleteServiceSMOImpl.java    License: Apache License 2.0 4 votes vote down vote up
public RestTemplate getRestTemplate() {
    return restTemplate;
}
 
Example 29
Source Project: MicroCommunity   Source File: DeleteComplaintSMOImpl.java    License: Apache License 2.0 4 votes vote down vote up
public void setRestTemplate(RestTemplate restTemplate) {
    this.restTemplate = restTemplate;
}
 
Example 30
Source Project: MicroCommunity   Source File: EditPurchaseApplySMOImpl.java    License: Apache License 2.0 4 votes vote down vote up
public RestTemplate getRestTemplate() {
    return restTemplate;
}