Search in sources :

Example 1 with Route

use of org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.Route in project azure-sdk-for-java by Azure.

the class KeyVaultCredentials method applyCredentialsFilter.

@Override
public void applyCredentialsFilter(OkHttpClient.Builder clientBuilder) {
    clientBuilder.addInterceptor(new Interceptor() {

        @Override
        public Response intercept(Chain chain) throws IOException {
            HttpUrl url = chain.request().url();
            Map<String, String> challengeMap = cache.getCachedChallenge(url);
            if (challengeMap != null) {
                // Get the bearer token
                String credential = getAuthenticationCredentials(challengeMap);
                Request newRequest = chain.request().newBuilder().header(AUTHENTICATE, BEARER_TOKEP_REFIX + credential).build();
                return chain.proceed(newRequest);
            } else {
                // response
                return chain.proceed(chain.request());
            }
        }
    });
    // Caches the challenge for failed request and re-send the request with
    // access token.
    clientBuilder.authenticator(new Authenticator() {

        @Override
        public Request authenticate(Route route, Response response) throws IOException {
            // if challenge is not cached then extract and cache it
            String authenticateHeader = response.header(WWW_AUTHENTICATE);
            Map<String, String> challengeMap = extractChallenge(authenticateHeader, BEARER_TOKEP_REFIX);
            // Cache the challenge
            cache.addCachedChallenge(response.request().url(), challengeMap);
            // Get the bearer token from the callback by providing the
            // challenges
            String credential = getAuthenticationCredentials(challengeMap);
            if (credential == null) {
                return null;
            }
            // be cached anywhere in our code.
            return response.request().newBuilder().header(AUTHENTICATE, BEARER_TOKEP_REFIX + credential).build();
        }
    });
}
Also used : Response(okhttp3.Response) Request(okhttp3.Request) IOException(java.io.IOException) Interceptor(okhttp3.Interceptor) Map(java.util.Map) HashMap(java.util.HashMap) HttpUrl(okhttp3.HttpUrl) Authenticator(okhttp3.Authenticator) Route(okhttp3.Route)

Example 2 with Route

use of org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.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 3 with Route

use of org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.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 4 with Route

use of org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.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 5 with Route

use of org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.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)

Aggregations

ArrayList (java.util.ArrayList)82 VpnInstanceOpDataEntry (org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.vpn.instance.op.data.VpnInstanceOpDataEntry)57 ExecutionException (java.util.concurrent.ExecutionException)55 VrfEntry (org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.fibmanager.rev150330.vrfentries.VrfEntry)55 Uint32 (org.opendaylight.yangtools.yang.common.Uint32)51 Uint64 (org.opendaylight.yangtools.yang.common.Uint64)45 Test (org.junit.Test)44 InstanceIdentifier (org.opendaylight.yangtools.yang.binding.InstanceIdentifier)43 Uuid (org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.Uuid)40 BigInteger (java.math.BigInteger)33 List (java.util.List)33 VrfTablesKey (org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.fibmanager.rev150330.fibentries.VrfTablesKey)33 Logger (org.slf4j.Logger)33 LoggerFactory (org.slf4j.LoggerFactory)33 Singleton (javax.inject.Singleton)32 Inject (javax.inject.Inject)30 RouteOrigin (org.opendaylight.netvirt.fibmanager.api.RouteOrigin)30 Collections (java.util.Collections)29 Prefixes (org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.prefix.to._interface.vpn.ids.Prefixes)29 Routes (org.opendaylight.yang.gen.v1.urn.opendaylight.netvirt.l3vpn.rev130911.vpn.to.extraroutes.vpn.extra.routes.Routes)29