下面列出了org.apache.http.HttpStatus#SC_METHOD_NOT_ALLOWED 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Check whether remote directory exists.
* If HEAD used by {@link #exists(String)} fails, GET is used instead.
*
* See <a href="http://code.google.com/p/sardine/issues/detail?id=48">http://code.google.com/p/sardine/issues/detail?id=48</a>
* and <a href="https://issues.alfresco.com/jira/browse/ALF-7883">https://issues.alfresco.com/jira/browse/ALF-7883</a>
* for more information and motivation.
*
* This method should work both for WebDAV and plain HTTP,
* hence PROPFIND can't be used.
*
* @param url
* Path to the directory.
* @return True if the directory exists.
* @throws IOException
*/
// CL-2709: The bug in Alfresco has already been fixed.
// As for Jackrabbit, http://koule:22401/repository/ returns 404 both for GET and HEAD
@Override
public boolean dirExists(String url) throws IOException {
try {
return exists(url); // first try with HTTP HEAD
} catch (SardineException se) {
// https://issues.alfresco.com/jira/browse/ALF-7883
switch (se.getStatusCode()) {
case HttpStatus.SC_BAD_REQUEST: // HEAD failed
case HttpStatus.SC_METHOD_NOT_ALLOWED: // HEAD not allowed
// try HTTP GET as a fallback
InputStream is = getIfExists(url, Collections.<String, String>emptyMap());
if (is == null) {
return false;
} else {
is.close();
return true;
}
}
throw se;
}
}
private Action getAction(String uri, String method) throws ActionMappingException {
if (!ACTION_MAPPINGS.containsKey(uri)) {
throw new ActionMappingException("Resource with URI " + uri + " is not found.", HttpStatus.SC_NOT_FOUND);
}
Class<? extends Action> controllerClass =
ACTION_MAPPINGS.getOrDefault(uri, new HashMap<>()).get(method);
if (controllerClass == null) {
throw new ActionMappingException("Method [" + method + "] is not allowed for URI " + uri + ".",
HttpStatus.SC_METHOD_NOT_ALLOWED);
}
try {
return controllerClass.newInstance();
} catch (Exception e) {
Assumption.fail("Could not create the action for " + uri + ": "
+ TeammatesException.toStringWithStackTrace(e));
return null;
}
}
/**
* @inheritDoc
*/
@Override
public int createFolder(String folderPath, String folderClass, Map<String, String> properties) throws IOException {
Set<PropertyValue> propertyValues = new HashSet<>();
if (properties != null) {
for (Map.Entry<String, String> entry : properties.entrySet()) {
propertyValues.add(Field.createPropertyValue(entry.getKey(), entry.getValue()));
}
}
propertyValues.add(Field.createPropertyValue("folderclass", folderClass));
// standard MkColMethod does not take properties, override ExchangePropPatchRequest instead
ExchangePropPatchRequest propPatchRequest = new ExchangePropPatchRequest(URIUtil.encodePath(getFolderPath(folderPath)), propertyValues) {
@Override
public String getMethod() {
return "MKCOL";
}
};
int status;
try (CloseableHttpResponse response = httpClientAdapter.execute(propPatchRequest)) {
propPatchRequest.handleResponse(response);
status = response.getStatusLine().getStatusCode();
if (status == HttpStatus.SC_MULTI_STATUS) {
status = propPatchRequest.getResponseStatusCode();
} else if (status == HttpStatus.SC_METHOD_NOT_ALLOWED) {
LOGGER.info("Folder " + folderPath + " already exists");
}
} catch (HttpResponseException e) {
throw new IOException(e.getMessage(), e);
}
LOGGER.debug("Create folder " + folderPath + " returned " + status);
return status;
}
private Response handleWebApplicationException(final WebApplicationException webappException) {
Response res = webappException.getResponse();
if (HttpStatus.SC_METHOD_NOT_ALLOWED == res.getStatus()) {
return this.handleDcCoreException(DcCoreException.Misc.METHOD_NOT_ALLOWED);
}
return res;
}
@Override
public ThirdPartyObject getThirdPartyObject(String bucketName, String objectName)
throws GalaxyFDSClientException {
HashMap<String, String> params = new HashMap<String, String>();
params.put("thirdPartyObject", "");
URI uri = formatUri(fdsConfig.getBaseUri(), bucketName + "/" + objectName,
(SubResource[]) null);
HttpUriRequest httpRequest = fdsHttpClient.prepareRequestMethod(uri, HttpMethod.GET, null, null,
params, null, null);
HttpResponse response = fdsHttpClient.executeHttpRequest(httpRequest,
Action.GetThirdPartyObject);
ThirdPartyObject thirdPartyObject = null;
int statusCode = response.getStatusLine().getStatusCode();
try {
if (statusCode == HttpStatus.SC_OK) {
FDSObjectMetadata metadata = FDSObjectMetadata
.parseObjectMetadata(headerArray2MultiValuedMap(response.getAllHeaders()));
ThirdPartyObjectBean thirdPartyObjectBean = (ThirdPartyObjectBean) fdsHttpClient
.processResponse(response, ThirdPartyObjectBean.class,
"get third party object for object [" + objectName + "] under bucket [" + bucketName
+ "]");
thirdPartyObject = new ThirdPartyObject();
thirdPartyObject.setObjectMetadata(metadata);
thirdPartyObject.setThirdPartyObjectBean(thirdPartyObjectBean);
} else if (statusCode == HttpStatus.SC_METHOD_NOT_ALLOWED) {
return null;
} else {
String errorMsg = fdsHttpClient.formatErrorMsg("get third party object for object ["
+ objectName + "] under bucket [" + bucketName + "]",
response);
throw new GalaxyFDSClientException(errorMsg, statusCode);
}
} finally {
if (thirdPartyObject == null) {
fdsHttpClient.closeResponseEntity(response);
}
}
return thirdPartyObject;
}
@Override
protected FileType doGetType() throws Exception {
lastHeadResponse = executeHttpUriRequest(new HttpHead(getInternalURI()));
final int status = lastHeadResponse.getStatusLine().getStatusCode();
if (status == HttpStatus.SC_OK
|| status == HttpStatus.SC_METHOD_NOT_ALLOWED /* method is not allowed, but resource exist */) {
return FileType.FILE;
} else if (status == HttpStatus.SC_NOT_FOUND || status == HttpStatus.SC_GONE) {
return FileType.IMAGINARY;
} else {
throw new FileSystemException("vfs.provider.http/head.error", getName(), Integer.valueOf(status));
}
}
private void notAllowedResponseDidNotHaveAnAllowHeader(HttpRequest request,
HttpResponse response) throws ClientProtocolException {
if (response.getStatusLine().getStatusCode() != HttpStatus.SC_METHOD_NOT_ALLOWED)
return;
if (response.getFirstHeader(HeaderConstants.ALLOW) == null)
throw new ClientProtocolException(
"405 Response did not contain an Allow header.");
}
@SuppressWarnings("resource")
private String unshorten(String url, int loop) {
if (loop > 2) {
return null;
}
try (CloseableHttpClient defaultHttpClient = HttpClientBuilder.create()
.disableRedirectHandling().build()) {
HttpHead head = new HttpHead(url);
HttpResponse response = defaultHttpClient.execute(head);
int status = response.getStatusLine().getStatusCode();
if (status == HttpStatus.SC_MOVED_PERMANENTLY
|| status == HttpStatus.SC_MOVED_TEMPORARILY) {
Header locationHeader = response.getFirstHeader("location");
if (locationHeader != null) {
String value = locationHeader.getValue();
if (!value.startsWith("http") && value.startsWith("/")) {
value = "http:/" + value;
}
int nloop = loop + 1;
return unshorten(value, nloop);
}
}
else if (status >= 400 && status != HttpStatus.SC_METHOD_NOT_ALLOWED
&& status != HttpStatus.SC_FORBIDDEN) {
return null;
}
}
catch (IllegalStateException | IOException e) {
if (!(e instanceof SSLException || e instanceof ConnectException)) {
// ignore this
}
}
return url;
}
public BackgroundException map(final Throwable failure, final StringBuilder buffer, final int statusCode) {
switch(statusCode) {
case HttpStatus.SC_UNAUTHORIZED:
return new LoginFailureException(buffer.toString(), failure);
case HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED:
return new ProxyLoginFailureException(buffer.toString(), failure);
case HttpStatus.SC_FORBIDDEN:
case HttpStatus.SC_NOT_ACCEPTABLE:
return new AccessDeniedException(buffer.toString(), failure);
case HttpStatus.SC_CONFLICT:
return new ConflictException(buffer.toString(), failure);
case HttpStatus.SC_NOT_FOUND:
case HttpStatus.SC_GONE:
case HttpStatus.SC_REQUESTED_RANGE_NOT_SATISFIABLE:
return new NotfoundException(buffer.toString(), failure);
case HttpStatus.SC_INSUFFICIENT_SPACE_ON_RESOURCE:
case HttpStatus.SC_INSUFFICIENT_STORAGE:
case HttpStatus.SC_PAYMENT_REQUIRED:
return new QuotaException(buffer.toString(), failure);
case HttpStatus.SC_UNPROCESSABLE_ENTITY:
case HttpStatus.SC_BAD_REQUEST:
case HttpStatus.SC_REQUEST_URI_TOO_LONG:
case HttpStatus.SC_METHOD_NOT_ALLOWED:
case HttpStatus.SC_NOT_IMPLEMENTED:
return new InteroperabilityException(buffer.toString(), failure);
case HttpStatus.SC_REQUEST_TIMEOUT:
case HttpStatus.SC_GATEWAY_TIMEOUT:
return new ConnectionTimeoutException(buffer.toString(), failure);
case HttpStatus.SC_LOCKED:
return new LockedException(buffer.toString(), failure);
case HttpStatus.SC_BAD_GATEWAY:
case HttpStatus.SC_INTERNAL_SERVER_ERROR:
case HttpStatus.SC_SERVICE_UNAVAILABLE:
case 429:
// Too Many Requests. Rate limiting
case 509:
// Bandwidth Limit Exceeded
return new RetriableAccessDeniedException(buffer.toString(), failure);
default:
return new InteroperabilityException(buffer.toString(), failure);
}
}
private int computeStatus(int status) {
switch (status) {
case HttpStatus.SC_FORBIDDEN:
case HttpStatus.SC_METHOD_NOT_ALLOWED:
case HttpStatus.SC_BAD_REQUEST:
case HttpStatus.SC_UNAUTHORIZED:
case HttpStatus.SC_PAYMENT_REQUIRED:
case HttpStatus.SC_NOT_FOUND:
case HttpStatus.SC_NOT_ACCEPTABLE:
case HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED:
case HttpStatus.SC_REQUEST_TIMEOUT:
case HttpStatus.SC_CONFLICT:
case HttpStatus.SC_GONE:
case HttpStatus.SC_LENGTH_REQUIRED:
case HttpStatus.SC_PRECONDITION_FAILED:
case HttpStatus.SC_REQUEST_TOO_LONG:
case HttpStatus.SC_REQUEST_URI_TOO_LONG:
case HttpStatus.SC_UNSUPPORTED_MEDIA_TYPE:
case HttpStatus.SC_REQUESTED_RANGE_NOT_SATISFIABLE:
case HttpStatus.SC_EXPECTATION_FAILED:
case HttpStatus.SC_INSUFFICIENT_SPACE_ON_RESOURCE:
case HttpStatus.SC_METHOD_FAILURE:
case HttpStatus.SC_UNPROCESSABLE_ENTITY:
case HttpStatus.SC_LOCKED:
case HttpStatus.SC_FAILED_DEPENDENCY:
case HttpStatus.SC_INTERNAL_SERVER_ERROR:
case HttpStatus.SC_NOT_IMPLEMENTED:
case HttpStatus.SC_BAD_GATEWAY:
case HttpStatus.SC_SERVICE_UNAVAILABLE:
case HttpStatus.SC_GATEWAY_TIMEOUT:
case HttpStatus.SC_HTTP_VERSION_NOT_SUPPORTED:
case HttpStatus.SC_INSUFFICIENT_STORAGE:
return 0;
case HttpStatus.SC_CONTINUE:
case HttpStatus.SC_SWITCHING_PROTOCOLS:
case HttpStatus.SC_PROCESSING:
case HttpStatus.SC_OK:
case HttpStatus.SC_CREATED:
case HttpStatus.SC_ACCEPTED:
case HttpStatus.SC_NON_AUTHORITATIVE_INFORMATION:
case HttpStatus.SC_NO_CONTENT:
case HttpStatus.SC_RESET_CONTENT:
case HttpStatus.SC_PARTIAL_CONTENT:
case HttpStatus.SC_MULTI_STATUS:
case HttpStatus.SC_MULTIPLE_CHOICES:
case HttpStatus.SC_MOVED_PERMANENTLY:
case HttpStatus.SC_MOVED_TEMPORARILY:
case HttpStatus.SC_SEE_OTHER:
case HttpStatus.SC_NOT_MODIFIED:
case HttpStatus.SC_USE_PROXY:
case HttpStatus.SC_TEMPORARY_REDIRECT:
return 1;
default :
return 1;
}
}