Search in sources :

Example 6 with Route

use of com.google.cloud.compute.v1.Route in project okhttp by square.

the class RetryAndFollowUpInterceptor method followUpRequest.

/**
   * Figures out the HTTP request to make in response to receiving {@code userResponse}. This will
   * either add authentication headers, follow redirects or handle a client request timeout. If a
   * follow-up is either unnecessary or not applicable, this returns null.
   */
private Request followUpRequest(Response userResponse) throws IOException {
    if (userResponse == null)
        throw new IllegalStateException();
    Connection connection = streamAllocation.connection();
    Route route = connection != null ? connection.route() : null;
    int responseCode = userResponse.code();
    final String method = userResponse.request().method();
    switch(responseCode) {
        case HTTP_PROXY_AUTH:
            Proxy selectedProxy = route != null ? route.proxy() : client.proxy();
            if (selectedProxy.type() != Proxy.Type.HTTP) {
                throw new ProtocolException("Received HTTP_PROXY_AUTH (407) code while not using proxy");
            }
            return client.proxyAuthenticator().authenticate(route, userResponse);
        case HTTP_UNAUTHORIZED:
            return client.authenticator().authenticate(route, userResponse);
        case HTTP_PERM_REDIRECT:
        case HTTP_TEMP_REDIRECT:
            // or HEAD, the user agent MUST NOT automatically redirect the request"
            if (!method.equals("GET") && !method.equals("HEAD")) {
                return null;
            }
        // fall-through
        case HTTP_MULT_CHOICE:
        case HTTP_MOVED_PERM:
        case HTTP_MOVED_TEMP:
        case HTTP_SEE_OTHER:
            // Does the client allow redirects?
            if (!client.followRedirects())
                return null;
            String location = userResponse.header("Location");
            if (location == null)
                return null;
            HttpUrl url = userResponse.request().url().resolve(location);
            // Don't follow redirects to unsupported protocols.
            if (url == null)
                return null;
            // If configured, don't follow redirects between SSL and non-SSL.
            boolean sameScheme = url.scheme().equals(userResponse.request().url().scheme());
            if (!sameScheme && !client.followSslRedirects())
                return null;
            // Most redirects don't include a request body.
            Request.Builder requestBuilder = userResponse.request().newBuilder();
            if (HttpMethod.permitsRequestBody(method)) {
                final boolean maintainBody = HttpMethod.redirectsWithBody(method);
                if (HttpMethod.redirectsToGet(method)) {
                    requestBuilder.method("GET", null);
                } else {
                    RequestBody requestBody = maintainBody ? userResponse.request().body() : null;
                    requestBuilder.method(method, requestBody);
                }
                if (!maintainBody) {
                    requestBuilder.removeHeader("Transfer-Encoding");
                    requestBuilder.removeHeader("Content-Length");
                    requestBuilder.removeHeader("Content-Type");
                }
            }
            // way to retain them.
            if (!sameConnection(userResponse, url)) {
                requestBuilder.removeHeader("Authorization");
            }
            return requestBuilder.url(url).build();
        case HTTP_CLIENT_TIMEOUT:
            // repeat the request (even non-idempotent ones.)
            if (userResponse.request().body() instanceof UnrepeatableRequestBody) {
                return null;
            }
            return userResponse.request();
        default:
            return null;
    }
}
Also used : ProtocolException(java.net.ProtocolException) Connection(okhttp3.Connection) Request(okhttp3.Request) HttpUrl(okhttp3.HttpUrl) Proxy(java.net.Proxy) Route(okhttp3.Route) RequestBody(okhttp3.RequestBody)

Example 7 with Route

use of com.google.cloud.compute.v1.Route in project okhttp by square.

the class StreamAllocation method findConnection.

/**
   * Returns a connection to host a new stream. This prefers the existing connection if it exists,
   * then the pool, finally building a new connection.
   */
private RealConnection findConnection(int connectTimeout, int readTimeout, int writeTimeout, boolean connectionRetryEnabled) throws IOException {
    Route selectedRoute;
    synchronized (connectionPool) {
        if (released)
            throw new IllegalStateException("released");
        if (codec != null)
            throw new IllegalStateException("codec != null");
        if (canceled)
            throw new IOException("Canceled");
        // Attempt to use an already-allocated connection.
        RealConnection allocatedConnection = this.connection;
        if (allocatedConnection != null && !allocatedConnection.noNewStreams) {
            return allocatedConnection;
        }
        // Attempt to get a connection from the pool.
        Internal.instance.get(connectionPool, address, this, null);
        if (connection != null) {
            return connection;
        }
        selectedRoute = route;
    }
    // If we need a route, make one. This is a blocking operation.
    if (selectedRoute == null) {
        selectedRoute = routeSelector.next();
    }
    RealConnection result;
    synchronized (connectionPool) {
        if (canceled)
            throw new IOException("Canceled");
        // Now that we have an IP address, make another attempt at getting a connection from the pool.
        // This could match due to connection coalescing.
        Internal.instance.get(connectionPool, address, this, selectedRoute);
        if (connection != null)
            return connection;
        // Create a connection and assign it to this allocation immediately. This makes it possible
        // for an asynchronous cancel() to interrupt the handshake we're about to do.
        route = selectedRoute;
        refusedStreamCount = 0;
        result = new RealConnection(connectionPool, selectedRoute);
        acquire(result);
    }
    // Do TCP + TLS handshakes. This is a blocking operation.
    result.connect(connectTimeout, readTimeout, writeTimeout, connectionRetryEnabled);
    routeDatabase().connected(result.route());
    Socket socket = null;
    synchronized (connectionPool) {
        // Pool the connection.
        Internal.instance.put(connectionPool, result);
        // release this connection and acquire that one.
        if (result.isMultiplexed()) {
            socket = Internal.instance.deduplicate(connectionPool, address, this);
            result = connection;
        }
    }
    closeQuietly(socket);
    return result;
}
Also used : IOException(java.io.IOException) Route(okhttp3.Route) Socket(java.net.Socket)

Example 8 with Route

use of com.google.cloud.compute.v1.Route in project okhttp by square.

the class RouteSelectorTest method singleRouteReturnsFailedRoute.

@Test
public void singleRouteReturnsFailedRoute() throws Exception {
    Address address = httpAddress();
    RouteSelector routeSelector = new RouteSelector(address, routeDatabase);
    assertTrue(routeSelector.hasNext());
    dns.set(uriHost, dns.allocate(1));
    Route route = routeSelector.next();
    routeDatabase.failed(route);
    routeSelector = new RouteSelector(address, routeDatabase);
    assertRoute(routeSelector.next(), address, NO_PROXY, dns.lookup(uriHost, 0), uriPort);
    assertFalse(routeSelector.hasNext());
    try {
        routeSelector.next();
        fail();
    } catch (NoSuchElementException expected) {
    }
}
Also used : SocketAddress(java.net.SocketAddress) Address(okhttp3.Address) InetAddress(java.net.InetAddress) InetSocketAddress(java.net.InetSocketAddress) Route(okhttp3.Route) NoSuchElementException(java.util.NoSuchElementException) Test(org.junit.Test)

Example 9 with Route

use of com.google.cloud.compute.v1.Route in project couchbase-lite-android by couchbase.

the class CBLWebSocket method setupAuthenticator.

private Authenticator setupAuthenticator() {
    if (options != null && options.containsKey(kC4ReplicatorOptionAuthentication)) {
        Map<String, Object> auth = (Map<String, Object>) options.get(kC4ReplicatorOptionAuthentication);
        if (auth != null) {
            final String username = (String) auth.get(kC4ReplicatorAuthUserName);
            final String password = (String) auth.get(kC4ReplicatorAuthPassword);
            if (username != null && password != null) {
                return new Authenticator() {

                    @Override
                    public Request authenticate(Route route, Response response) throws IOException {
                        // http://www.ietf.org/rfc/rfc2617.txt
                        Log.v(TAG, "Authenticating for response: " + response);
                        // If failed 3 times, give up.
                        if (responseCount(response) >= 3)
                            return null;
                        List<Challenge> challenges = response.challenges();
                        Log.v(TAG, "Challenges: " + challenges);
                        if (challenges != null) {
                            for (Challenge challenge : challenges) {
                                if (challenge.scheme().equals("Basic")) {
                                    String credential = Credentials.basic(username, password);
                                    return response.request().newBuilder().header("Authorization", credential).build();
                                }
                            // NOTE: Not implemented Digest authentication
                            // https://github.com/rburgst/okhttp-digest
                            // else if(challenge.scheme().equals("Digest")){
                            // }
                            }
                        }
                        return null;
                    }
                };
            }
        }
    }
    return null;
}
Also used : Response(okhttp3.Response) ByteString(okio.ByteString) HashMap(java.util.HashMap) Map(java.util.Map) Authenticator(okhttp3.Authenticator) Route(okhttp3.Route) Challenge(okhttp3.Challenge)

Example 10 with Route

use of com.google.cloud.compute.v1.Route in project hub-fortify-ssc-integration-service by blackducksoftware.

the class FortifyService method getHeader.

public static Builder getHeader(String userName, String password) {
    HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
    logging.setLevel(Level.BASIC);
    OkHttpClient.Builder okBuilder = new OkHttpClient.Builder();
    okBuilder.authenticator(new Authenticator() {

        @Override
        public Request authenticate(Route route, Response response) throws IOException {
            String credential = Credentials.basic(userName, password);
            if (credential.equals(response.request().header("Authorization"))) {
                try {
                    FortifyExceptionUtil.verifyFortifyResponseCode(response.code(), "Unauthorized access of Fortify Api");
                } catch (IntegrationException e) {
                    throw new IOException(e);
                }
                return null;
            }
            return response.request().newBuilder().header("Authorization", credential).build();
        }
    });
    okBuilder.addInterceptor(logging);
    return okBuilder;
}
Also used : Builder(okhttp3.OkHttpClient.Builder) Response(okhttp3.Response) OkHttpClient(okhttp3.OkHttpClient) IntegrationException(com.blackducksoftware.integration.exception.IntegrationException) Builder(okhttp3.OkHttpClient.Builder) Request(okhttp3.Request) IOException(java.io.IOException) HttpLoggingInterceptor(okhttp3.logging.HttpLoggingInterceptor) Authenticator(okhttp3.Authenticator) Route(okhttp3.Route)

Aggregations

Route (okhttp3.Route)30 Response (okhttp3.Response)16 Authenticator (okhttp3.Authenticator)14 Request (okhttp3.Request)12 IOException (java.io.IOException)10 OkHttpClient (okhttp3.OkHttpClient)10 InetSocketAddress (java.net.InetSocketAddress)9 Route (org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev171207.Route)9 Proxy (java.net.Proxy)7 Route (io.fabric8.knative.serving.v1.Route)6 RouteBuilder (io.fabric8.knative.serving.v1.RouteBuilder)6 Test (org.junit.Test)6 Test (org.junit.jupiter.api.Test)6 InstanceIdentifier (org.opendaylight.yangtools.yang.binding.InstanceIdentifier)6 KeyedInstanceIdentifier (org.opendaylight.yangtools.yang.binding.KeyedInstanceIdentifier)6 Address (okhttp3.Address)5 Connection (okhttp3.Connection)5 RIBSupport (org.opendaylight.protocol.bgp.rib.spi.RIBSupport)5 Identifier (org.opendaylight.yangtools.yang.binding.Identifier)5 Builder (okhttp3.OkHttpClient.Builder)4