Search in sources :

Example 1 with ServiceException

use of com.aliyun.oss.ServiceException in project aliyun-oss-java-sdk by aliyun.

the class OSSObjectOperation method getObjectMetadata.

/**
 * Get object matadata.
 */
public ObjectMetadata getObjectMetadata(GenericRequest genericRequest) throws OSSException, ClientException {
    assertParameterNotNull(genericRequest, "genericRequest");
    String bucketName = genericRequest.getBucketName();
    String key = genericRequest.getKey();
    assertParameterNotNull(bucketName, "bucketName");
    assertParameterNotNull(key, "key");
    ensureBucketNameValid(bucketName);
    ensureObjectKeyValid(key);
    RequestMessage request = new OSSRequestMessageBuilder(getInnerClient()).setEndpoint(getEndpoint()).setMethod(HttpMethod.HEAD).setBucket(bucketName).setKey(key).setOriginalRequest(genericRequest).build();
    List<ResponseHandler> reponseHandlers = new ArrayList<ResponseHandler>();
    reponseHandlers.add(new ResponseHandler() {

        @Override
        public void handle(ResponseMessage response) throws ServiceException, ClientException {
            if (response.getStatusCode() == HttpStatus.SC_NOT_FOUND) {
                safeCloseResponse(response);
                throw ExceptionFactory.createOSSException(response.getHeaders().get(OSSHeaders.OSS_HEADER_REQUEST_ID), OSSErrorCode.NO_SUCH_KEY, OSS_RESOURCE_MANAGER.getString("NoSuchKey"));
            }
        }
    });
    return doOperation(request, getObjectMetadataResponseParser, bucketName, key, true, null, reponseHandlers);
}
Also used : ResponseHandler(com.aliyun.oss.common.comm.ResponseHandler) ServiceException(com.aliyun.oss.ServiceException) RequestMessage(com.aliyun.oss.common.comm.RequestMessage) ArrayList(java.util.ArrayList) ResponseMessage(com.aliyun.oss.common.comm.ResponseMessage) ClientException(com.aliyun.oss.ClientException)

Example 2 with ServiceException

use of com.aliyun.oss.ServiceException in project aliyun-oss-java-sdk by aliyun.

the class ServiceClient method sendRequestImpl.

private ResponseMessage sendRequestImpl(RequestMessage request, ExecutionContext context) throws ClientException, ServiceException {
    RetryStrategy retryStrategy = context.getRetryStrategy() != null ? context.getRetryStrategy() : this.getDefaultRetryStrategy();
    // Sign the request if a signer provided.
    if (context.getSigner() != null && !request.isUseUrlSignature()) {
        context.getSigner().sign(request);
    }
    for (RequestSigner signer : context.getSignerHandlers()) {
        signer.sign(request);
    }
    InputStream requestContent = request.getContent();
    if (requestContent != null && requestContent.markSupported()) {
        requestContent.mark(OSSConstants.DEFAULT_STREAM_BUFFER_SIZE);
    }
    int retries = 0;
    ResponseMessage response = null;
    while (true) {
        try {
            if (retries > 0) {
                pause(retries, retryStrategy);
                if (requestContent != null && requestContent.markSupported()) {
                    try {
                        requestContent.reset();
                    } catch (IOException ex) {
                        logException("Failed to reset the request input stream: ", ex);
                        throw new ClientException("Failed to reset the request input stream: ", ex);
                    }
                }
            }
            /*
                 * The key four steps to send HTTP requests and receive HTTP
                 * responses.
                 */
            // Step 1. Preprocess HTTP request.
            handleRequest(request, context.getResquestHandlers());
            // Step 2. Build HTTP request with specified request parameters
            // and context.
            Request httpRequest = buildRequest(request, context);
            // Step 3. Send HTTP request to OSS.
            long startTime = System.currentTimeMillis();
            response = sendRequestCore(httpRequest, context);
            long duration = System.currentTimeMillis() - startTime;
            if (duration > config.getSlowRequestsThreshold()) {
                LogUtils.getLog().warn(formatSlowRequestLog(request, response, duration));
            }
            // Step 4. Preprocess HTTP response.
            handleResponse(response, context.getResponseHandlers());
            return response;
        } catch (ServiceException sex) {
            logException("[Server]Unable to execute HTTP request: ", sex, request.getOriginalRequest().isLogEnabled());
            // Notice that the response should not be closed in the
            // finally block because if the request is successful,
            // the response should be returned to the callers.
            closeResponseSilently(response);
            if (!shouldRetry(sex, request, response, retries, retryStrategy)) {
                throw sex;
            }
        } catch (ClientException cex) {
            logException("[Client]Unable to execute HTTP request: ", cex, request.getOriginalRequest().isLogEnabled());
            closeResponseSilently(response);
            if (!shouldRetry(cex, request, response, retries, retryStrategy)) {
                throw cex;
            }
        } catch (Exception ex) {
            logException("[Unknown]Unable to execute HTTP request: ", ex, request.getOriginalRequest().isLogEnabled());
            closeResponseSilently(response);
            throw new ClientException(COMMON_RESOURCE_MANAGER.getFormattedString("ConnectionError", ex.getMessage()), ex);
        } finally {
            retries++;
        }
    }
}
Also used : ServiceException(com.aliyun.oss.ServiceException) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) IOException(java.io.IOException) ClientException(com.aliyun.oss.ClientException) IOException(java.io.IOException) LogUtils.logException(com.aliyun.oss.common.utils.LogUtils.logException) ClientException(com.aliyun.oss.ClientException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) ServiceException(com.aliyun.oss.ServiceException) RequestSigner(com.aliyun.oss.common.auth.RequestSigner)

Example 3 with ServiceException

use of com.aliyun.oss.ServiceException in project alluxio by Alluxio.

the class OSSUnderFileSystem method createEmptyObject.

@Override
public boolean createEmptyObject(String key) {
    try {
        ObjectMetadata objMeta = new ObjectMetadata();
        objMeta.setContentLength(0);
        mClient.putObject(mBucketName, key, new ByteArrayInputStream(new byte[0]), objMeta);
        return true;
    } catch (ServiceException e) {
        LOG.error("Failed to create object: {}", key, e);
        return false;
    }
}
Also used : ServiceException(com.aliyun.oss.ServiceException) ByteArrayInputStream(java.io.ByteArrayInputStream) ObjectMetadata(com.aliyun.oss.model.ObjectMetadata)

Example 4 with ServiceException

use of com.aliyun.oss.ServiceException in project aliyun-oss-java-sdk by aliyun.

the class OSSBucketOperation method getBucketMetadata.

public BucketMetadata getBucketMetadata(GenericRequest genericRequest) throws OSSException, ClientException {
    assertParameterNotNull(genericRequest, "genericRequest");
    String bucketName = genericRequest.getBucketName();
    assertParameterNotNull(bucketName, "bucketName");
    ensureBucketNameValid(bucketName);
    RequestMessage request = new OSSRequestMessageBuilder(getInnerClient()).setEndpoint(getEndpoint()).setMethod(HttpMethod.HEAD).setBucket(bucketName).setOriginalRequest(genericRequest).build();
    List<ResponseHandler> reponseHandlers = new ArrayList<ResponseHandler>();
    reponseHandlers.add(new ResponseHandler() {

        @Override
        public void handle(ResponseMessage response) throws ServiceException, ClientException {
            if (response.getStatusCode() == HttpStatus.SC_NOT_FOUND) {
                safeCloseResponse(response);
                throw ExceptionFactory.createOSSException(response.getHeaders().get(OSSHeaders.OSS_HEADER_REQUEST_ID), OSSErrorCode.NO_SUCH_BUCKET, OSS_RESOURCE_MANAGER.getString("NoSuchBucket"));
            }
        }
    });
    return doOperation(request, ResponseParsers.getBucketMetadataResponseParser, bucketName, null, true, null, reponseHandlers);
}
Also used : ResponseHandler(com.aliyun.oss.common.comm.ResponseHandler) ServiceException(com.aliyun.oss.ServiceException) RequestMessage(com.aliyun.oss.common.comm.RequestMessage) ArrayList(java.util.ArrayList) ResponseMessage(com.aliyun.oss.common.comm.ResponseMessage) ClientException(com.aliyun.oss.ClientException)

Example 5 with ServiceException

use of com.aliyun.oss.ServiceException in project aliyun-oss-java-sdk by aliyun.

the class ServiceClientTest method testRetryWithServiceException.

@Test
public void testRetryWithServiceException() throws Exception {
    // This request will fail after 1 retries
    ClientConfiguration config = new ClientConfiguration();
    config.setMaxErrorRetry(1);
    // It should be always successful.
    int maxFailures = 0;
    String content = "Let's retry!";
    byte[] contentBytes = content.getBytes(OSSConstants.DEFAULT_CHARSET_NAME);
    ByteArrayInputStream contentStream = new ByteArrayInputStream(contentBytes);
    RequestMessage request = new RequestMessage(null, null);
    request.setEndpoint(new URI("http://localhost"));
    request.setMethod(HttpMethod.GET);
    request.setContent(contentStream);
    request.setContentLength(contentBytes.length);
    ExecutionContext context = new ExecutionContext();
    context.getResponseHandlers().add(new ResponseHandler() {

        @Override
        public void handle(ResponseMessage responseData) throws ServiceException, ClientException {
            throw new ServiceException();
        }
    });
    // This request will succeed after 2 retries
    ServiceClientImpl client = new ServiceClientImpl(config, maxFailures, null, 500, content);
    // Fix the max error retry count to 3
    try {
        client.sendRequest(request, context);
        fail("ServiceException has not been thrown.");
    } catch (ServiceException e) {
        assertEquals(2, client.getRequestAttempts());
    }
}
Also used : ResponseHandler(com.aliyun.oss.common.comm.ResponseHandler) ResponseMessage(com.aliyun.oss.common.comm.ResponseMessage) URI(java.net.URI) ExecutionContext(com.aliyun.oss.common.comm.ExecutionContext) ServiceException(com.aliyun.oss.ServiceException) ByteArrayInputStream(java.io.ByteArrayInputStream) RequestMessage(com.aliyun.oss.common.comm.RequestMessage) ClientException(com.aliyun.oss.ClientException) ClientConfiguration(com.aliyun.oss.ClientConfiguration) Test(org.junit.Test)

Aggregations

ServiceException (com.aliyun.oss.ServiceException)7 ClientException (com.aliyun.oss.ClientException)4 RequestMessage (com.aliyun.oss.common.comm.RequestMessage)3 ResponseHandler (com.aliyun.oss.common.comm.ResponseHandler)3 ResponseMessage (com.aliyun.oss.common.comm.ResponseMessage)3 ObjectMetadata (com.aliyun.oss.model.ObjectMetadata)3 ByteArrayInputStream (java.io.ByteArrayInputStream)3 IOException (java.io.IOException)2 ArrayList (java.util.ArrayList)2 ClientConfiguration (com.aliyun.oss.ClientConfiguration)1 RequestSigner (com.aliyun.oss.common.auth.RequestSigner)1 ExecutionContext (com.aliyun.oss.common.comm.ExecutionContext)1 LogUtils.logException (com.aliyun.oss.common.utils.LogUtils.logException)1 BufferedInputStream (java.io.BufferedInputStream)1 FileInputStream (java.io.FileInputStream)1 InputStream (java.io.InputStream)1 UnsupportedEncodingException (java.io.UnsupportedEncodingException)1 URI (java.net.URI)1 Date (java.util.Date)1 Test (org.junit.Test)1