下面列出了java.net.HttpRetryException#java.net.NoRouteToHostException 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public static URL handleRedirectRequest(LocalProxyConfig config, URL url, HashMap<String, String> headers) throws IOException {
int redirectCount = 0;
while (redirectCount++ < MAX_REDIRECT) {
HttpURLConnection connection = makeConnection(config, url, headers);
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_MULT_CHOICE
|| responseCode == HttpURLConnection.HTTP_MOVED_PERM
|| responseCode == HttpURLConnection.HTTP_MOVED_TEMP
|| responseCode == HttpURLConnection.HTTP_SEE_OTHER
&& (responseCode == 307 /* HTTP_TEMP_REDIRECT */
|| responseCode == 308 /* HTTP_PERM_REDIRECT */)) {
String location = connection.getHeaderField("Location");
connection.disconnect();
url = handleRedirect(url, location);
return handleRedirectRequest(config, url, headers);
} else {
return url;
}
}
throw new NoRouteToHostException("Too many redirects: " + redirectCount);
}
static void throwConnectException(String method, NativeConnectException refusedCause, int err)
throws IOException {
if (err == refusedCause.expectedErr()) {
throw refusedCause;
}
if (err == ERROR_EALREADY_NEGATIVE) {
throw new ConnectionPendingException();
}
if (err == ERROR_ENETUNREACH_NEGATIVE) {
throw new NoRouteToHostException();
}
if (err == ERROR_EISCONN_NEGATIVE) {
throw new AlreadyConnectedException();
}
if (err == ERRNO_ENOENT_NEGATIVE) {
throw new FileNotFoundException();
}
throw new ConnectException(method + "(..) failed: " + ERRORS[-err]);
}
private static boolean isWebExceptionRetriableInternal(Exception ex) {
if (ex instanceof PoolExhaustedException) {
return true;
}
IOException webEx = Utils.as(ex, IOException.class);
if (webEx == null) {
return false;
}
// any network failure for which we are certain the request hasn't reached the service endpoint.
if (webEx instanceof ConnectException ||
webEx instanceof UnknownHostException ||
webEx instanceof SSLHandshakeException ||
webEx instanceof NoRouteToHostException ||
webEx instanceof SSLPeerUnverifiedException) {
return true;
}
return false;
}
private static String getNotFoundError(CoreException ce) {
IStatus status = ce.getStatus();
Throwable t = status.getException();
if(t instanceof UnknownHostException ||
// XXX maybe a different msg ?
t instanceof SocketTimeoutException ||
t instanceof NoRouteToHostException ||
t instanceof ConnectException)
{
Bugzilla.LOG.log(Level.FINER, null, t);
return NbBundle.getMessage(BugzillaExecutor.class, "MSG_HOST_NOT_FOUND"); // NOI18N
}
String msg = getMessage(ce);
if(msg != null) {
msg = msg.trim().toLowerCase();
if(HTTP_ERROR_NOT_FOUND.equals(msg)) {
Bugzilla.LOG.log(Level.FINER, "returned error message [{0}]", msg); // NOI18N
return NbBundle.getMessage(BugzillaExecutor.class, "MSG_HOST_NOT_FOUND"); // NOI18N
}
}
return null;
}
/**
* Take an IOException and a URI, wrap it where possible with
* something that includes the URI
*
* @param dest target URI
* @param operation operation
* @param exception the caught exception.
* @return an exception to throw
*/
public static IOException wrapException(final String dest,
final String operation,
final IOException exception) {
String action = operation + " " + dest;
String xref = null;
if (exception instanceof ConnectException) {
xref = "ConnectionRefused";
} else if (exception instanceof UnknownHostException) {
xref = "UnknownHost";
} else if (exception instanceof SocketTimeoutException) {
xref = "SocketTimeout";
} else if (exception instanceof NoRouteToHostException) {
xref = "NoRouteToHost";
}
String msg = action
+ " failed on exception: "
+ exception;
if (xref != null) {
msg = msg + ";" + see(xref);
}
return wrapWithMessage(exception, msg);
}
@Test
public void testException() throws Throwable {
Exception e =
new NoRouteToHostException("that box caught fire 3 years ago");
ThrowableInformation ti = new ThrowableInformation(e);
Log4Json l4j = new Log4Json();
long timeStamp = Time.now();
String outcome = l4j.toJson(new StringWriter(),
"testException",
timeStamp,
"INFO",
"quoted\"",
"new line\n and {}",
ti)
.toString();
println("testException", outcome);
}
/**
* Take an IOException and a URI, wrap it where possible with
* something that includes the URI
*
* @param dest target URI
* @param operation operation
* @param exception the caught exception.
* @return an exception to throw
*/
public static IOException wrapException(final String dest,
final String operation,
final IOException exception) {
String action = operation + " " + dest;
String xref = null;
if (exception instanceof ConnectException) {
xref = "ConnectionRefused";
} else if (exception instanceof UnknownHostException) {
xref = "UnknownHost";
} else if (exception instanceof SocketTimeoutException) {
xref = "SocketTimeout";
} else if (exception instanceof NoRouteToHostException) {
xref = "NoRouteToHost";
}
String msg = action
+ " failed on exception: "
+ exception;
if (xref != null) {
msg = msg + ";" + see(xref);
}
return wrapWithMessage(exception, msg);
}
@Test
public void testException() throws Throwable {
Exception e =
new NoRouteToHostException("that box caught fire 3 years ago");
ThrowableInformation ti = new ThrowableInformation(e);
Log4Json l4j = new Log4Json();
long timeStamp = Time.now();
String outcome = l4j.toJson(new StringWriter(),
"testException",
timeStamp,
"INFO",
"quoted\"",
"new line\n and {}",
ti)
.toString();
println("testException", outcome);
}
public static void manageIOException(Exception e, Message message, Command command, Language lg, DiscordException notFound){
// First we try parsing the exception message to see if it contains the response code
Matcher exMsgStatusCodeMatcher = Pattern.compile("^Server returned HTTP response code: (\\d+)")
.matcher(e.getMessage());
if(exMsgStatusCodeMatcher.find()) {
int statusCode = Integer.parseInt(exMsgStatusCodeMatcher.group(1));
if (statusCode >= 500 && statusCode < 600) {
LOG.warn("manageIOException", e);
gameWebsite503.throwException(message, command, lg);
}
else {
LOG.error("manageIOException", e);
BasicDiscordException.UNKNOWN_ERROR.throwException(message, command, lg);
}
} else if (e instanceof UnknownHostException || e instanceof SocketTimeoutException) {
gameWebsite503.throwException(message, command, lg);
} else if (e instanceof FileNotFoundException
|| e instanceof HttpStatusException
|| e instanceof NoRouteToHostException){
notFound.throwException(message, command, lg);
}
else {
LOG.error("manageIOException", e);
BasicDiscordException.UNKNOWN_ERROR.throwException(message, command, lg);
}
}
public static void manageSilentlyIOException(Exception e){
Reporter.report(e);
// First we try parsing the exception message to see if it contains the response code
Matcher exMsgStatusCodeMatcher = Pattern.compile("^Server returned HTTP response code: (\\d+)")
.matcher(e.getMessage());
if(exMsgStatusCodeMatcher.find()) {
int statusCode = Integer.parseInt(exMsgStatusCodeMatcher.group(1));
if (statusCode >= 500 && statusCode < 600)
LOG.warn("manageSilentlyIOException", e);
else
LOG.error("manageSilentlyIOException", e);
} else if (e instanceof UnknownHostException
|| e instanceof SocketTimeoutException
|| e instanceof FileNotFoundException
|| e instanceof HttpStatusException
|| e instanceof NoRouteToHostException)
LOG.warn("manageSilentlyIOException", e);
else
LOG.error("manageSilentlyIOException", e);
}
private void handleException(IOException ioe){
//If we couldn't read the request, return;
if(msg == null) return;
//If have been aborted by other thread
if(mode == ABORT_MODE) return;
//If the request was successfully completed, but exception happened later
if(mode == PIPE_MODE) return;
int error_code = Proxy.SOCKS_FAILURE;
if(ioe instanceof SocksException)
error_code = ((SocksException)ioe).errCode;
else if(ioe instanceof NoRouteToHostException)
error_code = Proxy.SOCKS_HOST_UNREACHABLE;
else if(ioe instanceof ConnectException)
error_code = Proxy.SOCKS_CONNECTION_REFUSED;
else if(ioe instanceof InterruptedIOException)
error_code = Proxy.SOCKS_TTL_EXPIRE;
if(error_code > Proxy.SOCKS_ADDR_NOT_SUPPORTED || error_code < 0){
error_code = Proxy.SOCKS_FAILURE;
}
sendErrorMessage(error_code);
}
@Override
public boolean retryMethod(final HttpMethod method, final IOException exception, int executionCount) {
if (method == null) {
throw new IllegalArgumentException("HTTP method may not be null");
}
if (exception == null) {
throw new IllegalArgumentException("Exception parameter may not be null");
}
if (executionCount > super.getRetryCount()) {
// Do not retry if over max retry count
return false;
}
//Override the behavior of DefaultHttpMethodRetryHandler to retry in case of UnknownHostException
// and NoRouteToHostException.
if (exception instanceof UnknownHostException || exception instanceof NoRouteToHostException) {
return true;
}
return super.retryMethod(method, exception, executionCount);
}
/**
* @throws NoRouteToHostException if the process is terminated.
* @throws UnknownServiceException if the process has no known monitor address.
*/
@Nonnull
public QApiConnection getConnection() throws IOException {
if (monitor == null)
throw new UnknownServiceException("No monitor address known.");
try {
// If this succeeds, then we have exited.
int exitValue = process.exitValue();
connection = null;
throw new NoRouteToHostException("Process terminated with exit code " + exitValue);
} catch (IllegalThreadStateException e) {
}
synchronized (lock) {
if (connection != null)
return connection;
connection = new QApiConnection(monitor);
return connection;
}
}
/**
* This method handles a connection error that was caused while connecting the gateway to the backend.
*
* @param error the connection error to be handled
* @return a new ConnectorException
*/
public static ConnectorException handleConnectionError(Throwable error) {
ConnectorException ce = null;
if (error instanceof UnknownHostException || error instanceof ConnectException || error instanceof NoRouteToHostException) {
ce = new ConnectorException("Unable to connect to backend", error); //$NON-NLS-1$
ce.setStatusCode(502); // BAD GATEWAY
} else if (error instanceof InterruptedIOException || error instanceof java.util.concurrent.TimeoutException) {
ce = new ConnectorException("Connection to backend terminated" + error.getMessage(), error); //$NON-NLS-1$
ce.setStatusCode(504); // GATEWAY TIMEOUT
}
if (ce != null) {
return ce;
} else {
return new ConnectorException(error.getMessage(), error);
}
}
@Override
public boolean canInfinitelyRetry(Throwable t){
t=Throwables.getRootCause(t);
t=processPipelineException(t);
if(t instanceof NotServingPartitionException
|| t instanceof NoServerForRegionException
|| t instanceof WrongPartitionException
|| t instanceof PipelineTooBusy
|| t instanceof RegionBusyException
|| t instanceof NoRouteToHostException
|| t instanceof org.apache.hadoop.hbase.ipc.FailedServerException
|| t instanceof FailedServerException
|| t instanceof ServerNotRunningYetException
|| t instanceof ConnectTimeoutException
|| t instanceof IndexNotSetUpException) return true;
return false;
}
public RemoteSdkException(String s, Throwable throwable) {
super(s, throwable);
myAuthFailed = false;
Throwable t = throwable;
while (t != null) {
if (t instanceof NoRouteToHostException) {
myCause = t;
myNoRouteToHost = true;
return;
}
t = t.getCause();
}
myNoRouteToHost = false;
myCause = throwable;
}
/**
* Take an IOException and a URI, wrap it where possible with
* something that includes the URI
*
* @param dest target URI
* @param operation operation
* @param exception the caught exception.
* @return an exception to throw
*/
public static IOException wrapException(final String dest,
final String operation,
final IOException exception) {
String action = operation + " " + dest;
String xref = null;
if (exception instanceof ConnectException) {
xref = "ConnectionRefused";
} else if (exception instanceof UnknownHostException) {
xref = "UnknownHost";
} else if (exception instanceof SocketTimeoutException) {
xref = "SocketTimeout";
} else if (exception instanceof NoRouteToHostException) {
xref = "NoRouteToHost";
}
String msg = action
+ " failed on exception: "
+ exception;
if (xref != null) {
msg = msg + ";" + see(xref);
}
return wrapWithMessage(exception, msg);
}
protected boolean memberAlive(Member mbr, byte[] msgData,
boolean sendTest, boolean readTest,
long readTimeout, long conTimeout,
int optionFlag) {
//could be a shutdown notification
if ( Arrays.equals(mbr.getCommand(),Member.SHUTDOWN_PAYLOAD) ) return false;
try (Socket socket = new Socket()) {
InetAddress ia = InetAddress.getByAddress(mbr.getHost());
InetSocketAddress addr = new InetSocketAddress(ia, mbr.getPort());
socket.setSoTimeout((int)readTimeout);
socket.connect(addr, (int) conTimeout);
if ( sendTest ) {
ChannelData data = new ChannelData(true);
data.setAddress(getLocalMember(false));
data.setMessage(new XByteBuffer(msgData,false));
data.setTimestamp(System.currentTimeMillis());
int options = optionFlag | Channel.SEND_OPTIONS_BYTE_MESSAGE;
if ( readTest ) options = (options | Channel.SEND_OPTIONS_USE_ACK);
else options = (options & (~Channel.SEND_OPTIONS_USE_ACK));
data.setOptions(options);
byte[] message = XByteBuffer.createDataPackage(data);
socket.getOutputStream().write(message);
if ( readTest ) {
int length = socket.getInputStream().read(message);
return length > 0;
}
}//end if
return true;
} catch (SocketTimeoutException | ConnectException | NoRouteToHostException noop) {
//do nothing, we couldn't connect
} catch (Exception x) {
log.error(sm.getString("tcpFailureDetector.failureDetection.failed", mbr),x);
}
return false;
}
/**
* Appends the remote address to the message of the exceptions caused by connection attempt failure.将远程地址附加到连接尝试失败所引起的异常的消息。
*/
protected final Throwable annotateConnectException(Throwable cause, SocketAddress remoteAddress) {
if (cause instanceof ConnectException) {
return new AnnotatedConnectException((ConnectException) cause, remoteAddress);
}
if (cause instanceof NoRouteToHostException) {
return new AnnotatedNoRouteToHostException((NoRouteToHostException) cause, remoteAddress);
}
if (cause instanceof SocketException) {
return new AnnotatedSocketException((SocketException) cause, remoteAddress);
}
return cause;
}
/**
* 检查目标节点是否已经不存活了
*
* @param throwable 异常
* @return 是否是死亡节点
*/
public static boolean detectDead(Throwable throwable) {
if (throwable == null) {
return false;
}
Queue<Throwable> queue = new LinkedList<>();
queue.add(throwable);
Throwable t;
while (!queue.isEmpty()) {
t = queue.poll();
t = t instanceof ConnectionException ? t.getCause() : t;
if (t instanceof NoRouteToHostException) {
//没有路由
return true;
} else if (t instanceof ConnectException) {
//连接异常
String msg = t.getMessage().toLowerCase();
for (String deadMsg : DEAD_MSG) {
if (msg.contains(deadMsg)) {
return true;
}
}
return false;
} else if (t.getCause() != null) {
queue.add(t.getCause());
}
}
return false;
}
protected void establishConnection(SelectionKey currentKey)
throws IOException
{
// first, remove OP_Connect interest (fixes an immediate return of selector.select()
// with no ready keys bug)
currentKey.interestOps(0); // when controller wants to send a message, this will be changed to
// OP_WRITE automatically
@SuppressWarnings("resource")
SocketChannel channel = (SocketChannel) currentKey.channel();
Peer peer = (Peer) currentKey.attachment();
try
{
channel.finishConnect();
peer.connectionEstablished();
connObserver.outboundConnectionEstablished(peer);
}
catch (ConnectException conExc)
{
String message = conExc.getMessage();
errorReporter.logTrace(
"Outbound connection to " + peer +
" failed" +
(message != null ? ": " + message : "")
);
}
catch (NoRouteToHostException noRouteExc)
{
// ignore, Reconnector will retry later
}
}
@Override
public boolean isExpired() throws NoRouteToHostException, UnknownHostException {
// experimental: try to reset session timeout
if ("Exchange2007".equals(serverVersion)) {
HttpGet getMethod = new HttpGet("/owa/");
try (CloseableHttpResponse response = httpClientAdapter.execute(getMethod)) {
LOGGER.debug(response.getStatusLine().getStatusCode() + " at /owa/");
} catch (IOException e) {
LOGGER.warn(e.getMessage());
}
}
return super.isExpired();
}
@DataProvider(name = "exceptionToIsRetriable")
public Object[][] exceptionToIsRetriable() {
return new Object[][]{
// exception, is retriable
{
new RuntimeException(), false
},
{
new ConnectException(), true
},
{
new ConnectTimeoutException(), true
},
{
new UnknownHostException(), true
},
{
ReadTimeoutException.INSTANCE, false
},
{
new SSLHandshakeException("dummy"), true
},
{
new NoRouteToHostException(), true,
},
{
new SSLPeerUnverifiedException("dummy"), true
},
{
new SocketTimeoutException(), false
},
{
new PoolExhaustedException(), true
}
};
}
@DataProvider(name = "networkFailure")
public Object[][] networkFailure() {
return new Object[][]{
// exception, is retriable
{
new RuntimeException(), false
},
{
new ConnectException(), true
},
{
new ConnectTimeoutException(), true
},
{
new UnknownHostException(), true
},
{
ReadTimeoutException.INSTANCE, true
},
{
new SSLHandshakeException("dummy"), true
},
{
new NoRouteToHostException(), true,
},
{
new SSLPeerUnverifiedException("dummy"), true
},
{
new SocketTimeoutException(), true
},
{
new ChannelException(), true
}
};
}
private void handleException(final IOException ioe) {
// If we couldn't read the request, return;
if (msg == null) {
return;
}
// If have been aborted by other thread
if (mode == ABORT_MODE) {
return;
}
// If the request was successfully completed, but exception happened
// later
if (mode == PIPE_MODE) {
return;
}
int error_code = SocksProxyBase.SOCKS_FAILURE;
if (ioe instanceof SocksException) {
error_code = ((SocksException) ioe).errCode;
} else if (ioe instanceof NoRouteToHostException) {
error_code = SocksProxyBase.SOCKS_HOST_UNREACHABLE;
} else if (ioe instanceof ConnectException) {
error_code = SocksProxyBase.SOCKS_CONNECTION_REFUSED;
} else if (ioe instanceof InterruptedIOException) {
error_code = SocksProxyBase.SOCKS_TTL_EXPIRE;
}
if ((error_code > SocksProxyBase.SOCKS_ADDR_NOT_SUPPORTED)
|| (error_code < 0)) {
error_code = SocksProxyBase.SOCKS_FAILURE;
}
sendErrorMessage(error_code);
}
protected static RetryPolicy createRetryPolicy(Configuration conf,
String maxWaitTimeStr, long defMaxWaitTime,
String connectRetryIntervalStr, long defRetryInterval) {
long maxWaitTime = conf.getLong(maxWaitTimeStr, defMaxWaitTime);
long retryIntervalMS =
conf.getLong(connectRetryIntervalStr, defRetryInterval);
if (maxWaitTime == -1) {
// wait forever.
return RetryPolicies.RETRY_FOREVER;
}
Preconditions.checkArgument(maxWaitTime > 0, "Invalid Configuration. "
+ maxWaitTimeStr + " should be a positive value.");
Preconditions.checkArgument(retryIntervalMS > 0, "Invalid Configuration. "
+ connectRetryIntervalStr + "should be a positive value.");
RetryPolicy retryPolicy =
RetryPolicies.retryUpToMaximumTimeWithFixedSleep(maxWaitTime,
retryIntervalMS, TimeUnit.MILLISECONDS);
Map<Class<? extends Exception>, RetryPolicy> exceptionToPolicyMap =
new HashMap<Class<? extends Exception>, RetryPolicy>();
exceptionToPolicyMap.put(EOFException.class, retryPolicy);
exceptionToPolicyMap.put(ConnectException.class, retryPolicy);
exceptionToPolicyMap.put(NoRouteToHostException.class, retryPolicy);
exceptionToPolicyMap.put(UnknownHostException.class, retryPolicy);
exceptionToPolicyMap.put(RetriableException.class, retryPolicy);
exceptionToPolicyMap.put(SocketException.class, retryPolicy);
exceptionToPolicyMap.put(NMNotYetReadyException.class, retryPolicy);
return RetryPolicies.retryByException(RetryPolicies.TRY_ONCE_THEN_FAIL,
exceptionToPolicyMap);
}
@Override
public RetryAction shouldRetry(Exception e, int retries,
int failovers, boolean isIdempotentOrAtMostOnce) throws Exception {
if (failovers >= maxFailovers) {
return new RetryAction(RetryAction.RetryDecision.FAIL, 0,
"failovers (" + failovers + ") exceeded maximum allowed ("
+ maxFailovers + ")");
}
if (retries - failovers > maxRetries) {
return new RetryAction(RetryAction.RetryDecision.FAIL, 0, "retries ("
+ retries + ") exceeded maximum allowed (" + maxRetries + ")");
}
if (e instanceof ConnectException ||
e instanceof NoRouteToHostException ||
e instanceof UnknownHostException ||
e instanceof StandbyException ||
e instanceof ConnectTimeoutException ||
isWrappedStandbyException(e)) {
return new RetryAction(RetryAction.RetryDecision.FAILOVER_AND_RETRY,
getFailoverOrRetrySleepTime(failovers));
} else if (e instanceof RetriableException
|| getWrappedRetriableException(e) != null) {
// RetriableException or RetriableException wrapped
return new RetryAction(RetryAction.RetryDecision.RETRY,
getFailoverOrRetrySleepTime(retries));
} else if (e instanceof SocketException
|| (e instanceof IOException && !(e instanceof RemoteException))) {
if (isIdempotentOrAtMostOnce) {
return RetryAction.FAILOVER_AND_RETRY;
} else {
return new RetryAction(RetryAction.RetryDecision.FAIL, 0,
"the invoked method is not idempotent, and unable to determine "
+ "whether it was invoked");
}
} else {
return fallbackPolicy.shouldRetry(e, retries, failovers,
isIdempotentOrAtMostOnce);
}
}
@Test
public void testNestedException() throws Throwable {
Exception e =
new NoRouteToHostException("that box caught fire 3 years ago");
Exception ioe = new IOException("Datacenter problems", e);
ThrowableInformation ti = new ThrowableInformation(ioe);
Log4Json l4j = new Log4Json();
long timeStamp = Time.now();
String outcome = l4j.toJson(new StringWriter(),
"testNestedException",
timeStamp,
"INFO",
"quoted\"",
"new line\n and {}",
ti)
.toString();
println("testNestedException", outcome);
ContainerNode rootNode = Log4Json.parse(outcome);
assertEntryEquals(rootNode, Log4Json.LEVEL, "INFO");
assertEntryEquals(rootNode, Log4Json.NAME, "testNestedException");
assertEntryEquals(rootNode, Log4Json.TIME, timeStamp);
assertEntryEquals(rootNode, Log4Json.EXCEPTION_CLASS,
ioe.getClass().getName());
JsonNode node = assertNodeContains(rootNode, Log4Json.STACK);
assertTrue("Not an array: " + node, node.isArray());
node = assertNodeContains(rootNode, Log4Json.DATE);
assertTrue("Not a string: " + node, node.isTextual());
//rather than try and make assertions about the format of the text
//message equalling another ISO date, this test asserts that the hypen
//and colon characters are in the string.
String dateText = node.getTextValue();
assertTrue("No '-' in " + dateText, dateText.contains("-"));
assertTrue("No '-' in " + dateText, dateText.contains(":"));
}
protected static RetryPolicy createRetryPolicy(Configuration conf,
String maxWaitTimeStr, long defMaxWaitTime,
String connectRetryIntervalStr, long defRetryInterval) {
long maxWaitTime = conf.getLong(maxWaitTimeStr, defMaxWaitTime);
long retryIntervalMS =
conf.getLong(connectRetryIntervalStr, defRetryInterval);
if (maxWaitTime == -1) {
// wait forever.
return RetryPolicies.RETRY_FOREVER;
}
Preconditions.checkArgument(maxWaitTime > 0, "Invalid Configuration. "
+ maxWaitTimeStr + " should be a positive value.");
Preconditions.checkArgument(retryIntervalMS > 0, "Invalid Configuration. "
+ connectRetryIntervalStr + "should be a positive value.");
RetryPolicy retryPolicy =
RetryPolicies.retryUpToMaximumTimeWithFixedSleep(maxWaitTime,
retryIntervalMS, TimeUnit.MILLISECONDS);
Map<Class<? extends Exception>, RetryPolicy> exceptionToPolicyMap =
new HashMap<Class<? extends Exception>, RetryPolicy>();
exceptionToPolicyMap.put(EOFException.class, retryPolicy);
exceptionToPolicyMap.put(ConnectException.class, retryPolicy);
exceptionToPolicyMap.put(NoRouteToHostException.class, retryPolicy);
exceptionToPolicyMap.put(UnknownHostException.class, retryPolicy);
exceptionToPolicyMap.put(RetriableException.class, retryPolicy);
exceptionToPolicyMap.put(SocketException.class, retryPolicy);
exceptionToPolicyMap.put(NMNotYetReadyException.class, retryPolicy);
return RetryPolicies.retryByException(RetryPolicies.TRY_ONCE_THEN_FAIL,
exceptionToPolicyMap);
}
@Override
public RetryAction shouldRetry(Exception e, int retries,
int failovers, boolean isIdempotentOrAtMostOnce) throws Exception {
if (failovers >= maxFailovers) {
return new RetryAction(RetryAction.RetryDecision.FAIL, 0,
"failovers (" + failovers + ") exceeded maximum allowed ("
+ maxFailovers + ")");
}
if (retries - failovers > maxRetries) {
return new RetryAction(RetryAction.RetryDecision.FAIL, 0, "retries ("
+ retries + ") exceeded maximum allowed (" + maxRetries + ")");
}
if (e instanceof ConnectException ||
e instanceof NoRouteToHostException ||
e instanceof UnknownHostException ||
e instanceof StandbyException ||
e instanceof ConnectTimeoutException ||
isWrappedStandbyException(e)) {
return new RetryAction(RetryAction.RetryDecision.FAILOVER_AND_RETRY,
getFailoverOrRetrySleepTime(failovers));
} else if (e instanceof RetriableException
|| getWrappedRetriableException(e) != null) {
// RetriableException or RetriableException wrapped
return new RetryAction(RetryAction.RetryDecision.RETRY,
getFailoverOrRetrySleepTime(retries));
} else if (e instanceof SocketException
|| (e instanceof IOException && !(e instanceof RemoteException))) {
if (isIdempotentOrAtMostOnce) {
return RetryAction.FAILOVER_AND_RETRY;
} else {
return new RetryAction(RetryAction.RetryDecision.FAIL, 0,
"the invoked method is not idempotent, and unable to determine "
+ "whether it was invoked");
}
} else {
return fallbackPolicy.shouldRetry(e, retries, failovers,
isIdempotentOrAtMostOnce);
}
}