org.springframework.web.client.RestTemplate Java Examples
The following examples show how to use
org.springframework.web.client.RestTemplate.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ConfigServicePropertySourceLocator.java From spring-cloud-config with Apache License 2.0 | 9 votes |
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 #2
Source File: WaggleDanceIntegrationTest.java From waggle-dance with Apache License 2.0 | 6 votes |
@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 #3
Source File: h2oService.java From h2o-2 with Apache License 2.0 | 6 votes |
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 #4
Source File: CMSClientTest.java From oneops with Apache License 2.0 | 6 votes |
@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 #5
Source File: JaxrsClient.java From servicecomb-java-chassis with Apache License 2.0 | 6 votes |
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 #6
Source File: Rest.java From WeEvent with Apache License 2.0 | 6 votes |
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 File: GithubDataGrabber.java From Refactoring-Bot with MIT License | 6 votes |
/** * 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 #8
Source File: LoginController.java From tutorials with MIT License | 6 votes |
@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 #9
Source File: UaaAuthorizationHeaderUtil.java From jhipster-registry with Apache License 2.0 | 5 votes |
public UaaAuthorizationHeaderUtil(ClientRegistrationRepository clientRegistrationRepository, OAuth2AuthorizedClientService clientRegistrationService, RestTemplate uaaRestTemplate) { this.uaaRestTemplate = uaaRestTemplate; this.clientRegistrationRepository = clientRegistrationRepository; this.clientRegistrationService = clientRegistrationService; }
Example #10
Source File: SkipEndPointsIntegrationTestsWithoutContextPathWithBasePath.java From spring-cloud-sleuth with Apache License 2.0 | 5 votes |
@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 #11
Source File: GitlabDataGrabber.java From Refactoring-Bot with MIT License | 5 votes |
/** * 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 #12
Source File: DataValueSynchronization.java From dhis2-core with BSD 3-Clause "New" or "Revised" License | 5 votes |
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 #13
Source File: CreditAgencyPoller.java From ddd-with-spring with Apache License 2.0 | 5 votes |
@Autowired public CreditAgencyPoller(RestTemplate restTemplate, ScoringApplicationService scoringApplicationService) { this.lastModified = new Date(); this.restTemplate = restTemplate; this.scoringApplicationService = scoringApplicationService; }
Example #14
Source File: GetController.java From Spring-Boot-Book with Apache License 2.0 | 5 votes |
@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 #15
Source File: SpringWebBeanResolutionTest.java From ogham with Apache License 2.0 | 5 votes |
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 #16
Source File: QuotesWebSocketIntegrationTest.java From bearchoke with Apache License 2.0 | 5 votes |
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 #17
Source File: UaaSignatureVerifierClient.java From cubeai with Apache License 2.0 | 5 votes |
public UaaSignatureVerifierClient(DiscoveryClient discoveryClient, @Qualifier("loadBalancedRestTemplate") RestTemplate restTemplate, OAuth2Properties oAuth2Properties) { this.restTemplate = restTemplate; this.oAuth2Properties = oAuth2Properties; // Load available UAA servers discoveryClient.getServices(); }
Example #18
Source File: UserAuthenticationProvider.java From jVoiD with Apache License 2.0 | 5 votes |
@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 #19
Source File: DataflowTemplateTests.java From spring-cloud-dataflow with Apache License 2.0 | 5 votes |
@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 #20
Source File: WebClientExceptionTests.java From spring-cloud-sleuth with Apache License 2.0 | 5 votes |
@LoadBalanced @Bean public RestTemplate restTemplate() { SimpleClientHttpRequestFactory clientHttpRequestFactory = new SimpleClientHttpRequestFactory(); clientHttpRequestFactory.setReadTimeout(1); clientHttpRequestFactory.setConnectTimeout(1); return new RestTemplate(clientHttpRequestFactory); }
Example #21
Source File: SkipEndPointsIntegrationTestsWithoutContextPathWithBasePath.java From spring-cloud-sleuth with Apache License 2.0 | 5 votes |
@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 #22
Source File: GrayRestTemplateAutoConfiguration.java From spring-cloud-gray with Apache License 2.0 | 5 votes |
@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 #23
Source File: JaxrsClient.java From servicecomb-java-chassis with Apache License 2.0 | 5 votes |
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 #24
Source File: DemoApplicationTest.java From n2o-framework with Apache License 2.0 | 5 votes |
@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 #25
Source File: ContentRequestMatchersIntegrationTests.java From spring-analysis-note with MIT License | 5 votes |
@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 #26
Source File: ClusterProxyRegistrationClientTest.java From cloudbreak with Apache License 2.0 | 5 votes |
@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 #27
Source File: BintraySearchProviderImpl.java From NBANDROID-V2 with Apache License 2.0 | 5 votes |
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 #28
Source File: CompletionTemplate.java From spring-cloud-dataflow with Apache License 2.0 | 4 votes |
public CompletionTemplate(RestTemplate restTemplate, Link streamLink, Link taskLink) { this.restTemplate = restTemplate; this.streamCompletionUriTemplate = UriTemplate.of(streamLink.getHref()); this.taskCompletionUriTemplate = UriTemplate.of(taskLink.getHref()); }
Example #29
Source File: CodeFirstRestTemplate.java From servicecomb-java-chassis with Apache License 2.0 | 4 votes |
private void testCodeFirstSayHi2(RestTemplate template, String cseUrlPrefix) { ResponseEntity<String> responseEntity = template.exchange(cseUrlPrefix + "sayhi/{name}/v2", HttpMethod.PUT, null, String.class, "world"); TestMgr.check("world sayhi 2", responseEntity.getBody()); }
Example #30
Source File: PostRepositoryTest.java From spring-boot-starter-data-firebase with MIT License | 4 votes |
@Bean public RestTemplate restTemplate() { return new RestTemplate(); }