reactor.netty.http.client.HttpClientResponse Java Examples

The following examples show how to use reactor.netty.http.client.HttpClientResponse. 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: HttpClientFinalizerResponseConnectionInterceptor.java    From skywalking with Apache License 2.0 6 votes vote down vote up
@Override
public void beforeMethod(EnhancedInstance objInst, Method method, Object[] allArguments, Class<?>[] argumentsTypes,
                         MethodInterceptResult result) throws Throwable {
    BiFunction<? super HttpClientResponse, ? super Connection, ? extends Publisher> finalReceiver = (BiFunction<? super HttpClientResponse, ? super Connection, ? extends Publisher>) allArguments[0];
    EnhanceObjectCache cache = (EnhanceObjectCache) objInst.getSkyWalkingDynamicField();
    allArguments[0] = new BiFunction<HttpClientResponse, Connection, Publisher>() {
        @Override
        public Publisher apply(final HttpClientResponse response, final Connection connection) {
            Publisher publisher = finalReceiver.apply(response, connection);
            // receive the response. Stop the span.
            if (cache.getSpan() != null) {
                if (response.status().code() >= 400) {
                    cache.getSpan().errorOccurred();
                }
                Tags.STATUS_CODE.set(cache.getSpan(), String.valueOf(response.status().code()));
                cache.getSpan().asyncFinish();
            }

            if (cache.getSpan1() != null) {
                cache.getSpan1().asyncFinish();
            }
            return publisher;
        }
    };
}
 
Example #2
Source File: NettyRoutingFilter.java    From spring-cloud-gateway with Apache License 2.0 6 votes vote down vote up
private void setResponseStatus(HttpClientResponse clientResponse,
		ServerHttpResponse response) {
	HttpStatus status = HttpStatus.resolve(clientResponse.status().code());
	if (status != null) {
		response.setStatusCode(status);
	}
	else {
		while (response instanceof ServerHttpResponseDecorator) {
			response = ((ServerHttpResponseDecorator) response).getDelegate();
		}
		if (response instanceof AbstractServerHttpResponse) {
			((AbstractServerHttpResponse) response)
					.setStatusCodeValue(clientResponse.status().code());
		}
		else {
			// TODO: log warning here, not throw error?
			throw new IllegalStateException("Unable to set status code "
					+ clientResponse.status().code() + " on response of type "
					+ response.getClass().getName());
		}
	}
}
 
Example #3
Source File: NetUtils.java    From Shadbot with GNU General Public License v3.0 6 votes vote down vote up
private static <T> Mono<T> handleResponse(HttpClientResponse resp, ByteBufMono body, JavaType type) {
    final int statusCode = resp.status().code();
    if (statusCode / 100 != 2 && statusCode != 404) {
        return body.asString()
                .defaultIfEmpty("Empty body")
                .flatMap(err -> Mono.error(new ServerAccessException(resp, err)));
    }
    if (!resp.responseHeaders().get(HttpHeaderNames.CONTENT_TYPE).startsWith(HttpHeaderValues.APPLICATION_JSON.toString())) {
        return body.asString()
                .defaultIfEmpty("Empty body")
                .flatMap(err -> Mono.error(new HeaderException(resp, err)));
    }

    return body.asInputStream()
            .flatMap(input -> Mono.fromCallable(() -> NetUtils.MAPPER.readValue(input, type)));
}
 
Example #4
Source File: TitusWebClientAddOns.java    From titus-control-plane with Apache License 2.0 6 votes vote down vote up
/**
 * {@link HttpClientResponse#uri()} is incomplete, and contains only URL path. We have to reconstruct full URL
 * from pieces available. It is still not complete, as there is no way to find out if this is plain text or
 * TLS connection.
 */
private static String buildFullUri(HttpClientResponse response) {
    if (response instanceof HttpOperations) {
        HttpOperations httpOperations = (HttpOperations) response;

        StringBuilder sb = new StringBuilder("http://");

        InetSocketAddress address = httpOperations.address();
        sb.append(address.getHostString());
        sb.append(':').append(address.getPort());

        String path = response.path();
        if (!path.startsWith("/")) {
            sb.append('/');
        }
        sb.append(path);

        return sb.toString();
    }
    return response.path();
}
 
Example #5
Source File: ResponseHeaderStrategy.java    From Discord4J with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public Duration apply(HttpClientResponse response) {
    HttpHeaders headers = response.responseHeaders();
    int remaining = headers.getInt("X-RateLimit-Remaining", -1);
    if (remaining == 0) {
        long resetAt = (long) (Double.parseDouble(headers.get("X-RateLimit-Reset-After")) * 1000);
        return Duration.ofMillis(resetAt);
    }
    return Duration.ZERO;
}
 
Example #6
Source File: ReactorNettyHttpClientSpringBootTests.java    From spring-cloud-sleuth with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldRecordRemoteEndpoint() throws Exception {
	disposableServer = HttpServer.create().port(0)
			.handle((in, out) -> out.sendString(Flux.just("foo"))).bindNow();

	HttpClientResponse response = httpClient.port(disposableServer.port()).get()
			.uri("/").response().block();

	assertThat(response.status()).isEqualTo(HttpResponseStatus.OK);

	MutableSpan clientSpan = spanHandler.takeRemoteSpan(CLIENT);

	assertThat(clientSpan.remoteIp()).isNotNull();
	assertThat(clientSpan.remotePort()).isNotZero();
}
 
Example #7
Source File: HttpClientBeanPostProcessor.java    From spring-cloud-sleuth with Apache License 2.0 5 votes vote down vote up
void handle(Context context, @Nullable HttpClientResponse resp,
		@Nullable Throwable error) {
	PendingSpan pendingSpan = context.getOrDefault(PendingSpan.class, null);
	if (pendingSpan == null) {
		return; // Somehow TracingMapConnect was not invoked.. skip out
	}

	Span span = pendingSpan.getAndSet(null);
	if (span == null) {
		return; // Unexpected. In the handle method, without a span to finish!
	}
	HttpClientResponseWrapper response = resp != null
			? new HttpClientResponseWrapper(resp) : null;
	handler().handleReceive(response, error, span);
}
 
Example #8
Source File: ClientException.java    From Discord4J with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Create a new {@link ClientException} with the given HTTP request and response details.
 *
 * @param request the original {@link ClientRequest} that caused this exception
 * @param response the failing {@link HttpClientResponse}
 * @param errorResponse the response body converted to an {@link ErrorResponse}, or {@code null} if not available
 */
public ClientException(ClientRequest request, HttpClientResponse response, @Nullable ErrorResponse errorResponse) {
    super(request.getMethod().toString() + " " + request.getUrl() + " returned " + response.status().toString() +
            (errorResponse != null ? " with response " + errorResponse.getFields() : ""));
    this.request = request;
    this.status = response.status();
    this.headers = response.responseHeaders();
    this.errorResponse = errorResponse;
}
 
Example #9
Source File: ClientResponse.java    From Discord4J with GNU Lesser General Public License v3.0 5 votes vote down vote up
ClientResponse(HttpClientResponse response, NettyInbound inbound, ExchangeStrategies exchangeStrategies,
               ClientRequest clientRequest, List<ResponseFunction> responseFunctions) {
    this.response = response;
    this.inbound = inbound;
    this.exchangeStrategies = exchangeStrategies;
    this.clientRequest = clientRequest;
    this.responseFunctions = responseFunctions;
}
 
Example #10
Source File: RequestStream.java    From Discord4J with GNU Lesser General Public License v3.0 5 votes vote down vote up
public RequestSubscriber(RateLimitStrategy strategy) {
    this.responseFunction = response -> {
        HttpClientResponse httpResponse = response.getHttpResponse();
        if (log.isDebugEnabled()) {
            Instant requestTimestamp =
                    Instant.ofEpochMilli(httpResponse.currentContext().get(DiscordWebClient.KEY_REQUEST_TIMESTAMP));
            Duration responseTime = Duration.between(requestTimestamp, Instant.now());
            LogUtil.traceDebug(log, trace -> format(httpResponse.currentContext(),
                    "Read " + httpResponse.status() + " in " + responseTime + (!trace ? "" :
                            " with headers: " + httpResponse.responseHeaders())));
        }
        Duration nextReset = strategy.apply(httpResponse);
        if (!nextReset.isZero()) {
            if (log.isDebugEnabled()) {
                log.debug(format(httpResponse.currentContext(), "Delaying next request by {}"), nextReset);
            }
            sleepTime = nextReset;
        }
        boolean global = Boolean.parseBoolean(httpResponse.responseHeaders().get("X-RateLimit-Global"));
        Mono<Void> action = Mono.empty();
        if (global) {
            long retryAfter = Long.parseLong(httpResponse.responseHeaders().get("Retry-After"));
            Duration fixedBackoff = Duration.ofMillis(retryAfter);
            action = globalRateLimiter.rateLimitFor(fixedBackoff)
                    .doOnTerminate(() -> log.debug(format(httpResponse.currentContext(),
                            "Globally rate limited for {}"), fixedBackoff));
        }
        if (httpResponse.status().code() >= 400) {
            return action.then(response.createException().flatMap(Mono::error));
        } else {
            return action.thenReturn(response);
        }
    };
}
 
Example #11
Source File: SeparatedTransport.java    From etherjar with Apache License 2.0 5 votes vote down vote up
/**
 * Read response
 * @param resp HTTP Response headers
 * @param data HTTP Response data
 * @return publisher of read bytes
 * @throws RpcException if status code is not 200 of an error happened on reading data
 */
protected Publisher<byte[]> read(HttpClientResponse resp, ByteBufFlux data) {
    if (resp.status() == HttpResponseStatus.OK) {
        return data.aggregate()
            .asByteArray()
            .onErrorResume((t) ->
                Mono.error(new RpcException(RpcResponseError.CODE_UPSTREAM_INVALID_RESPONSE, "Upstream connection error. Failed to read response"))
            );
    } else {
        throw new RpcException(RpcResponseError.CODE_UPSTREAM_INVALID_RESPONSE, "Upstream connection error. Status: " + resp.status().code());
    }
}
 
Example #12
Source File: HeaderException.java    From Shadbot with GNU General Public License v3.0 5 votes vote down vote up
public HeaderException(HttpClientResponse response, String body) {
    super(String.format("%s %s wrong header (%s) %s",
            response.method().asciiName(), response.resourceUrl(),
            response.responseHeaders().get(HttpHeaderNames.CONTENT_TYPE), body));
    this.response = response;
    this.body = body;
}
 
Example #13
Source File: ReactorClientHttpResponse.java    From spring-analysis-note with MIT License 4 votes vote down vote up
public ReactorClientHttpResponse(HttpClientResponse response, NettyInbound inbound, ByteBufAllocator alloc) {
	this.response = response;
	this.inbound = inbound;
	this.bufferFactory = new NettyDataBufferFactory(alloc);
}
 
Example #14
Source File: WebClientMetric.java    From titus-control-plane with Apache License 2.0 4 votes vote down vote up
public void incrementOnError(HttpClientResponse response, Throwable throwable) {
    delegate.incrementOnError(response.method().name(), response.path(), throwable);
}
 
Example #15
Source File: ReactorClientHttpConnector.java    From java-technology-stack with MIT License 4 votes vote down vote up
private ClientHttpResponse adaptResponse(HttpClientResponse response, NettyInbound nettyInbound,
		ByteBufAllocator allocator) {

	return new ReactorClientHttpResponse(response, nettyInbound, allocator);
}
 
Example #16
Source File: HttpClientBeanPostProcessor.java    From spring-cloud-sleuth with Apache License 2.0 4 votes vote down vote up
HttpClientResponseWrapper(HttpClientResponse delegate) {
	this.delegate = delegate;
}
 
Example #17
Source File: ReactorClientHttpResponse.java    From java-technology-stack with MIT License 4 votes vote down vote up
public ReactorClientHttpResponse(HttpClientResponse response, NettyInbound inbound, ByteBufAllocator alloc) {
	this.response = response;
	this.inbound = inbound;
	this.bufferFactory = new NettyDataBufferFactory(alloc);
}
 
Example #18
Source File: HttpClientBeanPostProcessor.java    From spring-cloud-sleuth with Apache License 2.0 4 votes vote down vote up
HttpClientHandler<brave.http.HttpClientRequest, brave.http.HttpClientResponse> handler() {
	if (this.handler == null) {
		this.handler = HttpClientHandler.create(httpTracing.get());
	}
	return this.handler;
}
 
Example #19
Source File: HttpClientBeanPostProcessor.java    From spring-cloud-sleuth with Apache License 2.0 4 votes vote down vote up
@Override
public void accept(HttpClientResponse response, Throwable error) {
	handle(response.currentContext(), response, error);
}
 
Example #20
Source File: HttpClientBeanPostProcessor.java    From spring-cloud-sleuth with Apache License 2.0 4 votes vote down vote up
@Override
public void accept(HttpClientResponse response, Connection connection) {
	handle(response.currentContext(), response, null);
}
 
Example #21
Source File: HttpClientBeanPostProcessor.java    From spring-cloud-sleuth with Apache License 2.0 4 votes vote down vote up
HttpClientHandler<brave.http.HttpClientRequest, brave.http.HttpClientResponse> handler() {
	if (this.handler == null) {
		this.handler = HttpClientHandler.create(httpTracing.get());
	}
	return this.handler;
}
 
Example #22
Source File: ClientResponse.java    From Discord4J with GNU Lesser General Public License v3.0 4 votes vote down vote up
private static ClientException clientException(ClientRequest request, HttpClientResponse response,
                                               @Nullable ErrorResponse errorResponse) {
    return new ClientException(request, response, errorResponse);
}
 
Example #23
Source File: HeaderException.java    From Shadbot with GNU General Public License v3.0 4 votes vote down vote up
public HttpClientResponse getResponse() {
    return this.response;
}
 
Example #24
Source File: ServerAccessException.java    From Shadbot with GNU General Public License v3.0 4 votes vote down vote up
public ServerAccessException(HttpClientResponse response, String body) {
    super(String.format("%s %s failed (%d) %s",
            response.method().asciiName(), response.resourceUrl(), response.status().code(), body));
    this.response = response;
    this.body = body;
}
 
Example #25
Source File: ReactorClientHttpConnector.java    From spring-analysis-note with MIT License 4 votes vote down vote up
private ClientHttpResponse adaptResponse(HttpClientResponse response, NettyInbound nettyInbound,
		ByteBufAllocator allocator) {

	return new ReactorClientHttpResponse(response, nettyInbound, allocator);
}
 
Example #26
Source File: ServerAccessException.java    From Shadbot with GNU General Public License v3.0 4 votes vote down vote up
public HttpClientResponse getResponse() {
    return this.response;
}
 
Example #27
Source File: WebClientMetric.java    From titus-control-plane with Apache License 2.0 4 votes vote down vote up
public void incrementOnSuccess(HttpClientResponse response, Connection connection) {
    delegate.incrementOnSuccess(response.method().name(), response.path(), response.status().toString());
}
 
Example #28
Source File: ClientResponse.java    From Discord4J with GNU Lesser General Public License v3.0 2 votes vote down vote up
/**
 * Return the underlying {@link HttpClientResponse} from where you can access the response headers, status and
 * context.
 *
 * @return this response {@link HttpClientResponse}
 */
public HttpClientResponse getHttpResponse() {
    return response;
}
 
Example #29
Source File: RateLimitStrategy.java    From Discord4J with GNU Lesser General Public License v3.0 2 votes vote down vote up
/**
 * Apply this function to a {@link HttpClientResponse} to obtain a {@link Duration} representing a delay due to
 * rate limiting.
 *
 * @param response the original {@link HttpClientResponse}
 * @return a {@link Duration} indicating rate limiting, can be {@link Duration#ZERO} if no limit is present
 */
Duration apply(HttpClientResponse response);