下面列出了java.net.HttpURLConnection#HTTP_NOT_IMPLEMENTED 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Creates a new catalog.
*
* @param createCatalogDto catalog
*/
@RequestMapping(
method = RequestMethod.POST,
path = "/catalog",
consumes = MediaType.APPLICATION_JSON_VALUE
)
@ResponseStatus(HttpStatus.CREATED)
@ApiOperation(
position = 3,
value = "Creates a new catalog",
notes = "Returns success if there were no errors creating the catalog"
)
@ApiResponses(
{
@ApiResponse(
code = HttpURLConnection.HTTP_NOT_IMPLEMENTED,
message = "Not yet implemented"
)
}
)
public void createCatalog(@Valid @RequestBody final CreateCatalogDto createCatalogDto) {
throw new MetacatNotSupportedException("Create catalog is not supported.");
}
/**
* Determines whether the operation should be retried and specifies the interval until the next retry.
*
* @param retryContext
* A {@link RetryContext} object that indicates the number of retries, last request's results, whether
* the next retry should happen in the primary or secondary location, and specifies the location mode.
* @param operationContext
* An {@link OperationContext} object for tracking the current operation.
* @return
* A {@link RetryInfo} object that indicates whether the next retry will happen in the primary or secondary
* location, and specifies the location mode. If <code>null</code>, the operation will not be retried.
*/
@Override
public RetryInfo evaluate(RetryContext retryContext, OperationContext operationContext) {
boolean secondaryNotFound = this.evaluateLastAttemptAndSecondaryNotFound(retryContext);
if (retryContext.getCurrentRetryCount() < this.maximumAttempts) {
// If this method is called after a successful response, it means
// we failed during the response body download. So, we should not
// check for success codes here.
int statusCode = retryContext.getLastRequestResult().getStatusCode();
if ((!secondaryNotFound && statusCode >= 300 && statusCode < 500 && statusCode != 408)
|| statusCode == HttpURLConnection.HTTP_NOT_IMPLEMENTED
|| statusCode == HttpURLConnection.HTTP_VERSION) {
return null;
}
final long retryInterval = Math.max(
Math.min(this.deltaBackoffIntervalInMs, RetryPolicy.DEFAULT_MAX_BACKOFF),
RetryPolicy.DEFAULT_MIN_BACKOFF);
return this.evaluateRetryInfo(retryContext, secondaryNotFound, retryInterval);
}
return null;
}
/**
* Determines whether the operation should be retried and specifies the interval until the next retry.
*
* @param retryContext
* A {@link RetryContext} object that indicates the number of retries, last request's results, whether
* the next retry should happen in the primary or secondary location, and specifies the location mode.
* @param operationContext
* An {@link OperationContext} object for tracking the current operation.
* @return
* A {@link RetryInfo} object that indicates whether the next retry will happen in the primary or secondary
* location, and specifies the location mode. If <code>null</code>, the operation will not be retried.
*/
@Override
public RetryInfo evaluate(RetryContext retryContext, OperationContext operationContext) {
boolean secondaryNotFound = this.evaluateLastAttemptAndSecondaryNotFound(retryContext);
if (retryContext.getCurrentRetryCount() < this.maximumAttempts) {
// If this method is called after a successful response, it means
// we failed during the response body download. So, we should not
// check for success codes here.
int statusCode = retryContext.getLastRequestResult().getStatusCode();
if ((!secondaryNotFound && statusCode >= 300 && statusCode < 500 && statusCode != 408)
|| statusCode == HttpURLConnection.HTTP_NOT_IMPLEMENTED
|| statusCode == HttpURLConnection.HTTP_VERSION) {
return null;
}
// Calculate backoff Interval between 80% and 120% of the desired
// backoff, multiply by 2^n -1 for exponential
double incrementDelta = (Math.pow(2, retryContext.getCurrentRetryCount()) - 1);
final int boundedRandDelta = (int) (this.deltaBackoffIntervalInMs * 0.8)
+ this.randRef.nextInt((int) (this.deltaBackoffIntervalInMs * 1.2)
- (int) (this.deltaBackoffIntervalInMs * 0.8));
incrementDelta *= boundedRandDelta;
final long retryInterval = (int) Math.round(Math.min(this.resolvedMinBackoff + incrementDelta,
this.resolvedMaxBackoff));
return this.evaluateRetryInfo(retryContext, secondaryNotFound, retryInterval);
}
return null;
}
private boolean ping() throws IOException {
RequestConfig requestConfig =
RequestConfig.custom()
.setSocketTimeout(HTTP_PING_TIMEOUT)
.setConnectTimeout(HTTP_PING_TIMEOUT)
.setConnectionRequestTimeout(HTTP_PING_TIMEOUT)
.setRedirectsEnabled(false)
.build();
CloseableHttpClient httpClient;
if (allowAllHosts) {
SSLContextBuilder builder = new SSLContextBuilder();
try {
builder.loadTrustMaterial(new TrustAllStrategy());
SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(builder.build(), NoopHostnameVerifier.INSTANCE);
httpClient = HttpClientBuilder.create()
.setDefaultRequestConfig(requestConfig)
.setRetryHandler(new DefaultHttpRequestRetryHandler(HTTP_CLIENT_RETRIES, false))
.setSSLSocketFactory(socketFactory)
.setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
.build();
} catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) {
throw new IOException("Unable to set self signed strategy on http wait: " + e, e);
}
} else {
httpClient = HttpClientBuilder.create()
.setDefaultRequestConfig(requestConfig)
.setRetryHandler(new DefaultHttpRequestRetryHandler(HTTP_CLIENT_RETRIES, false))
.build();
}
try (CloseableHttpResponse response = httpClient.execute(RequestBuilder.create(method.toUpperCase()).setUri(url).build())) {
int responseCode = response.getStatusLine().getStatusCode();
if (responseCode == HttpURLConnection.HTTP_NOT_IMPLEMENTED) {
throw new IllegalArgumentException("Invalid or not supported HTTP method '" + method.toUpperCase() + "' for checking " + url);
}
return responseCode >= statusMin && responseCode <= statusMax;
} finally {
httpClient.close();
}
}
/**
* List of errors which this method should handle:
* <p/>
* 400 Bad Request
* 401 Unauthorized (user password has changed)
* 403 Forbidden (access denied)
* 404 Not found (object was already removed for example)
* 405 Method not allowed (wrong HTTP request method)
* 408 Request Time Out (too slow internet connection, long processing time, etc)
* 409 Conflict (you are trying to treat some resource as another.
* For example to create interpretation for map through chart URI)
* 500 Internal server error (for example NullPointerException)
* 501 Not implemented (no such method or resource)
* 502 Bad Gateway (can be retried later)
* 503 Service unavailable (can be temporary issue)
* 504 Gateway Timeout (we need to retry request later)
*/
public static void handleApiException(APIException apiException, BaseModel model) throws APIException {
switch (apiException.getKind()) {
case HTTP: {
switch (apiException.getResponse().getStatus()) {
case HttpURLConnection.HTTP_BAD_REQUEST: {
// TODO Implement mechanism for handling HTTP errors (allow user to resolve it).
break;
}
case HttpURLConnection.HTTP_UNAUTHORIZED: {
// if the user password has changed, none of other network
// requests won't pass. So we need to stop synchronization.
throw apiException;
}
case HttpURLConnection.HTTP_FORBIDDEN: {
// TODO Implement mechanism for handling HTTP errors (allow user to resolve it).
// User does not has access to given resource anymore.
// We need to handle this in a special way
break;
}
case HttpURLConnection.HTTP_NOT_FOUND: {
// The given resource does not exist on the server anymore.
// Remove it locally.
if (model != null) {
model.delete();
}
break;
}
case HttpURLConnection.HTTP_CONFLICT: {
// TODO Implement mechanism for handling HTTP errors (allow user to resolve it).
// Trying to access wrong resource.
break;
}
case HttpURLConnection.HTTP_INTERNAL_ERROR: {
// TODO Implement mechanism for handling HTTP errors (allow user to resolve it).
break;
}
case HttpURLConnection.HTTP_NOT_IMPLEMENTED: {
// TODO Implement mechanism for handling HTTP errors (allow user to resolve it).
break;
}
}
break;
}
case NETWORK: {
// Retry later.
break;
}
case CONVERSION:
case UNEXPECTED: {
// TODO Implement mechanism for handling HTTP errors (allow user to resolve it).
// implement possibility to show error status. In most cases, this types of errors
// won't be resolved automatically.
// for now, just rethrow exception.
throw apiException;
}
}
}
private boolean ping() throws IOException {
RequestConfig requestConfig =
RequestConfig.custom()
.setSocketTimeout(HTTP_PING_TIMEOUT)
.setConnectTimeout(HTTP_PING_TIMEOUT)
.setConnectionRequestTimeout(HTTP_PING_TIMEOUT)
.setRedirectsEnabled(false)
.build();
CloseableHttpClient httpClient;
if (allowAllHosts) {
SSLContextBuilder builder = new SSLContextBuilder();
try {
builder.loadTrustMaterial(new TrustAllStrategy());
SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(builder.build(), NoopHostnameVerifier.INSTANCE);
httpClient = HttpClientBuilder.create()
.setDefaultRequestConfig(requestConfig)
.setRetryHandler(new DefaultHttpRequestRetryHandler(HTTP_CLIENT_RETRIES, false))
.setSSLSocketFactory(socketFactory)
.setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
.build();
} catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) {
throw new IOException("Unable to set self signed strategy on http wait: " + e, e);
}
} else {
httpClient = HttpClientBuilder.create()
.setDefaultRequestConfig(requestConfig)
.setRetryHandler(new DefaultHttpRequestRetryHandler(HTTP_CLIENT_RETRIES, false))
.build();
}
try (CloseableHttpResponse response = httpClient.execute(RequestBuilder.create(method.toUpperCase()).setUri(url).build())) {
int responseCode = response.getStatusLine().getStatusCode();
if (responseCode == HttpURLConnection.HTTP_NOT_IMPLEMENTED) {
throw new IllegalArgumentException("Invalid or not supported HTTP method '" + method.toUpperCase() + "' for checking " + url);
}
return responseCode >= statusMin && responseCode <= statusMax;
} finally {
httpClient.close();
}
}
/**
* Translates the specified HTTP status code into a storage exception.
*
* @param statusCode
* The HTTP status code returned by the operation.
* @param statusDescription
* A <code>String</code> that represents the status description.
* @param inner
* An <code>Exception</code> object that represents a reference to the initial exception, if one exists.
*
* @return A <code>StorageException</code> object that represents translated exception.
**/
protected static StorageException translateFromHttpStatus(final int statusCode, final String statusDescription,
final Exception inner) {
String errorCode;
switch (statusCode) {
case HttpURLConnection.HTTP_FORBIDDEN:
errorCode = StorageErrorCode.ACCESS_DENIED.toString();
break;
case HttpURLConnection.HTTP_GONE:
case HttpURLConnection.HTTP_NOT_FOUND:
errorCode = StorageErrorCode.RESOURCE_NOT_FOUND.toString();
break;
case 416:
case HttpURLConnection.HTTP_BAD_REQUEST:
// 416: RequestedRangeNotSatisfiable - No corresponding enum in HttpURLConnection
errorCode = StorageErrorCode.BAD_REQUEST.toString();
break;
case HttpURLConnection.HTTP_PRECON_FAILED:
case HttpURLConnection.HTTP_NOT_MODIFIED:
errorCode = StorageErrorCode.CONDITION_FAILED.toString();
break;
case HttpURLConnection.HTTP_CONFLICT:
errorCode = StorageErrorCode.RESOURCE_ALREADY_EXISTS.toString();
break;
case HttpURLConnection.HTTP_UNAVAILABLE:
errorCode = StorageErrorCode.SERVER_BUSY.toString();
break;
case HttpURLConnection.HTTP_GATEWAY_TIMEOUT:
errorCode = StorageErrorCode.SERVICE_TIMEOUT.toString();
break;
case HttpURLConnection.HTTP_INTERNAL_ERROR:
errorCode = StorageErrorCode.SERVICE_INTERNAL_ERROR.toString();
break;
case HttpURLConnection.HTTP_NOT_IMPLEMENTED:
errorCode = StorageErrorCode.NOT_IMPLEMENTED.toString();
break;
case HttpURLConnection.HTTP_BAD_GATEWAY:
errorCode = StorageErrorCode.BAD_GATEWAY.toString();
break;
case HttpURLConnection.HTTP_VERSION:
errorCode = StorageErrorCode.HTTP_VERSION_NOT_SUPPORTED.toString();
break;
default:
errorCode = null;
}
if (errorCode == null) {
return null;
} else {
return new StorageException(errorCode, statusDescription, statusCode, null, inner);
}
}
/**
* Map from HTTP status code to reason description.
* Sentry HTTP breadcrumbs expect a text description of the HTTP status-code.
* This function implements a look-up table with a default value for unknown status-codes.
* @param statusCode an integer HTTP status code, expected to be in the range [200,505].
* @return a non-empty string in all cases.
*/
private static String httpReason(int statusCode) {
switch (statusCode) {
// 2xx
case HttpURLConnection.HTTP_OK: return "OK";
case HttpURLConnection.HTTP_CREATED: return "Created";
case HttpURLConnection.HTTP_ACCEPTED: return "Accepted";
case HttpURLConnection.HTTP_NOT_AUTHORITATIVE: return "Non-Authoritative Information";
case HttpURLConnection.HTTP_NO_CONTENT: return "No Content";
case HttpURLConnection.HTTP_RESET: return "Reset Content";
case HttpURLConnection.HTTP_PARTIAL: return "Partial Content";
// 3xx
case HttpURLConnection.HTTP_MULT_CHOICE: return "Multiple Choices";
case HttpURLConnection.HTTP_MOVED_PERM: return "Moved Permanently";
case HttpURLConnection.HTTP_MOVED_TEMP: return "Temporary Redirect";
case HttpURLConnection.HTTP_SEE_OTHER: return "See Other";
case HttpURLConnection.HTTP_NOT_MODIFIED: return "Not Modified";
case HttpURLConnection.HTTP_USE_PROXY: return "Use Proxy";
// 4xx
case HttpURLConnection.HTTP_BAD_REQUEST: return "Bad Request";
case HttpURLConnection.HTTP_UNAUTHORIZED: return "Unauthorized";
case HttpURLConnection.HTTP_PAYMENT_REQUIRED: return "Payment Required";
case HttpURLConnection.HTTP_FORBIDDEN: return "Forbidden";
case HttpURLConnection.HTTP_NOT_FOUND: return "Not Found";
case HttpURLConnection.HTTP_BAD_METHOD: return "Method Not Allowed";
case HttpURLConnection.HTTP_NOT_ACCEPTABLE: return "Not Acceptable";
case HttpURLConnection.HTTP_PROXY_AUTH: return "Proxy Authentication Required";
case HttpURLConnection.HTTP_CLIENT_TIMEOUT: return "Request Time-Out";
case HttpURLConnection.HTTP_CONFLICT: return "Conflict";
case HttpURLConnection.HTTP_GONE: return "Gone";
case HttpURLConnection.HTTP_LENGTH_REQUIRED: return "Length Required";
case HttpURLConnection.HTTP_PRECON_FAILED: return "Precondition Failed";
case HttpURLConnection.HTTP_ENTITY_TOO_LARGE: return "Request Entity Too Large";
case HttpURLConnection.HTTP_REQ_TOO_LONG: return "Request-URI Too Large";
case HttpURLConnection.HTTP_UNSUPPORTED_TYPE: return "Unsupported Media Type";
// 5xx
case HttpURLConnection.HTTP_INTERNAL_ERROR: return "Internal Server Error";
case HttpURLConnection.HTTP_NOT_IMPLEMENTED: return "Not Implemented";
case HttpURLConnection.HTTP_BAD_GATEWAY: return "Bad Gateway";
case HttpURLConnection.HTTP_UNAVAILABLE: return "Service Unavailable";
case HttpURLConnection.HTTP_GATEWAY_TIMEOUT: return "Gateway Timeout";
case HttpURLConnection.HTTP_VERSION: return "Version Not Supported";
default: return "unknown";
}
}