@Bean public ArkClient arkClient(Environment environment) { // todo: we should probably just network config in json format so it can directly consume ark-node configs String arkNetworkName = environment.getProperty("arkNetwork.name"); ArkNetwork arkNetwork = new ArkNetworkFactory() .createFromYml("ark-config/" + arkNetworkName + ".yml"); RestTemplate restTemplate = new RestTemplateBuilder() .setConnectTimeout(2000) .setReadTimeout(2000) .build(); HttpArkClient httpArkClient = new HttpArkClient(arkNetwork, restTemplate); httpArkClient.updatePeers(); return httpArkClient; }
@BeforeClass public static void beforeClass() throws Exception { jettyServer = new Server(0); WebAppContext webApp = new WebAppContext(); webApp.setServer(jettyServer); webApp.setContextPath(CONTEXT_PATH); webApp.setWar("src/test/webapp"); jettyServer.setHandler(webApp); jettyServer.start(); serverPort = ((ServerConnector)jettyServer.getConnectors()[0]).getLocalPort(); testRestTemplate = new TestRestTemplate(new RestTemplateBuilder() .rootUri("http://localhost:" + serverPort + CONTEXT_PATH)); }
/** * Construct rest template with data app uri. * * @param builder rest template builder * @param dataAppUri data app uri from application.properties */ public MovieRepository(RestTemplateBuilder builder, @Value("${moviedb.webapp.dataAppUri}") String dataAppUri) { logger.debug("data app:" + dataAppUri); String trimmedURL = dataAppUri.trim().toLowerCase(); String dataAppApiUrl; if (trimmedURL.startsWith("http://") || trimmedURL.startsWith("https://")) { dataAppApiUrl = trimmedURL + "/api/v1"; } else { dataAppApiUrl = "http://" + trimmedURL + "/api/v1"; } logger.debug("data app api root url: " + dataAppApiUrl); restTemplate = builder.rootUri(dataAppApiUrl).build(); restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory()); }
@Bean public RestTemplate bitcoinRpcRestTemplate(BitcoinRpcSettings bitcoinRpcSettings) { return new RestTemplateBuilder() .rootUri(bitcoinRpcSettings.getUrl()) .basicAuthorization(bitcoinRpcSettings.getUsername(), bitcoinRpcSettings.getPassword()) .build(); }
@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)); }
/** * 是否有必要模仿Spring不提供RestTemplate,只提供RestTemplateBuilder * * @return dummy */ @Bean(name = WxBeans.WX_API_TEMPLATE_NAME) public WxApiTemplate wxApiTemplate() { RestTemplateBuilder builder = new RestTemplateBuilder(); builder = builder.requestFactory(new WxApiHttpRequestFactory(wxProperties)) .errorHandler(new WxResponseErrorHandler()); HttpMessageConverters converters = this.messageConverters.getIfUnique(); List<HttpMessageConverter<?>> converterList = new ArrayList<>(); // 加入默认转换 converterList.add(new WxHttpInputMessageConverter()); if (converters != null) { converterList.addAll(converters.getConverters()); builder = builder.messageConverters(Collections.unmodifiableList(converterList)); } return new WxApiTemplate(builder.build()); }
@Bean @ConditionalOnMissingBean public RestTemplateBuilder restTemplateBuilder() { RestTemplateBuilder builder = new RestTemplateBuilder(); HttpMessageConverters converters = this.messageConverters.getIfUnique(); if (converters != null) { builder = builder.messageConverters(converters.getConverters()); } List<RestTemplateCustomizer> customizers = this.restTemplateCustomizers .getIfAvailable(); if (!CollectionUtils.isEmpty(customizers)) { customizers = new ArrayList<RestTemplateCustomizer>(customizers); AnnotationAwareOrderComparator.sort(customizers); builder = builder.customizers(customizers); } return builder; }
@Bean @ConditionalOnMissingBean public ProxyExchangeArgumentResolver proxyExchangeArgumentResolver( Optional<RestTemplateBuilder> optional, ProxyProperties proxy) { RestTemplateBuilder builder = optional.orElse(new RestTemplateBuilder()); RestTemplate template = builder.build(); template.setErrorHandler(new NoOpResponseErrorHandler()); template.getMessageConverters().add(new ByteArrayHttpMessageConverter() { @Override public boolean supports(Class<?> clazz) { return true; } }); ProxyExchangeArgumentResolver resolver = new ProxyExchangeArgumentResolver( template); resolver.setHeaders(proxy.convertHeaders()); resolver.setSensitive(proxy.getSensitive()); // can be null return resolver; }
public ProjectGenerationStatPublisher(ProjectRequestDocumentFactory documentFactory, StatsProperties statsProperties, RestTemplateBuilder restTemplateBuilder, RetryTemplate retryTemplate) { this.documentFactory = documentFactory; this.statsProperties = statsProperties; this.objectMapper = createObjectMapper(); StatsProperties.Elastic elastic = statsProperties.getElastic(); if (StringUtils.hasText(elastic.getUsername())) { this.restTemplate = restTemplateBuilder .basicAuthorization(elastic.getUsername(), elastic.getPassword()) .build(); } else { this.restTemplate = restTemplateBuilder.build(); } this.retryTemplate = retryTemplate; }
@Before public void setUp() { log = mock(Log.class); when(log.isDebugEnabled()).thenReturn(true); restTemplate = new RestTemplateBuilder() .customizers(new LoggingCustomizer(log)) .rootUri(wireMockRule.url("/")) .build(); }
@Before public void setup() { // setup WireMock.startRecording(configure(WireMock.recordSpec()) .extractTextBodiesOver(9999999L) .extractBinaryBodiesOver(9999999L) .makeStubsPersistent(false) ); restTemplate = configure(new RestTemplateBuilder()) .rootUri("http://localhost:" + wireMockPort) .build(); }
private RestTemplate restTemplate(ReleaserProperties properties) { Assert.hasText(properties.getGit().getOauthToken(), "In order to connect to Sagan you need to pass the Github OAuth token. " + "You can do it via the [--releaser.git.oauth-token=...] command line argument or an env variable [export RELEASER_GIT_OAUTH_TOKEN=...]."); return new RestTemplateBuilder() .basicAuthorization(properties.getGit().getOauthToken(), "") .build(); }
@Autowired public SubmissionSenderService(RestTemplateBuilder restTemplateBuilder, SandboxSubmissionProperties sandboxSubmissionProperties) { this.sandboxSubmissionProperties = sandboxSubmissionProperties; restTemplate = restTemplateBuilder .rootUri(sandboxSubmissionProperties.getSandboxUrl()) .build(); }
AlfredServiceImpl(final RestTemplateBuilder restTemplateBuilder, final NodeReferenceBuilder nodeReferenceBuilder, final String url, final String username, final String password) { this.nodeReferenceBuilder = nodeReferenceBuilder; this.url = url; restTemplate = restTemplateBuilder.build(); // restTemplate.getMessageConverters().add(new MappingJacksonHttpMessageConverter()); restTemplate.getMessageConverters().add(new StringHttpMessageConverter()); restTemplate.getInterceptors().add( new BasicAuthorizationInterceptor(username, password != null ? password : "")); logger.debug("Creation of AlfredServiceImpl for URL {}", url); }
public PensionFundStatisticsService(RestTemplateBuilder restTemplateBuilder) { restTemplate = restTemplateBuilder .setConnectTimeout(30_000) .setReadTimeout(60_000) .additionalMessageConverters(new Jaxb2RootElementHttpMessageConverter()) .build(); }
@Bean @Override public RestTemplateBuilder restTemplateBuilder() { final ClientHttpRequestInterceptor interceptor = new ClientHttpRequestInterceptor() { @Override public ClientHttpResponse intercept(final HttpRequest request, final byte[] body, final ClientHttpRequestExecution execution) throws IOException { if (logger.isInfoEnabled()) { logger.info(new String(body)); } return execution.execute(request, body); } }; return super.restTemplateBuilder().additionalInterceptors(interceptor); }
@Override public RestClient create(ClassLoader classLoader) throws RestClientCreationException { // Try to obtain a RestTemplate Optional<RestTemplateBuilder> restTemplateBuilder = Context.get().resource("restTemplateBuilder", RestTemplateBuilder.class, classLoader); if (restTemplateBuilder.isPresent()) { return new RestTemplateRestClient(restTemplateBuilder.get().build()); } LOGGER.debug(() -> "No RestTemplateBuilder type Context resource available - RestClient creation skipped"); return null; }
@Autowired public FetchAddOnList(RestTemplateBuilder restTemplateBuilder, ObjectMapper mapper, IndexingService indexingService) { this.restTemplateBuilder = restTemplateBuilder; this.mapper = mapper; this.indexingService = indexingService; }
@Autowired public FetchCoreVersionsList(RestTemplateBuilder restTemplateBuilder, ObjectMapper mapper, VersionsService versionsService) { this.restTemplateBuilder = restTemplateBuilder; this.mapper = mapper; this.versionsService = versionsService; }
@Autowired public FetchDetailsToIndex(IndexingService indexingService, RestTemplateBuilder restTemplateBuilder) { this.indexingService = indexingService; this.restTemplateBuilder = restTemplateBuilder; this.documentBuilderFactory = DocumentBuilderFactory.newInstance(); this.documentBuilderFactory.setValidating(false); }
@Bean @Primary public TestRestTemplate zg2TestRestTemplate(ObjectProvider<RestTemplateBuilder> builderProvider, Environment environment) { SimpleModule sm = new SimpleModule(); Zg2proRestTemplate rt = new Zg2proRestTemplate(sm); TestRestTemplate trt = new TestRestTemplate(rt); trt.setUriTemplateHandler(new LocalHostUriTemplateHandler(environment)); return trt; }
@Bean public ArkClient arkClient(Environment environment) { // todo: we should probably just network config in json format so it can directly consume ark-node configs String arkNetworkName = environment.getProperty("arkNetwork.name"); ArkNetwork arkNetwork = new ArkNetworkFactory() .createFromYml("ark-config/" + arkNetworkName + ".yml"); RestTemplate restTemplate = new RestTemplateBuilder().build(); return new HttpArkClient(arkNetwork, restTemplate); }
public ElasticBeatConfigurationGenerator(MesosConfigProperties mesosConfigProperties, RestTemplateBuilder restTemplateBuilder, UniversalScheduler universalScheduler, Clock clock) { this.mesosConfigProperties = mesosConfigProperties; this.universalScheduler = universalScheduler; this.clock = clock; this.restTemplateBuilder = restTemplateBuilder; }
private RestTemplate createRestTemplate(JiraConnectionProperties jiraConnectionProperties) { RestTemplateBuilder builder = restTemplateBuilder.errorHandler(new JiraRestResponseErrorHandler(url)); BasicAuthentication basicAuth = jiraConnectionProperties.getBasicAuth(); if (basicAuth != null) { builder = builder.basicAuthorization(basicAuth.getUsername(), basicAuth.getPassword()); } if (jiraConnectionProperties.getSslTrustStore() != null) { builder = builder.requestFactory(new HttpComponentsClientHttpRequestFactory(httpClient(jiraConnectionProperties))); } return builder.build(); }
private void waitUntilPivioServerIsUp() { await().atMost(180, SECONDS).until(() -> { String documentResponse = ""; RestTemplate faultSensitiveRestTemplate = new RestTemplateBuilder().rootUri(PIVIO_SERVER_BASE_URL).build(); try { documentResponse = faultSensitiveRestTemplate.getForObject("/document", String.class); } catch (Exception ignored) { LOG.debug("Pivio Server is not up yet. Exception message: {}", ignored.getMessage()); } return !documentResponse.isEmpty(); }); }
@Bean public RestTemplate restTemplateOne(RestTemplateBuilder builder) { try { return builder.build(); } finally { breakBuilderOnNextCall(builder); } }
@Bean public RestTemplate restTemplateTwo(RestTemplateBuilder builder) { try { return builder.build(); } finally { breakBuilderOnNextCall(builder); } }
private void breakBuilderOnNextCall(RestTemplateBuilder builder) { builder.additionalCustomizers(new RestTemplateCustomizer() { @Override public void customize(RestTemplate restTemplate) { throw new IllegalStateException(); } }); }
@Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { RestTemplateBuilder builder = getRestTemplateBuilder(applicationContext); TestRestTemplate template = new TestRestTemplate(builder.build()); template.setUriTemplateHandler( new LocalHostUriTemplateHandler(applicationContext.getEnvironment())); this.object = template; }
private RestTemplateBuilder getRestTemplateBuilder( ApplicationContext applicationContext) { try { return applicationContext.getBean(RestTemplateBuilder.class); } catch (NoSuchBeanDefinitionException ex) { return new RestTemplateBuilder(); } }
@Test public void detectRootUriShouldDefaultToTrue() throws Exception { MockServerRestTemplateCustomizer customizer = new MockServerRestTemplateCustomizer( UnorderedRequestExpectationManager.class); customizer.customize( new RestTemplateBuilder().rootUri("http://example.com").build()); assertThat(customizer.getServer()).extracting("expectationManager") .hasAtLeastOneElementOfType(RootUriRequestExpectationManager.class); }
@Test public void setDetectRootUriShouldDisableRootUriDetection() throws Exception { this.customizer.setDetectRootUri(false); this.customizer.customize( new RestTemplateBuilder().rootUri("http://example.com").build()); assertThat(this.customizer.getServer()).extracting("expectationManager") .hasAtLeastOneElementOfType(SimpleRequestExpectationManager.class); }
@Test public void customizeShouldBindServer() throws Exception { RestTemplate template = new RestTemplateBuilder(this.customizer).build(); this.customizer.getServer().expect(requestTo("/test")).andRespond(withSuccess()); template.getForEntity("/test", String.class); this.customizer.getServer().verify(); }
@Test public void bindToShouldReturnMockRestServiceServer() throws Exception { RestTemplate restTemplate = new RestTemplateBuilder().build(); MockRestServiceServer bound = RootUriRequestExpectationManager .bindTo(restTemplate); assertThat(bound).isNotNull(); }
@Test public void bindToWithExpectationManagerShouldReturnMockRestServiceServer() throws Exception { RestTemplate restTemplate = new RestTemplateBuilder().build(); MockRestServiceServer bound = RootUriRequestExpectationManager .bindTo(restTemplate, this.delegate); assertThat(bound).isNotNull(); }
@Test public void forRestTemplateWhenUsingRootUriTemplateHandlerShouldReturnRootUriRequestExpectationManager() throws Exception { RestTemplate restTemplate = new RestTemplateBuilder().rootUri(this.uri).build(); RequestExpectationManager actual = RootUriRequestExpectationManager .forRestTemplate(restTemplate, this.delegate); assertThat(actual).isInstanceOf(RootUriRequestExpectationManager.class); assertThat(actual).extracting("rootUri").containsExactly(this.uri); }
@Test public void forRestTemplateWhenNotUsingRootUriTemplateHandlerShouldReturnOriginalRequestExpectationManager() throws Exception { RestTemplate restTemplate = new RestTemplateBuilder().build(); RequestExpectationManager actual = RootUriRequestExpectationManager .forRestTemplate(restTemplate, this.delegate); assertThat(actual).isSameAs(this.delegate); }
@Test public void boundRestTemplateShouldPrefixRootUri() { RestTemplate restTemplate = new RestTemplateBuilder() .rootUri("http://example.com").build(); MockRestServiceServer server = RootUriRequestExpectationManager .bindTo(restTemplate); server.expect(requestTo("/hello")).andRespond(withSuccess()); restTemplate.getForEntity("/hello", String.class); }
@Test public void boundRestTemplateWhenUrlIncludesDomainShouldNotPrefixRootUri() { RestTemplate restTemplate = new RestTemplateBuilder() .rootUri("http://example.com").build(); MockRestServiceServer server = RootUriRequestExpectationManager .bindTo(restTemplate); server.expect(requestTo("/hello")).andRespond(withSuccess()); this.thrown.expect(AssertionError.class); this.thrown.expectMessage( "expected:<http://example.com/hello> but was:<http://spring.io/hello>"); restTemplate.getForEntity("http://spring.io/hello", String.class); }