/** * Method to create http requests to services */ public default <I, O> ListenableFuture<ResponseEntity<O>> createRequest(final URIBuilder uri, final HttpMethod method, final I body, final Class<O> returnClazz, final HttpHeaders header) { final AsyncRestTemplate restTemplate = new AsyncRestTemplate(); restTemplate.setErrorHandler(new DefaultResponseErrorHandler()); if (header != null) { header.setContentType(MediaType.APPLICATION_JSON); } HttpEntity<?> entity; if (body != null) { entity = new HttpEntity<I>(body, header); } else { entity = new HttpEntity<String>(null, header); } return restTemplate.exchange(uri.toString(), method, entity, returnClazz); }
@Override public ResponseEntity<String> submit(JCurlRequestOptions requestOptions) throws Exception { ResponseEntity<String> stringResponseEntity = null; try (CloseableHttpAsyncClient hc = createCloseableHttpAsyncClient()) { for (int i = 0; i < requestOptions.getCount(); i++) { final HttpHeaders headers = new HttpHeaders(); for (Map.Entry<String, String> e : requestOptions.getHeaderMap().entrySet()) { headers.put(e.getKey(), Collections.singletonList(e.getValue())); } final HttpEntity<Void> requestEntity = new HttpEntity<>(headers); AsyncRestTemplate template = new AsyncRestTemplate(new HttpComponentsAsyncClientHttpRequestFactory(hc)); final ListenableFuture<ResponseEntity<String>> exchange = template.exchange(requestOptions.getUrl(), HttpMethod.GET, requestEntity, String.class); stringResponseEntity = exchange.get(); System.out.println(stringResponseEntity.getBody()); } return stringResponseEntity; } }
@DataProvider(value = { "true", "false" }) @Test public void createTracingEnabledAsyncRestTemplate_single_arg_returns_AsyncRestTemplate_with_wingtips_interceptor_added_with_subspan_option_set_to_expected_value( boolean subspanOptionOn ) { // when AsyncRestTemplate result = WingtipsSpringUtil.createTracingEnabledAsyncRestTemplate(subspanOptionOn); // then assertThat(result.getInterceptors()).hasSize(1); assertThat(result.getInterceptors().get(0)).isInstanceOf(WingtipsAsyncClientHttpRequestInterceptor.class); verifySubspanOptionValue(result.getInterceptors().get(0), subspanOptionOn); }
private AsyncRestTemplate createNewRestTemplate(String addr) { // we use async client because usual client does not allow to interruption in some cases NettyRequestFactory factory = new NettyRequestFactory(); if(AddressUtils.isHttps(addr)) { try { initSsl(addr, factory); } catch (Exception e) { log.error("", e); } } final AsyncRestTemplate restTemplate = new AsyncRestTemplate(factory); List<AsyncClientHttpRequestInterceptor> interceptors = new ArrayList<>(); interceptors.add(new HttpAuthInterceptor(registryRepository)); if(!StringUtils.isEmpty(agentPassword)) { interceptors.add(new BasicAuthAsyncInterceptor("admin", agentPassword)); } restTemplate.setInterceptors(interceptors); return restTemplate; }
@SuppressWarnings("unchecked") DockerServiceImpl dockerService() { ClusterConfig config = ClusterConfigImpl.builder().host("localhost:2375").build(); AsyncRestTemplate restTemplate = new AsyncRestTemplate(); restTemplate.setInterceptors( Collections.singletonList( new HttpAuthInterceptor(null))); return DockerServiceImpl.builder() .config(config) .cluster("test") .restTemplate(restTemplate) .nodeInfoProvider(mock(NodeInfoProvider.class)) .eventConsumer(mock(MessageBus.class)) .objectMapper(new ObjectMapper()) .build(); }
@SuppressWarnings("unchecked") DockerServiceImpl dockerService() { ClusterConfig config = ClusterConfigImpl.builder() .host("172.31.0.12:2375").build(); AsyncRestTemplate restTemplate = new AsyncRestTemplate(); RegistryRepository registryRepository = mock(RegistryRepository.class); restTemplate.setInterceptors( Collections.singletonList( new HttpAuthInterceptor(registryRepository))); return DockerServiceImpl.builder() .config(config) .cluster("test") .restTemplate(restTemplate) .nodeInfoProvider(mock(NodeInfoProvider.class)) .eventConsumer(mock(MessageBus.class)) .objectMapper(new ObjectMapper()) .build(); }
@Test @SuppressWarnings("unchecked") @Ignore public void testLaunchTask() throws Exception { ClusterConfig config = ClusterConfigImpl.builder().host("localhost:2375").build(); DockerService dockerService = DockerServiceImpl.builder() .config(config) .restTemplate(new AsyncRestTemplate()) .nodeInfoProvider(mock(NodeInfoProvider.class)) .eventConsumer(mock(MessageBus.class)) .objectMapper(new ObjectMapper()) .cluster("test") .build(); ClassLoader classLoader = getClass().getClassLoader(); File file = new File(classLoader.getResource("docker-compose.yml").getFile()); ComposeResult composeResult = composeExecutor.up(ComposeArg.builder().file(file).runUpdate(false).build(), dockerService); Assert.notNull(composeResult); }
private String registerAsyncRestTemplate(final String id, final String factoryId, final String convertersId, @Nullable final String baseUrl) { return registry.register(id, AsyncRestTemplate.class, () -> { LOG.debug("Client [{}]: Registering AsyncRestTemplate", id); final BeanDefinitionBuilder restTemplate = genericBeanDefinition(AsyncRestTemplate.class); restTemplate.addConstructorArgReference(factoryId); final DefaultUriTemplateHandler handler = new DefaultUriTemplateHandler(); handler.setBaseUrl(baseUrl); restTemplate.addPropertyValue("uriTemplateHandler", handler); final AbstractBeanDefinition converters = BeanDefinitionBuilder.genericBeanDefinition() .setFactoryMethod("getConverters") .getBeanDefinition(); converters.setFactoryBeanName(convertersId); restTemplate.addPropertyValue("messageConverters", converters); return restTemplate; }); }
@Bean @Resource(name = "jsonV1Converter") public AsyncRestTemplate asyncRestTemplate(AsyncClientHttpRequestFactory asyncClientHttpRequestFactory, MappingJackson2HttpMessageConverter jsonConverter) { AsyncRestTemplate restTemplate = new AsyncRestTemplate(asyncClientHttpRequestFactory); // Replace the default json converter by our converter // Remove for(HttpMessageConverter httpMessageConverter : restTemplate.getMessageConverters()) { if (httpMessageConverter instanceof MappingJackson2HttpMessageConverter) { restTemplate.getMessageConverters().remove(httpMessageConverter); break; } } // Add restTemplate.getMessageConverters().add(jsonConverter); return restTemplate; }
@Test public void multipleRestTemplates() { ConfigurableApplicationContext context = init(TwoRestTemplates.class); final Map<String, AsyncRestTemplate> restTemplates = context .getBeansOfType(AsyncRestTemplate.class); MatcherAssert.assertThat(restTemplates, is(notNullValue())); Collection<AsyncRestTemplate> templates = restTemplates.values(); MatcherAssert.assertThat(templates, hasSize(2)); TwoRestTemplates.Two two = context.getBean(TwoRestTemplates.Two.class); MatcherAssert.assertThat(two.loadBalanced, is(notNullValue())); assertLoadBalanced(two.loadBalanced); MatcherAssert.assertThat(two.nonLoadBalanced, is(notNullValue())); MatcherAssert.assertThat(two.nonLoadBalanced.getInterceptors(), is(empty())); }
public SleepServerApiClient() throws Exception { connectionManager = new PoolingNHttpClientConnectionManager( new DefaultConnectingIOReactor(IOReactorConfig.DEFAULT)); connectionManager.setMaxTotal(20000); connectionManager.setDefaultMaxPerRoute(20000); RequestConfig config = RequestConfig.custom().setConnectTimeout(120000) .build(); CloseableHttpAsyncClient httpClient = HttpAsyncClientBuilder.create() .setConnectionManager(connectionManager) .setDefaultRequestConfig(config).build(); HttpComponentsAsyncClientHttpRequestFactory requestFactory = new HttpComponentsAsyncClientHttpRequestFactory( httpClient); client = new AsyncRestTemplate(requestFactory); }
public TracingAsyncRestTemplateTest() { final AsyncRestTemplate restTemplate = new AsyncRestTemplate(); restTemplate.setInterceptors(Collections.<AsyncClientHttpRequestInterceptor>singletonList( new TracingAsyncRestTemplateInterceptor(mockTracer, Collections.<RestTemplateSpanDecorator>singletonList(new RestTemplateSpanDecorator.StandardTags())))); client = new Client<AsyncRestTemplate>() { @Override public <T> ResponseEntity<T> getForEntity(String url, Class<T> clazz) { ListenableFuture<ResponseEntity<T>> forEntity = restTemplate.getForEntity(url, clazz); try { return forEntity.get(); } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); Assert.fail(); } return null; } @Override public AsyncRestTemplate template() { return restTemplate; } }; mockServer = MockRestServiceServer.bindTo(client.template()).ignoreExpectOrder(true).build(); }
@PostConstruct public void init() { if (restTemplates != null) { for (AsyncRestTemplate restTemplate: restTemplates) { registerTracingInterceptor(restTemplate); } } }
private void registerTracingInterceptor(AsyncRestTemplate restTemplate) { List<AsyncClientHttpRequestInterceptor> interceptors = restTemplate.getInterceptors(); for (AsyncClientHttpRequestInterceptor interceptor: interceptors) { if (interceptor instanceof TracingAsyncRestTemplateInterceptor) { return; } } log.info("Adding " + TracingAsyncRestTemplateInterceptor.class.getSimpleName() + " to async rest template"); interceptors = new ArrayList<>(interceptors); interceptors.add(new TracingAsyncRestTemplateInterceptor(tracer)); restTemplate.setInterceptors(interceptors); }
@Override public ResponseEntity<String> submit(JCurlRequestOptions requestOptions) throws Exception { int ioWorkerCount = Runtime.getRuntime().availableProcessors() * 2; NioEventLoopGroup eventLoopGroup = new NioEventLoopGroup(ioWorkerCount); try { final Netty4ClientHttpRequestFactory netty4ClientHttpRequestFactory = new Netty4ClientHttpRequestFactory(eventLoopGroup); netty4ClientHttpRequestFactory.setConnectTimeout(2000); netty4ClientHttpRequestFactory.setReadTimeout(2000); /* SslContext sslContext = SslContextBuilder .forClient() .sslProvider(SslProvider.JDK) .build() ; */ if (requestOptions.getUrl().toLowerCase().startsWith("https://")) { SslContext sslContext = new DefaultClientSslContext(); netty4ClientHttpRequestFactory.setSslContext(sslContext); } netty4ClientHttpRequestFactory.afterPropertiesSet(); ResponseEntity<String> stringResponseEntity = null; for (int i = 0; i < requestOptions.getCount(); i++) { final HttpHeaders headers = new HttpHeaders(); for(Map.Entry<String,String> e : requestOptions.getHeaderMap().entrySet()) { headers.put(e.getKey(), Collections.singletonList(e.getValue())); } final HttpEntity<Void> requestEntity = new HttpEntity<>(headers); AsyncRestTemplate template = new AsyncRestTemplate(netty4ClientHttpRequestFactory); final ListenableFuture<ResponseEntity<String>> exchange = template.exchange(requestOptions.getUrl(), HttpMethod.GET, requestEntity, String.class); stringResponseEntity = exchange.get(); System.out.println(stringResponseEntity.getBody()); } return stringResponseEntity; } finally { eventLoopGroup.shutdownGracefully(100, 500, TimeUnit.MILLISECONDS); } }
/** * Create a {@code MockRestServiceServer} and set up the given * {@code AsyRestTemplate} with a mock {@link AsyncClientHttpRequestFactory}. * @param asyncRestTemplate the AsyncRestTemplate to set up for mock testing * @return the created mock server */ public static MockRestServiceServer createServer(AsyncRestTemplate asyncRestTemplate) { Assert.notNull(asyncRestTemplate, "'asyncRestTemplate' must not be null"); MockRestServiceServer mockServer = new MockRestServiceServer(); RequestMatcherClientHttpRequestFactory factory = mockServer.new RequestMatcherClientHttpRequestFactory(); asyncRestTemplate.setAsyncRequestFactory(factory); return mockServer; }
/** * Default constructor * @param asyncRestTemplate AsyncRestTemplate to handle requests * @param baseURL base URL for the NGSIv2 service */ public Ngsi2Client(AsyncRestTemplate asyncRestTemplate, String baseURL) { this(); this.asyncRestTemplate = asyncRestTemplate; this.baseURL = baseURL; // Inject NGSI2 error handler and Java 8 support injectNgsi2ErrorHandler(); injectJava8ObjectMapper(); }
@Before public void setup() { client = new OpenLpwaProvider(url, apiKey); AsyncRestTemplate asyncRestTemplate = new AsyncRestTemplate(); asyncRestTemplate.setErrorHandler(new OpenLpwaResponseErrorHandler()); ReflectionTestUtils.setField(client, "asyncRestTemplate", asyncRestTemplate); mockServer = MockRestServiceServer.createServer(asyncRestTemplate); }
@Test public void createTracingEnabledAsyncRestTemplate_no_args_returns_AsyncRestTemplate_with_wingtips_interceptor_added_with_subspan_option_on() { // when AsyncRestTemplate result = WingtipsSpringUtil.createTracingEnabledAsyncRestTemplate(); // then assertThat(result.getInterceptors()).hasSize(1); assertThat(result.getInterceptors().get(0)).isInstanceOf(WingtipsAsyncClientHttpRequestInterceptor.class); verifySubspanOptionValue(result.getInterceptors().get(0), true); }
@Autowired public SpringOneController(RestTemplate restTemplate, Tracer tracer, SpanNamer spanNamer, SpringOneWorker springOneWorker, AsyncRestTemplate asyncRestTemplate, Service1Client service1Client, TraceKeys traceKeys) { this.restTemplate = restTemplate; this.tracer = tracer; this.spanNamer = spanNamer; this.springOneWorker = springOneWorker; this.asyncRestTemplate = asyncRestTemplate; this.service1Client = service1Client; this.traceKeys = traceKeys; }
public ApiHttpClient(final String channelAccessToken) { RequestConfig requestConfig = RequestConfig.custom() .setConnectionRequestTimeout(timeoutInMillis) .setConnectTimeout(timeoutInMillis) .build(); CloseableHttpAsyncClient asyncClient = HttpAsyncClientBuilder.create() .setDefaultRequestConfig(requestConfig) .addInterceptorLast((HttpRequest httpRequest, HttpContext httpContext) -> { httpRequest.addHeader("X-Line-ChannelToken", channelAccessToken); httpRequest.addHeader("Content-Type", "application/json; charser=UTF-8"); httpRequest.removeHeaders("Accept"); httpRequest.addHeader("Accept", "application/json; charset=UTF-8"); }) .setMaxConnTotal(maxConnections) .setMaxConnPerRoute(maxConnections) .disableCookieManagement() .build(); asyncRestTemplate = new AsyncRestTemplate(new HttpComponentsAsyncClientHttpRequestFactory(asyncClient)); asyncRestTemplate.setErrorHandler(new ApiResponseErrorHandler()); httpHeaders = new HttpHeaders(); httpHeaders.set("X-Line-ChannelToken", channelAccessToken); httpHeaders.setContentType(new MediaType("application", "json", Charset.forName("UTF-8"))); List<MediaType> list = new ArrayList<>(); list.add(new MediaType("application", "json", Charset.forName("UTF-8"))); httpHeaders.setAccept(list); objectMapper = new ObjectMapper(); objectMapper.configure(MapperFeature.USE_WRAPPER_NAME_AS_PROPERTY_NAME, true); objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); objectMapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false); objectMapper.setAnnotationIntrospector(new JaxbAnnotationIntrospector(TypeFactory.defaultInstance())); objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); }
public InputStreamTest() { final AsyncRestTemplate template = new AsyncRestTemplate(); this.server = MockRestServiceServer.createServer(template); this.unit = Http.builder() .requestFactory(template.getAsyncRequestFactory()) .converter(new InputStreamHttpMessageConverter()) .baseUrl("https://api.example.com") .build(); }
public MockSetup(final String baseUrl, final Iterable<HttpMessageConverter<?>> converters) { final AsyncRestTemplate template = new AsyncRestTemplate(); this.server = MockRestServiceServer.createServer(template); this.http = Http.builder() .requestFactory(template.getAsyncRequestFactory()) .converters(converters) .baseUrl(baseUrl) .build(); }
@Override public void register() { settings.getClients().forEach((id, client) -> { final String factoryId = registerAsyncClientHttpRequestFactory(id, client); final BeanDefinition converters = registerHttpMessageConverters(id); final String baseUrl = client.getBaseUrl(); final List<BeanMetadataElement> plugins = registerPlugins(id, client); registerHttp(id, client, factoryId, converters, plugins); registerTemplate(id, RestTemplate.class, factoryId, baseUrl, converters, plugins); registerTemplate(id, AsyncRestTemplate.class, factoryId, baseUrl, converters, plugins); }); }
@Bean public AsyncRestTemplate exampleAsyncRestTemplate(final AsyncClientHttpRequestFactory requestFactory, final ClientHttpMessageConverters converters) { final AsyncRestTemplate template = new AsyncRestTemplate(); final DefaultUriTemplateHandler handler = new DefaultUriTemplateHandler(); handler.setBaseUrl("https://www.example.com"); template.setUriTemplateHandler(handler); template.setAsyncRequestFactory(requestFactory); template.setMessageConverters(converters.getConverters()); return template; }
public CaptureTest() { final AsyncRestTemplate template = new AsyncRestTemplate(); this.server = MockRestServiceServer.createServer(template); this.unit = Http.builder() .requestFactory(template.getAsyncRequestFactory()) .converter(createJsonConverter()) .converter(new StringHttpMessageConverter()) .baseUrl("https://api.example.com") .build(); }
public NIORestClient(AsyncRestTemplate template) { super(); this.template = template; MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter(); converter.setObjectMapper(JacksonUtil.getMapper()); template.getMessageConverters().add(converter); }
@Bean public NIORestClient restClient(){ HttpComponentsAsyncClientHttpRequestFactory rest = new HttpComponentsAsyncClientHttpRequestFactory(); rest.setConnectionRequestTimeout(connectionRequestTimeout); rest.setReadTimeout(readTimeout); rest.setConnectTimeout(connectTimeout); return new NIORestClient(new AsyncRestTemplate(rest)); }
@Bean public AsyncRestTemplate asyncRestTemplateSupportHal(MappingJackson2HttpMessageConverter jackson2ConverterSupportHal) throws Exception { // HttpComponentsAsyncClientHttpRequestFactory internally uses NIO AsyncRestTemplate asyncRestTemplate = new AsyncRestTemplate(new HttpComponentsAsyncClientHttpRequestFactory(asyncHttpClient())); asyncRestTemplate.setMessageConverters( Arrays.asList(jackson2ConverterSupportHal) ); return asyncRestTemplate; }
public BottlerService(BottlingWorker bottlingWorker, PresentingClient presentingClient, RestTemplate restTemplate, AsyncRestTemplate asyncRestTemplate, Tracer tracer) { this.bottlingWorker = bottlingWorker; this.presentingClient = presentingClient; this.restTemplate = restTemplate; this.asyncRestTemplate = asyncRestTemplate; this.tracer = tracer; }
@Bean BottlerService bottlingService(BottlingWorker bottlingWorker, PresentingClient presentingClient, @LoadBalanced RestTemplate restTemplate, AsyncRestTemplate asyncRestTemplate, Tracer tracer) { return new BottlerService(bottlingWorker, presentingClient, restTemplate, asyncRestTemplate, tracer); }
private AsyncRestTemplate getAsyncRestTemplate() { SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory(); factory.setTaskExecutor(new SimpleAsyncTaskExecutor()); factory.setConnectTimeout(gorouterProperties.getConnectTimeout()); factory.setReadTimeout(gorouterProperties.getReadTimeout()); return new AsyncRestTemplate(factory); }
@Bean public Runnable gatheringJob(LoadStore loadStore) { return new GatheringJob(loadStore, new GorouterClient(new AsyncRestTemplate(), null), new DefaultGorouterAddressRetriever(Arrays .asList("http://localhost:36888/test/gorouterMock/1", "http://localhost:36888/test/gorouterMock/2"))); }
@Bean public SmartInitializingSingleton loadBalancedAsyncRestTemplateInitializer( final List<AsyncRestTemplateCustomizer> customizers) { return new SmartInitializingSingleton() { @Override public void afterSingletonsInstantiated() { for (AsyncRestTemplate restTemplate : AsyncRestTemplateCustomizerConfig.this.restTemplates) { for (AsyncRestTemplateCustomizer customizer : customizers) { customizer.customize(restTemplate); } } } }; }
@Bean public AsyncRestTemplateCustomizer asyncRestTemplateCustomizer( final AsyncLoadBalancerInterceptor loadBalancerInterceptor) { return new AsyncRestTemplateCustomizer() { @Override public void customize(AsyncRestTemplate restTemplate) { List<AsyncClientHttpRequestInterceptor> list = new ArrayList<>( restTemplate.getInterceptors()); list.add(loadBalancerInterceptor); restTemplate.setInterceptors(list); } }; }
@Test public void restTemplateGetsLoadBalancerInterceptor() { ConfigurableApplicationContext context = init(OneRestTemplate.class); final Map<String, AsyncRestTemplate> restTemplates = context .getBeansOfType(AsyncRestTemplate.class); MatcherAssert.assertThat(restTemplates, is(notNullValue())); MatcherAssert.assertThat(restTemplates.values(), hasSize(1)); AsyncRestTemplate restTemplate = restTemplates.values().iterator().next(); MatcherAssert.assertThat(restTemplate, is(notNullValue())); assertLoadBalanced(restTemplate); }
@Bean public AsyncRestTemplate asyncRestTemplate(){ AsyncRestTemplate art = new AsyncRestTemplate(); return art; }
@Bean @LoadBalanced public AsyncRestTemplate asyncRestTemplate(){ AsyncRestTemplate art = new AsyncRestTemplate(); return art; }
@Bean public AsyncRestTemplate restTemplate(){ return new AsyncRestTemplate(new Netty4ClientHttpRequestFactory()); }