Search in sources :

Example 16 with CosServiceException

use of com.qcloud.cos.exception.CosServiceException in project cos-java-sdk-v5 by tencentyun.

the class COSClient method setBucketLifecycleConfiguration.

@Override
public void setBucketLifecycleConfiguration(SetBucketLifecycleConfigurationRequest setBucketLifecycleConfigurationRequest) throws CosClientException, CosServiceException {
    rejectNull(setBucketLifecycleConfigurationRequest, "The set bucket lifecycle configuration request object must be specified.");
    String bucketName = setBucketLifecycleConfigurationRequest.getBucketName();
    BucketLifecycleConfiguration bucketLifecycleConfiguration = setBucketLifecycleConfigurationRequest.getLifecycleConfiguration();
    rejectNull(bucketName, "The bucket name parameter must be specified when setting bucket lifecycle configuration.");
    rejectNull(bucketLifecycleConfiguration, "The lifecycle configuration parameter must be specified when setting bucket lifecycle configuration.");
    rejectNull(clientConfig.getRegion(), "region is null, region in clientConfig must be specified when setting bucket lifecycle configuration");
    CosHttpRequest<SetBucketLifecycleConfigurationRequest> request = createRequest(bucketName, null, setBucketLifecycleConfigurationRequest, HttpMethodName.PUT);
    request.addParameter("lifecycle", null);
    byte[] content = new BucketConfigurationXmlFactory().convertToXmlByteArray(bucketLifecycleConfiguration);
    request.addHeader("Content-Length", String.valueOf(content.length));
    request.addHeader("Content-Type", "application/xml");
    request.setContent(new ByteArrayInputStream(content));
    try {
        byte[] md5 = Md5Utils.computeMD5Hash(content);
        String md5Base64 = BinaryUtils.toBase64(md5);
        request.addHeader("Content-MD5", md5Base64);
    } catch (Exception e) {
        throw new CosClientException("Couldn't compute md5 sum", e);
    }
    invoke(request, voidCosResponseHandler);
}
Also used : ByteArrayInputStream(java.io.ByteArrayInputStream) CosClientException(com.qcloud.cos.exception.CosClientException) DecoderException(org.apache.commons.codec.DecoderException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) MultiObjectDeleteException(com.qcloud.cos.exception.MultiObjectDeleteException) IOException(java.io.IOException) URISyntaxException(java.net.URISyntaxException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) CosServiceException(com.qcloud.cos.exception.CosServiceException) CosClientException(com.qcloud.cos.exception.CosClientException) MalformedURLException(java.net.MalformedURLException)

Example 17 with CosServiceException

use of com.qcloud.cos.exception.CosServiceException in project cos-java-sdk-v5 by tencentyun.

the class COSClient method getObject.

@Override
public COSObject getObject(GetObjectRequest getObjectRequest) throws CosClientException, CosServiceException {
    rejectNull(getObjectRequest, "The GetObjectRequest parameter must be specified when requesting an object");
    rejectNull(getObjectRequest.getBucketName(), "The bucket name parameter must be specified when requesting an object");
    rejectNull(getObjectRequest.getKey(), "The key parameter must be specified when requesting an object");
    rejectNull(clientConfig.getRegion(), "region is null, region in clientConfig must be specified when requesting an object");
    CosHttpRequest<GetObjectRequest> request = createRequest(getObjectRequest.getBucketName(), getObjectRequest.getKey(), getObjectRequest, HttpMethodName.GET);
    addParameterIfNotNull(request, "versionId", getObjectRequest.getVersionId());
    // Range
    long[] range = getObjectRequest.getRange();
    if (range != null) {
        request.addHeader(Headers.RANGE, "bytes=" + Long.toString(range[0]) + "-" + Long.toString(range[1]));
    }
    addResponseHeaderParameters(request, getObjectRequest.getResponseHeaders());
    addDateHeader(request, Headers.GET_OBJECT_IF_MODIFIED_SINCE, getObjectRequest.getModifiedSinceConstraint());
    addDateHeader(request, Headers.GET_OBJECT_IF_UNMODIFIED_SINCE, getObjectRequest.getUnmodifiedSinceConstraint());
    addStringListHeader(request, Headers.GET_OBJECT_IF_MATCH, getObjectRequest.getMatchingETagConstraints());
    addStringListHeader(request, Headers.GET_OBJECT_IF_NONE_MATCH, getObjectRequest.getNonmatchingETagConstraints());
    // Populate the SSE-C parameters to the request header
    populateSSE_C(request, getObjectRequest.getSSECustomerKey());
    // Populate the traffic limit parameter to the request header
    populateTrafficLimit(request, getObjectRequest.getTrafficLimit());
    try {
        COSObject cosObject = invoke(request, new COSObjectResponseHandler());
        cosObject.setBucketName(getObjectRequest.getBucketName());
        cosObject.setKey(getObjectRequest.getKey());
        InputStream is = cosObject.getObjectContent();
        HttpRequestBase httpRequest = cosObject.getObjectContent().getHttpRequest();
        is = new ServiceClientHolderInputStream(is, this);
        // bytes and complains if what we received doesn't match the Etag.
        if (!skipMd5CheckStrategy.skipClientSideValidation(getObjectRequest, cosObject.getObjectMetadata())) {
            try {
                byte[] serverSideHash = BinaryUtils.fromHex(cosObject.getObjectMetadata().getETag());
                // No content length check is performed when the
                // MD5 check is enabled, since a correct MD5 check would
                // imply a correct content length.
                MessageDigest digest = MessageDigest.getInstance("MD5");
                is = new DigestValidationInputStream(is, digest, serverSideHash);
            } catch (NoSuchAlgorithmException e) {
                log.warn("No MD5 digest algorithm available.  Unable to calculate " + "checksum and verify data integrity.", e);
            } catch (DecoderException e) {
                log.warn("BinaryUtils.fromHex error. Unable to calculate " + "checksum and verify data integrity. etag:" + cosObject.getObjectMetadata().getETag(), e);
            }
        } else {
            // Ensures the data received from COS has the same length as the
            // expected content-length
            is = new LengthCheckInputStream(is, // expected length
            cosObject.getObjectMetadata().getContentLength(), // bytes received from cos are all included even if
            INCLUDE_SKIPPED_BYTES);
        // skipped
        }
        cosObject.setObjectContent(new COSObjectInputStream(is, httpRequest));
        return cosObject;
    } catch (CosServiceException cse) {
        /*
             * If the request failed because one of the specified constraints was not met (ex:
             * matching ETag, modified since date, etc.), then return null, so that users don't have
             * to wrap their code in try/catch blocks and check for this status code if they want to
             * use constraints.
             */
        if (cse.getStatusCode() == 412 || cse.getStatusCode() == 304) {
            return null;
        }
        throw cse;
    }
}
Also used : LengthCheckInputStream(com.qcloud.cos.internal.LengthCheckInputStream) HttpRequestBase(org.apache.http.client.methods.HttpRequestBase) DigestValidationInputStream(com.qcloud.cos.internal.DigestValidationInputStream) ReleasableInputStream(com.qcloud.cos.internal.ReleasableInputStream) MD5DigestCalculatingInputStream(com.qcloud.cos.internal.MD5DigestCalculatingInputStream) LengthCheckInputStream(com.qcloud.cos.internal.LengthCheckInputStream) ServiceClientHolderInputStream(com.qcloud.cos.internal.ServiceClientHolderInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) ResettableInputStream(com.qcloud.cos.internal.ResettableInputStream) SdkFilterInputStream(com.qcloud.cos.internal.SdkFilterInputStream) InputStream(java.io.InputStream) COSObjectResponseHandler(com.qcloud.cos.internal.COSObjectResponseHandler) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) DecoderException(org.apache.commons.codec.DecoderException) DigestValidationInputStream(com.qcloud.cos.internal.DigestValidationInputStream) CosServiceException(com.qcloud.cos.exception.CosServiceException) MessageDigest(java.security.MessageDigest) ServiceClientHolderInputStream(com.qcloud.cos.internal.ServiceClientHolderInputStream)

Example 18 with CosServiceException

use of com.qcloud.cos.exception.CosServiceException in project cos-java-sdk-v5 by tencentyun.

the class COSClient method copyObject.

@Override
public CopyObjectResult copyObject(CopyObjectRequest copyObjectRequest) throws CosClientException, CosServiceException {
    rejectNull(copyObjectRequest, "The CopyObjectRequest parameter must be specified when copying an object");
    rejectNull(copyObjectRequest.getSourceBucketName(), "The source bucket name must be specified when copying an object");
    rejectNull(copyObjectRequest.getSourceKey(), "The source object key must be specified when copying an object");
    rejectNull(copyObjectRequest.getDestinationBucketName(), "The destination bucket name must be specified when copying an object");
    rejectNull(copyObjectRequest.getDestinationKey(), "The destination object key must be specified when copying an object");
    rejectNull(clientConfig.getRegion(), "region is null, region in clientConfig must be specified when copying an object");
    String destinationKey = copyObjectRequest.getDestinationKey();
    String destinationBucketName = copyObjectRequest.getDestinationBucketName();
    CosHttpRequest<CopyObjectRequest> request = createRequest(destinationBucketName, destinationKey, copyObjectRequest, HttpMethodName.PUT);
    populateRequestWithCopyObjectParameters(request, copyObjectRequest);
    /*
         * We can't send a non-zero length Content-Length header if the user specified it, otherwise
         * it messes up the HTTP connection when the remote server thinks there's more data to pull.
         */
    setZeroContentLength(request);
    CopyObjectResultHandler copyObjectResultHandler = null;
    try {
        @SuppressWarnings("unchecked") ResponseHeaderHandlerChain<CopyObjectResultHandler> handler = new ResponseHeaderHandlerChain<CopyObjectResultHandler>(// xml payload unmarshaller
        new Unmarshallers.CopyObjectUnmarshaller(), // header handlers
        new ServerSideEncryptionHeaderHandler<CopyObjectResultHandler>(), new ObjectExpirationHeaderHandler<CopyObjectResultHandler>(), new VIDResultHandler<CopyObjectResultHandler>());
        copyObjectResultHandler = invoke(request, handler);
    } catch (CosServiceException cse) {
        /*
             * If the request failed because one of the specified constraints was not met (ex:
             * matching ETag, modified since date, etc.), then return null, so that users don't have
             * to wrap their code in try/catch blocks and check for this status code if they want to
             * use constraints.
             */
        if (cse.getStatusCode() == Constants.FAILED_PRECONDITION_STATUS_CODE) {
            return null;
        }
        throw cse;
    }
    /*
         * CopyObject has two failure modes: 1 - An HTTP error code is returned and the error is
         * processed like any other error response. 2 - An HTTP 200 OK code is returned, but the
         * response content contains an XML error response.
         *
         * This makes it very difficult for the client runtime to cleanly detect this case and
         * handle it like any other error response. We could extend the runtime to have a more
         * flexible/customizable definition of success/error (per request), but it's probably
         * overkill for this one special case.
         */
    if (copyObjectResultHandler.getErrorCode() != null) {
        String errorCode = copyObjectResultHandler.getErrorCode();
        String errorMessage = copyObjectResultHandler.getErrorMessage();
        String requestId = copyObjectResultHandler.getErrorRequestId();
        CosServiceException cse = new CosServiceException(errorMessage);
        cse.setErrorCode(errorCode);
        cse.setRequestId(requestId);
        cse.setStatusCode(200);
        throw cse;
    }
    CopyObjectResult copyObjectResult = new CopyObjectResult();
    copyObjectResult.setETag(copyObjectResultHandler.getETag());
    copyObjectResult.setLastModifiedDate(copyObjectResultHandler.getLastModified());
    copyObjectResult.setVersionId(copyObjectResultHandler.getVersionId());
    copyObjectResult.setSSEAlgorithm(copyObjectResultHandler.getSSEAlgorithm());
    copyObjectResult.setSSECustomerAlgorithm(copyObjectResultHandler.getSSECustomerAlgorithm());
    copyObjectResult.setSSECustomerKeyMd5(copyObjectResultHandler.getSSECustomerKeyMd5());
    copyObjectResult.setExpirationTime(copyObjectResultHandler.getExpirationTime());
    copyObjectResult.setExpirationTimeRuleId(copyObjectResultHandler.getExpirationTimeRuleId());
    copyObjectResult.setDateStr(copyObjectResultHandler.getDateStr());
    copyObjectResult.setCrc64Ecma(copyObjectResultHandler.getCrc64Ecma());
    copyObjectResult.setRequestId(copyObjectResultHandler.getRequestId());
    return copyObjectResult;
}
Also used : Unmarshallers(com.qcloud.cos.internal.Unmarshallers) CosServiceException(com.qcloud.cos.exception.CosServiceException) CopyObjectResultHandler(com.qcloud.cos.internal.XmlResponsesSaxParser.CopyObjectResultHandler) ResponseHeaderHandlerChain(com.qcloud.cos.internal.ResponseHeaderHandlerChain)

Example 19 with CosServiceException

use of com.qcloud.cos.exception.CosServiceException in project cos-java-sdk-v5 by tencentyun.

the class COSClient method getBucketPolicy.

@Override
public BucketPolicy getBucketPolicy(GetBucketPolicyRequest getBucketPolicyRequest) throws CosClientException, CosServiceException {
    rejectNull(getBucketPolicyRequest, "The request object must be specified when getting a bucket policy");
    String bucketName = getBucketPolicyRequest.getBucketName();
    rejectNull(bucketName, "The bucket name must be specified when getting a bucket policy");
    CosHttpRequest<GetBucketPolicyRequest> request = createRequest(bucketName, null, getBucketPolicyRequest, HttpMethodName.GET);
    request.addParameter("policy", null);
    BucketPolicy result = new BucketPolicy();
    try {
        String policyText = invoke(request, new COSStringResponseHandler());
        result.setPolicyText(policyText);
        return result;
    } catch (CosServiceException cse) {
        if (cse.getErrorCode().equals("NoSuchBucketPolicy"))
            return result;
        throw cse;
    }
}
Also used : CosServiceException(com.qcloud.cos.exception.CosServiceException) COSStringResponseHandler(com.qcloud.cos.internal.COSStringResponseHandler)

Example 20 with CosServiceException

use of com.qcloud.cos.exception.CosServiceException in project cos-java-sdk-v5 by tencentyun.

the class COSClient method restoreObject.

@Override
public void restoreObject(RestoreObjectRequest restoreObjectRequest) throws CosClientException, CosServiceException {
    rejectNull(restoreObjectRequest, "The RestoreObjectRequest parameter must be specified when restore a object.");
    String bucketName = restoreObjectRequest.getBucketName();
    String key = restoreObjectRequest.getKey();
    String versionId = restoreObjectRequest.getVersionId();
    int expirationIndays = restoreObjectRequest.getExpirationInDays();
    rejectNull(bucketName, "The bucket name parameter must be specified when copying a cas object");
    rejectNull(key, "The key parameter must be specified when copying a cas object");
    if (expirationIndays == -1) {
        throw new IllegalArgumentException("The expiration in days parameter must be specified when copying a cas object");
    }
    CosHttpRequest<RestoreObjectRequest> request = createRequest(bucketName, key, restoreObjectRequest, HttpMethodName.POST);
    request.addParameter("restore", null);
    addParameterIfNotNull(request, "versionId", versionId);
    byte[] content = RequestXmlFactory.convertToXmlByteArray(restoreObjectRequest);
    request.addHeader("Content-Length", String.valueOf(content.length));
    request.addHeader("Content-Type", "application/xml");
    request.setContent(new ByteArrayInputStream(content));
    try {
        byte[] md5 = Md5Utils.computeMD5Hash(content);
        String md5Base64 = BinaryUtils.toBase64(md5);
        request.addHeader("Content-MD5", md5Base64);
    } catch (Exception e) {
        throw new CosClientException("Couldn't compute md5 sum", e);
    }
    invoke(request, voidCosResponseHandler);
}
Also used : ByteArrayInputStream(java.io.ByteArrayInputStream) CosClientException(com.qcloud.cos.exception.CosClientException) DecoderException(org.apache.commons.codec.DecoderException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) MultiObjectDeleteException(com.qcloud.cos.exception.MultiObjectDeleteException) IOException(java.io.IOException) URISyntaxException(java.net.URISyntaxException) UnsupportedEncodingException(java.io.UnsupportedEncodingException) CosServiceException(com.qcloud.cos.exception.CosServiceException) CosClientException(com.qcloud.cos.exception.CosClientException) MalformedURLException(java.net.MalformedURLException)

Aggregations

CosServiceException (com.qcloud.cos.exception.CosServiceException)82 CosClientException (com.qcloud.cos.exception.CosClientException)64 COSClient (com.qcloud.cos.COSClient)37 ClientConfig (com.qcloud.cos.ClientConfig)37 BasicCOSCredentials (com.qcloud.cos.auth.BasicCOSCredentials)37 COSCredentials (com.qcloud.cos.auth.COSCredentials)37 Region (com.qcloud.cos.region.Region)37 File (java.io.File)28 IOException (java.io.IOException)20 PutObjectRequest (com.qcloud.cos.model.PutObjectRequest)15 TransferManager (com.qcloud.cos.transfer.TransferManager)14 ExecutorService (java.util.concurrent.ExecutorService)14 GetObjectRequest (com.qcloud.cos.model.GetObjectRequest)13 ByteArrayInputStream (java.io.ByteArrayInputStream)13 PutObjectResult (com.qcloud.cos.model.PutObjectResult)12 MultiObjectDeleteException (com.qcloud.cos.exception.MultiObjectDeleteException)11 ObjectMetadata (com.qcloud.cos.model.ObjectMetadata)11 ArrayList (java.util.ArrayList)10 LinkedList (java.util.LinkedList)10 Test (org.junit.Test)10