1 /* 2 * Copyright (C) 2013 Square, Inc. 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 package com.squareup.okhttp; 17 18 import java.io.IOException; 19 import java.util.LinkedHashSet; 20 import java.util.Set; 21 import javax.net.ssl.SSLHandshakeException; 22 23 /** 24 * A blacklist of failed routes to avoid when creating a new connection to a 25 * target address. This is used so that OkHttp can learn from its mistakes: if 26 * there was a failure attempting to connect to a specific IP address, proxy 27 * server or TLS mode, that failure is remembered and alternate routes are 28 * preferred. 29 */ 30 public final class RouteDatabase { 31 private final Set<Route> failedRoutes = new LinkedHashSet<Route>(); 32 33 /** Records a failure connecting to {@code failedRoute}. */ 34 public synchronized void failed(Route failedRoute, IOException failure) { 35 failedRoutes.add(failedRoute); 36 37 if (!(failure instanceof SSLHandshakeException)) { 38 // If the problem was not related to SSL then it will also fail with 39 // a different TLS mode therefore we can be proactive about it. 40 failedRoutes.add(failedRoute.flipTlsMode()); 41 } 42 } 43 44 /** Records success connecting to {@code failedRoute}. */ 45 public synchronized void connected(Route route) { 46 failedRoutes.remove(route); 47 } 48 49 /** Returns true if {@code route} has failed recently and should be avoided. */ 50 public synchronized boolean shouldPostpone(Route route) { 51 return failedRoutes.contains(route); 52 } 53 54 public synchronized int failedRoutesCount() { 55 return failedRoutes.size(); 56 } 57 } 58