Java tutorial
/* * (c) 2015 CenturyLink. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.centurylink.cloud.sdk.core.client.retry; import org.apache.http.HttpResponse; import org.apache.http.client.ServiceUnavailableRetryStrategy; import org.apache.http.protocol.HttpContext; import java.util.List; import static java.util.Arrays.asList; import static org.jboss.resteasy.util.HttpResponseCodes.SC_ACCEPTED; import static org.jboss.resteasy.util.HttpResponseCodes.SC_CREATED; import static org.jboss.resteasy.util.HttpResponseCodes.SC_NOT_FOUND; import static org.jboss.resteasy.util.HttpResponseCodes.SC_NO_CONTENT; import static org.jboss.resteasy.util.HttpResponseCodes.SC_OK; /** * @author Ilya Drabenia */ public class ClcRetryStrategy implements ServiceUnavailableRetryStrategy { /** * Maximum number of allowed retries if the server responds with a HTTP code * in our retry code list. Default value is 1. */ private final int maxRetries; /** * Retry interval between subsequent requests, in milliseconds. Default * value is 1 second. */ private final long retryInterval; public ClcRetryStrategy(int maxRetries, int retryInterval) { super(); if (maxRetries < 1) { throw new IllegalArgumentException("MaxRetries must be greater than 1"); } if (retryInterval < 1) { throw new IllegalArgumentException("Retry interval must be greater than 1"); } this.maxRetries = maxRetries; this.retryInterval = retryInterval; } public ClcRetryStrategy() { this(1, 1000); } @Override public boolean retryRequest(final HttpResponse response, int executionCount, final HttpContext context) { return executionCount <= maxRetries && isRequestFailed(response); } private boolean isRequestFailed(HttpResponse response) { List<Integer> successResultCodes = asList(SC_OK, SC_CREATED, SC_ACCEPTED, SC_NO_CONTENT, SC_NOT_FOUND); return !successResultCodes.contains(response.getStatusLine().getStatusCode()); } @Override public long getRetryInterval() { return retryInterval; } }