Search in sources :

Example 1 with HttpResponse

use of io.fabric8.kubernetes.client.http.HttpResponse in project kubernetes-client by fabric8io.

the class JdkHttpClientImpl method sendAsync.

@Override
public <T> CompletableFuture<HttpResponse<T>> sendAsync(HttpRequest request, Class<T> type) {
    JdkHttpRequestImpl jdkRequest = (JdkHttpRequestImpl) request;
    JdkHttpRequestImpl.BuilderImpl builderImpl = jdkRequest.newBuilder();
    for (Interceptor interceptor : builder.interceptors.values()) {
        interceptor.before(builderImpl, jdkRequest);
        jdkRequest = builderImpl.build();
    }
    BodyHandler<T> bodyHandler;
    if (type == null) {
        bodyHandler = (BodyHandler<T>) BodyHandlers.discarding();
    } else if (type == InputStream.class) {
        bodyHandler = (BodyHandler<T>) BodyHandlers.ofInputStream();
    } else if (type == String.class) {
        bodyHandler = (BodyHandler<T>) BodyHandlers.ofString();
    } else {
        bodyHandler = responseInfo -> {
            BodySubscriber<InputStream> upstream = BodyHandlers.ofInputStream().apply(responseInfo);
            BodySubscriber<Reader> downstream = BodySubscribers.mapping(upstream, (InputStream is) -> new InputStreamReader(is, StandardCharsets.UTF_8));
            return (BodySubscriber<T>) downstream;
        };
    }
    CompletableFuture<java.net.http.HttpResponse<T>> cf = this.httpClient.sendAsync(builderImpl.build().request, bodyHandler);
    for (Interceptor interceptor : builder.interceptors.values()) {
        cf = cf.thenCompose(response -> {
            if (response != null && !HttpResponse.isSuccessful(response.statusCode()) && interceptor.afterFailure(builderImpl, new JdkHttpResponseImpl<>(response))) {
                return this.httpClient.sendAsync(builderImpl.build().request, bodyHandler);
            }
            return CompletableFuture.completedFuture(response);
        });
    }
    return cf.thenApply(JdkHttpResponseImpl::new);
}
Also used : BodyHandlers(java.net.http.HttpResponse.BodyHandlers) Listener(io.fabric8.kubernetes.client.http.WebSocket.Listener) HttpRequest(io.fabric8.kubernetes.client.http.HttpRequest) BodySubscribers(java.net.http.HttpResponse.BodySubscribers) BodyHandler(java.net.http.HttpResponse.BodyHandler) BodySubscriber(java.net.http.HttpResponse.BodySubscriber) IOException(java.io.IOException) CompletableFuture(java.util.concurrent.CompletableFuture) CompletionException(java.util.concurrent.CompletionException) HttpResponse(io.fabric8.kubernetes.client.http.HttpResponse) Reader(java.io.Reader) InputStreamReader(java.io.InputStreamReader) InterruptedIOException(java.io.InterruptedIOException) StandardCharsets(java.nio.charset.StandardCharsets) ExecutionException(java.util.concurrent.ExecutionException) AtomicLong(java.util.concurrent.atomic.AtomicLong) List(java.util.List) Interceptor(io.fabric8.kubernetes.client.http.Interceptor) WebSocketHandshakeException(java.net.http.WebSocketHandshakeException) Optional(java.util.Optional) WebSocket(io.fabric8.kubernetes.client.http.WebSocket) URI(java.net.URI) HttpClient(io.fabric8.kubernetes.client.http.HttpClient) InputStream(java.io.InputStream) InputStreamReader(java.io.InputStreamReader) InputStream(java.io.InputStream) Reader(java.io.Reader) InputStreamReader(java.io.InputStreamReader) HttpResponse(io.fabric8.kubernetes.client.http.HttpResponse) BodySubscriber(java.net.http.HttpResponse.BodySubscriber) BodyHandler(java.net.http.HttpResponse.BodyHandler) Interceptor(io.fabric8.kubernetes.client.http.Interceptor)

Example 2 with HttpResponse

use of io.fabric8.kubernetes.client.http.HttpResponse in project kubernetes-client by fabric8io.

the class OkHttpClientImpl method sendAsync.

@Override
public <T> CompletableFuture<HttpResponse<T>> sendAsync(HttpRequest request, Class<T> type) {
    CompletableFuture<HttpResponse<T>> future = new CompletableFuture<>();
    Call call = httpClient.newCall(((OkHttpRequestImpl) request).getRequest());
    call.enqueue(new Callback() {

        @Override
        public void onResponse(Call call, Response response) throws IOException {
            future.complete(new OkHttpResponseImpl<>(response, type));
        }

        @Override
        public void onFailure(Call call, IOException e) {
            future.completeExceptionally(e);
        }
    });
    future.whenComplete((r, t) -> {
        if (future.isCancelled()) {
            call.cancel();
        }
    });
    return future;
}
Also used : HttpResponse(io.fabric8.kubernetes.client.http.HttpResponse) Response(okhttp3.Response) Call(okhttp3.Call) CompletableFuture(java.util.concurrent.CompletableFuture) Callback(okhttp3.Callback) HttpResponse(io.fabric8.kubernetes.client.http.HttpResponse) IOException(java.io.IOException)

Example 3 with HttpResponse

use of io.fabric8.kubernetes.client.http.HttpResponse in project kubernetes-client by fabric8io.

the class BackwardsCompatibilityInterceptor method afterFailure.

@Override
public boolean afterFailure(Builder builder, HttpResponse<?> response) {
    ResourceKey target = findNewTarget(builder, response);
    if (target == null) {
        return false;
    }
    HttpRequest request = response.request();
    if (request.bodyString() != null && !request.method().equalsIgnoreCase(PATCH)) {
        Object object = Serialization.unmarshal(request.bodyString());
        if (object instanceof HasMetadata) {
            HasMetadata h = (HasMetadata) object;
            h.setApiVersion(target.group + "/" + target.version);
            switch(request.method()) {
                case "POST":
                    builder.post(JSON, Serialization.asJson(h));
                    break;
                case "PUT":
                    builder.put(JSON, Serialization.asJson(h));
                    break;
                case "DELETE":
                    builder.delete(JSON, Serialization.asJson(h));
                    break;
                default:
                    return false;
            }
        }
    }
    return true;
}
Also used : HttpRequest(io.fabric8.kubernetes.client.http.HttpRequest) HasMetadata(io.fabric8.kubernetes.api.model.HasMetadata)

Example 4 with HttpResponse

use of io.fabric8.kubernetes.client.http.HttpResponse in project kubernetes-client by fabric8io.

the class OpenIDConnectionUtils method getOIDCDiscoveryDocumentAsMap.

/**
 * OpenID providers publish their metadata at a well-known URL OpenID providers publish their metadata
 * at a well-known URL which looks like this: https://[base-server-url]/.well-known/openid-configuration
 * This method performs an Http Get at this public URL and fetches response as a HashMap
 *
 * @param client HttpClient for doing HTTP Get to well known URL of OpenID provider
 * @param issuer OpenID Connect provider issuer URL
 * @return a HashMap of Discovery document
 */
static Map<String, Object> getOIDCDiscoveryDocumentAsMap(HttpClient client, String issuer) {
    HttpRequest request = client.newHttpRequestBuilder().uri(getWellKnownUrlForOpenIDIssuer(issuer)).build();
    try {
        HttpResponse<String> response = client.send(request, String.class);
        if (response.isSuccessful() && response.body() != null) {
            return convertJsonStringToMap(response.body());
        } else {
            // Don't produce an error that's too huge (e.g. if we get HTML back for some reason).
            String responseBody = response.body();
            LOGGER.warn("oidc: failed to query metadata endpoint: {} {}", response.code(), responseBody);
        }
    } catch (IOException e) {
        LOGGER.warn("Could not refresh OIDC token, failure in getting refresh URL", e);
    }
    return Collections.emptyMap();
}
Also used : HttpRequest(io.fabric8.kubernetes.client.http.HttpRequest) IOException(java.io.IOException)

Example 5 with HttpResponse

use of io.fabric8.kubernetes.client.http.HttpResponse in project kubernetes-client by fabric8io.

the class OpenIDConnectionUtils method refreshOidcToken.

/**
 * Issue Token Refresh HTTP Request to OIDC Provider
 *
 * @param client Http Client for issuing HTTP request
 * @param clientId client id
 * @param refreshToken refresh token
 * @param clientSecret client secret
 * @param tokenURL OpenID Connection provider's token refresh url
 * @return response as HashMap
 * @throws IOException in case of any error in contacting OIDC provider
 */
static Map<String, Object> refreshOidcToken(HttpClient client, String clientId, String refreshToken, String clientSecret, String tokenURL) throws IOException {
    HttpRequest request = getTokenRefreshHttpRequest(client, tokenURL, clientId, refreshToken, clientSecret);
    HttpResponse<String> response = client.send(request, String.class);
    String body = response.body();
    if (body != null) {
        // Get response body as string
        if (response.isSuccessful()) {
            // Deserialize response body into a Map and return
            return convertJsonStringToMap(body);
        } else {
            // Log error response body
            LOGGER.warn("Response: {}", body);
        }
    }
    return Collections.emptyMap();
}
Also used : HttpRequest(io.fabric8.kubernetes.client.http.HttpRequest)

Aggregations

HttpRequest (io.fabric8.kubernetes.client.http.HttpRequest)10 InputStream (java.io.InputStream)9 HttpClient (io.fabric8.kubernetes.client.http.HttpClient)7 IOException (java.io.IOException)7 HttpResponse (io.fabric8.kubernetes.client.http.HttpResponse)5 CompletableFuture (java.util.concurrent.CompletableFuture)4 Status (io.fabric8.kubernetes.api.model.Status)3 KubernetesClientException (io.fabric8.kubernetes.client.KubernetesClientException)3 URI (java.net.URI)3 HttpResponse (org.apache.http.HttpResponse)3 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)2 CreateRepositoryDTO (io.fabric8.gerrit.CreateRepositoryDTO)2 HasMetadata (io.fabric8.kubernetes.api.model.HasMetadata)2 NamespaceBuilder (io.fabric8.kubernetes.api.model.NamespaceBuilder)2 Builder (io.fabric8.kubernetes.client.http.HttpRequest.Builder)2 Interceptor (io.fabric8.kubernetes.client.http.Interceptor)2 WebSocket (io.fabric8.kubernetes.client.http.WebSocket)2 WebSocketHandshakeException (io.fabric8.kubernetes.client.http.WebSocketHandshakeException)2 InputStreamReader (java.io.InputStreamReader)2 MalformedURLException (java.net.MalformedURLException)2