本文整理汇总了Java中io.reactivex.netty.protocol.http.client.HttpClientRequest类的典型用法代码示例。如果您正苦于以下问题:Java HttpClientRequest类的具体用法?Java HttpClientRequest怎么用?Java HttpClientRequest使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
HttpClientRequest类属于io.reactivex.netty.protocol.http.client包,在下文中一共展示了HttpClientRequest类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: testConcurrentPatch
import io.reactivex.netty.protocol.http.client.HttpClientRequest; //导入依赖的package包/类
@Test
public void testConcurrentPatch() throws InterruptedException {
HttpClientRequest<ByteBuf, ByteBuf> post = post(100L);
Observable<byte[]> slowContent = Observable.just("hello ".getBytes()).repeat()
.zipWith(Observable.interval(50, TimeUnit.MILLISECONDS).startWith(0L), (data, nop) -> data).take(10);
Observable<byte[]> fastContent = Observable.just("goodbye ".getBytes()).repeat()
.zipWith(Observable.interval(10, TimeUnit.MILLISECONDS).startWith(0L), (data, nop) -> data).take(10);
Iterator<HttpClientResponse<ByteBuf>> iterator = post.map(this::getLocation)
.flatMap(location -> Observable.merge(
patch(location, 0 , slowContent),
patch(location, 0, fastContent).delay(120, TimeUnit.MILLISECONDS)))
.toBlocking().getIterator();
// the first response should be the failure
assertThat(iterator.next()).isNotNull()
.extracting(HttpClientResponse::getStatus).containsExactly(HttpResponseStatus.BAD_REQUEST);
// the second one should be sucessfull
assertThat(iterator.next()).isNotNull()
.extracting(HttpClientResponse::getStatus).containsExactly(HttpResponseStatus.NO_CONTENT);
}
示例2: buildEventStream
import io.reactivex.netty.protocol.http.client.HttpClientRequest; //导入依赖的package包/类
protected static Observable<JsonNode> buildEventStream(String buildId, String lastEventId) {
AtomicReference<String> _lastBuildEventId = new AtomicReference<>(null);
HttpClientRequest<ByteBuf, ByteBuf> request = HTTP_CLIENT
.createGet("/build-export/v1/build/" + buildId + "/events?eventTypes=" + EventProcessor.EVENT_TYPES)
.setKeepAlive(true);
if (BASIC_AUTH != null) {
request = request.addHeader("Authorization", "Basic " + BASIC_AUTH);
}
if (lastEventId != null) {
request = request.addHeader("Last-Event-ID", lastEventId);
}
return request
.flatMap(HttpClientResponse::getContentAsServerSentEvents)
.doOnNext(serverSentEvent -> _lastBuildEventId.set(serverSentEvent.getEventIdAsString()))
.doOnSubscribe(() -> LOGGER.info("Streaming events for build: " + buildId))
.filter(serverSentEvent -> serverSentEvent.getEventTypeAsString().equals("BuildEvent"))
.map(Application::parse)
.onErrorResumeNext(t -> {
LOGGER.info("Error streaming build events of build " + buildId + ", resuming from event id" + _lastBuildEventId.get() + "...");
return buildEventStream(buildId, _lastBuildEventId.get());
});
}
示例3: newHttpClient
import io.reactivex.netty.protocol.http.client.HttpClientRequest; //导入依赖的package包/类
@Override
public HttpClient<ByteBuf, ByteBuf> newHttpClient(final IClientConfig config) {
final List<ExecutionListener<HttpClientRequest<ByteBuf>, HttpClientResponse<ByteBuf>>> listeners = new ArrayList<>();
listeners.add(createBearerHeaderAdder());
final PipelineConfiguratorComposite<HttpClientResponse<ByteBuf>, HttpClientRequest<ByteBuf>> pipelineConfigurator = new PipelineConfiguratorComposite<HttpClientResponse<ByteBuf>,
HttpClientRequest<ByteBuf>>(new HttpClientPipelineConfigurator<ByteBuf, ByteBuf>(),
new HttpObjectAggregationConfigurator(maxChunkSize));
final LoadBalancingHttpClient<ByteBuf, ByteBuf> client = LoadBalancingHttpClient.<ByteBuf, ByteBuf>builder()
.withClientConfig(config)
.withExecutorListeners(listeners)
.withRetryHandler(getDefaultHttpRetryHandlerWithConfig(config))
.withPipelineConfigurator(pipelineConfigurator)
.withPoolCleanerScheduler(RibbonTransport.poolCleanerScheduler)
.build();
return client;
}
示例4: get
import io.reactivex.netty.protocol.http.client.HttpClientRequest; //导入依赖的package包/类
private Observable<JsonNode> get(String url)
{
return rxNetty.submit(withHeaders(HttpClientRequest.create(HttpMethod.GET, configuration.getPath() + url)))
.flatMap(clientResponse ->
{
if (clientResponse.getStatus().code() == 200)
{
return clientResponse.getContent();
}
else
{
logger.error("Got http {} from zmon", clientResponse.getStatus().code());
return Observable.empty();
}
})
.flatMap(this::parse);
}
示例5: apply
import io.reactivex.netty.protocol.http.client.HttpClientRequest; //导入依赖的package包/类
@Override
public void apply(HttpClientRequest<ByteBuf> request, Authentication auth) {
logger.info("OAuth2TokenStrategy called for auth: " + auth + " and request: " + request);
if (auth != null) {
if (auth instanceof OAuth2Authentication) {
Object details = auth.getDetails();
if (details instanceof OAuth2AuthenticationDetails) {
logger.info("OAuth2 authentication details found");
OAuth2AuthenticationDetails oauth = (OAuth2AuthenticationDetails) details;
String accessToken = oauth.getTokenValue();
String tokenType = oauth.getTokenType() == null ? "Bearer" : oauth.getTokenType();
request.withHeader("Authorization", tokenType + " " + accessToken);
} else {
logger.info("No OAuth2 authentication details found");
}
}
} else {
logger.warn("OAuth2TokenStrategy enabled, but inbound request does not contain a Spring Security Authentication context");
}
}
示例6: retrieveJsonFromRequest
import io.reactivex.netty.protocol.http.client.HttpClientRequest; //导入依赖的package包/类
/**
* Calls the remote service using the provided request, applies error handling and
* converts the response into a {@link Map}. The entire request and response are
* executed and handled in a hot observable.
*
* @param serviceId the id of the service for which the request is made
* @param request the request which has to be executed using RxNetty
* @return an {@link Observable} emitting the JSON response as a Map with String keys
* and Object values.
*/
public Observable<Map<String, Object>> retrieveJsonFromRequest(String serviceId, HttpClientRequest<ByteBuf> request) {
RxClient.ServerInfo serverInfo = getServerInfoFromRequestOrClient(request, rxClient);
return rxClient.submit(serverInfo, request)
.publish().autoConnect()
.doOnError(el -> errorHandler.handleNodeError(serviceId, format("Error retrieving node(s) for url {0} with headers {1}: {2}",
request.getUri(), request.getHeaders().entries(), el), el))
.filter(r -> {
if (r.getStatus().code() < 400) {
return true;
} else {
errorHandler.handleNodeWarning(serviceId, "Exception " + r.getStatus() + " for url " + request.getUri() + " with headers " + r.getHeaders().entries());
return false;
}
})
.flatMap(AbstractHttpContentHolder::getContent)
.map(data -> data.toString(Charset.defaultCharset()))
.map(response -> {
JacksonJsonParser jsonParser = new JacksonJsonParser();
return jsonParser.parseMap(response);
})
.doOnNext(r -> logger.info("Json retrieved from call: {}", r))
.onErrorResumeNext(Observable.empty());
}
示例7: getIndexFromServiceInstance
import io.reactivex.netty.protocol.http.client.HttpClientRequest; //导入依赖的package包/类
private Observable<Node> getIndexFromServiceInstance(ServiceInstance serviceInstance, final Object outboundSecurityObject) {
final String url = uriResolver.resolveHomePageUrl(serviceInstance);
final String serviceId = serviceInstance.getServiceId().toLowerCase();
HttpClientRequest<ByteBuf> request = HttpClientRequest.createGet(url);
applyOutboundSecurityStrategyOnRequest(request, outboundSecurityObject);
for (Map.Entry<String, String> header : properties.getRequestHeaders().entrySet()) {
request.withHeader(header.getKey(), header.getValue());
}
return caller.retrieveJsonFromRequest(serviceId, request)
.map(JSONObject::new)
.concatMap(source -> indexToNodeConverter.convert(serviceInstance.getServiceId().toLowerCase(), url, source))
.filter(node -> !properties.getFilteredServices().contains(node.getId()))
.doOnNext(el -> logger.info("Index node {} discovered in url: {}", el.getId(), url))
.doOnError(e -> logger.error("Error while fetching node: ", e))
.doOnCompleted(() -> logger.info("Completed emissions of an index node observable for url: " + url))
.onErrorResumeNext(Observable.empty());
}
示例8: getHealthNodesFromService
import io.reactivex.netty.protocol.http.client.HttpClientRequest; //导入依赖的package包/类
protected Observable<Node> getHealthNodesFromService(String serviceId, String url, final Object outboundSecurityObject) {
HttpClientRequest<ByteBuf> request = HttpClientRequest.createGet(url);
applyOutboundSecurityStrategyOnRequest(request, outboundSecurityObject);
for (Entry<String, String> header : properties.getRequestHeaders().entrySet()) {
request.withHeader(header.getKey(), header.getValue());
}
return caller.retrieveJsonFromRequest(serviceId, request)
.flatMap(el -> healthToNodeConverter.convertToNodes(serviceId, el))
.filter(node -> !properties.getFilteredServices().contains(node.getId()))
//TODO: .map(node -> springCloudEnricher.enrich(node))
.doOnNext(el -> logger.info("Health node {} discovered in url: {}", el.getId(), url))
.doOnError(e -> logger.error("Error during healthnode fetching: ", e))
.doOnCompleted(() -> logger.info("Completed emission of a health node observable from url: " + url))
.onErrorResumeNext(Observable.empty());
}
开发者ID:ordina-jworks,项目名称:microservices-dashboard-server,代码行数:17,代码来源:HealthIndicatorsAggregator.java
示例9: getPactUrlsNotFound
import io.reactivex.netty.protocol.http.client.HttpClientRequest; //导入依赖的package包/类
@SuppressWarnings("unchecked")
@Test
public void getPactUrlsNotFound() throws InterruptedException {
HttpClientResponse<ByteBuf> urlsNotFoundResponse = mock(HttpClientResponse.class);
when(urlsNotFoundResponse.getContent()).thenReturn(null);
when(urlsNotFoundResponse.getStatus()).thenReturn(HttpResponseStatus.NOT_FOUND);
HttpResponseHeaders httpResponseHeaders = mock(HttpResponseHeaders.class);
when(httpResponseHeaders.entries()).thenReturn(newArrayList());
when(urlsNotFoundResponse.getHeaders()).thenReturn(httpResponseHeaders);
when(rxClient.submit(any(RxClient.ServerInfo.class), any(HttpClientRequest.class)))
.thenReturn(Observable.just(urlsNotFoundResponse));
TestSubscriber<Node> testSubscriber = new TestSubscriber<>();
pactsAggregator.aggregateNodes().toBlocking().subscribe(testSubscriber);
testSubscriber.assertNoErrors();
List<Node> nodes = testSubscriber.getOnNextEvents();
assertThat(nodes).isEmpty();
verify(publisher).publishEvent(any(SystemEvent.class));
}
示例10: onErrorWhenGettingNodeOne
import io.reactivex.netty.protocol.http.client.HttpClientRequest; //导入依赖的package包/类
@SuppressWarnings("unchecked")
@Test
public void onErrorWhenGettingNodeOne() {
HttpClientResponse<ByteBuf> urlsResponse = mock(HttpClientResponse.class);
ByteBuf byteBuf = (new PooledByteBufAllocator()).directBuffer();
ByteBufUtil.writeUtf8(byteBuf, onePactSource);
when(urlsResponse.getContent()).thenReturn(Observable.just(byteBuf));
when(urlsResponse.getStatus()).thenReturn(HttpResponseStatus.OK);
when(rxClient.submit(any(RxClient.ServerInfo.class), any(HttpClientRequest.class)))
.thenReturn(Observable.just(urlsResponse), Observable.error(new RuntimeException()));
TestSubscriber<Node> testSubscriber = new TestSubscriber<>();
pactsAggregator.aggregateNodes().toBlocking().subscribe(testSubscriber);
testSubscriber.assertError(RuntimeException.class);
verify(publisher).publishEvent(any(SystemEvent.class));
}
示例11: shouldGetMappingNodesFromService
import io.reactivex.netty.protocol.http.client.HttpClientRequest; //导入依赖的package包/类
@SuppressWarnings({"rawtypes", "unchecked"})
@Test
public void shouldGetMappingNodesFromService() {
when(properties.getRequestHeaders()).thenReturn(requestHeaders());
Map retrievedMap = new HashMap();
Observable retrievedMapObservable = Observable.just(retrievedMap);
when(caller.retrieveJsonFromRequest(anyString(), any(HttpClientRequest.class)))
.thenReturn(retrievedMapObservable);
mockStatic(MappingsToNodeConverter.class);
PowerMockito.when(MappingsToNodeConverter.convertToNodes(anyString(), anyMap()))
.thenReturn(Observable.from(correctNodes()));
TestSubscriber<Node> testSubscriber = new TestSubscriber<>();
aggregator.getMappingNodesFromService("testService", "testUrl", null).toBlocking().subscribe(testSubscriber);
List<Node> nodes = testSubscriber.getOnNextEvents();
verify(caller, times(1)).retrieveJsonFromRequest(eq("testService"), requestCaptor.capture());
assertThat(requestCaptor.getValue().getHeaders().entries()).usingElementComparator(stringEntryComparator())
.containsExactlyElementsOf(requestHeaders().entrySet());
assertThat(nodes).containsOnly(new Node("Node1"), new Node("Node2"));
}
示例12: shouldReturnEmptyObservableOnEmptySourceObservable
import io.reactivex.netty.protocol.http.client.HttpClientRequest; //导入依赖的package包/类
@SuppressWarnings({"rawtypes", "unchecked"})
@Test
public void shouldReturnEmptyObservableOnEmptySourceObservable() {
when(properties.getRequestHeaders()).thenReturn(requestHeaders());
Observable retrievedMapObservable = Observable.empty();
when(caller.retrieveJsonFromRequest(anyString(), any(HttpClientRequest.class)))
.thenReturn(retrievedMapObservable);
TestSubscriber<Node> testSubscriber = new TestSubscriber<>();
aggregator.getMappingNodesFromService("testService", "testUrl", null).toBlocking().subscribe(testSubscriber);
testSubscriber.assertNoValues();
testSubscriber.assertCompleted();
verify(caller, times(1)).retrieveJsonFromRequest(eq("testService"), requestCaptor.capture());
assertThat(requestCaptor.getValue().getHeaders().entries()).usingElementComparator(stringEntryComparator())
.containsExactlyElementsOf(requestHeaders().entrySet());
}
示例13: shouldReturnEmptyObservableOnErroneousConversion
import io.reactivex.netty.protocol.http.client.HttpClientRequest; //导入依赖的package包/类
@SuppressWarnings({"rawtypes", "unchecked"})
@Test
public void shouldReturnEmptyObservableOnErroneousConversion() {
when(properties.getRequestHeaders()).thenReturn(requestHeaders());
Map retrievedMap = new HashMap();
Observable retrievedMapObservable = Observable.just(retrievedMap).publish().autoConnect();
when(caller.retrieveJsonFromRequest(anyString(), any(HttpClientRequest.class)))
.thenReturn(retrievedMapObservable);
mockStatic(MappingsToNodeConverter.class);
PowerMockito.when(MappingsToNodeConverter.convertToNodes(anyString(), anyMap()))
.thenThrow(new RuntimeException("Error1"));
TestSubscriber<Node> testSubscriber = new TestSubscriber<>();
aggregator.getMappingNodesFromService("testService", "testUrl", null).toBlocking().subscribe(testSubscriber);
testSubscriber.getOnNextEvents();
testSubscriber.assertNoValues();
testSubscriber.assertCompleted();
verify(caller, times(1)).retrieveJsonFromRequest(eq("testService"), requestCaptor.capture());
assertThat(requestCaptor.getValue().getHeaders().entries()).usingElementComparator(stringEntryComparator())
.containsExactlyElementsOf(requestHeaders().entrySet());
}
示例14: emptyObservableFromIndexCallShouldReturnZeroNodes
import io.reactivex.netty.protocol.http.client.HttpClientRequest; //导入依赖的package包/类
@Test
@SuppressWarnings("unchecked")
public void emptyObservableFromIndexCallShouldReturnZeroNodes() throws InterruptedException {
when(discoveryClient.getServices()).thenReturn(Collections.singletonList("service"));
ServiceInstance instance = mock(ServiceInstance.class);
when(discoveryClient.getInstances("service")).thenReturn(Collections.singletonList(instance));
when(instance.getServiceId()).thenReturn("service");
when(instance.getUri()).thenReturn(URI.create("http://localhost:8089/service"));
when(caller.retrieveJsonFromRequest(eq("service"), any(HttpClientRequest.class))).thenReturn(Observable.empty());
TestSubscriber<Node> testSubscriber = new TestSubscriber<>();
indexesAggregator.aggregateNodes().toBlocking().subscribe(testSubscriber);
List<Node> nodes = testSubscriber.getOnNextEvents();
assertThat(nodes).hasSize(0);
}
示例15: shouldGetHealthNodesFromService
import io.reactivex.netty.protocol.http.client.HttpClientRequest; //导入依赖的package包/类
@Test
public void shouldGetHealthNodesFromService() {
when(properties.getRequestHeaders()).thenReturn(requestHeaders());
Map retrievedMap = new HashMap();
Observable retrievedMapObservable = Observable.just(retrievedMap);
when(caller.retrieveJsonFromRequest(anyString(), any(HttpClientRequest.class)))
.thenReturn(retrievedMapObservable);
when(converter.convertToNodes(anyString(), anyMap()))
.thenReturn(Observable.from(correctNodes()));
TestSubscriber<Node> testSubscriber = new TestSubscriber<>();
aggregator.getHealthNodesFromService("testService", "testUrl", null).toBlocking().subscribe(testSubscriber);
List<Node> nodes = testSubscriber.getOnNextEvents();
verify(caller, times(1)).retrieveJsonFromRequest(eq("testService"), requestCaptor.capture());
assertThat(requestCaptor.getValue().getHeaders().entries()).usingElementComparator(stringEntryComparator())
.containsExactlyElementsOf(requestHeaders().entrySet());
assertThat(nodes).containsOnly(new Node("Node1"), new Node("Node2"));
}
开发者ID:ordina-jworks,项目名称:microservices-dashboard-server,代码行数:20,代码来源:HealthIndicatorsAggregatorTest.java