Search in sources :

Example 76 with CosClientException

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

the class DelFileDemo method DelSingleFile.

// 删除单个文件(不带版本号, 即bucket未开启多版本)
public static void DelSingleFile() {
    // 1 初始化用户身份信息(secretId, secretKey)
    COSCredentials cred = new BasicCOSCredentials("AKIDXXXXXXXX", "1A2Z3YYYYYYYYYY");
    // 2 设置bucket的区域, COS地域的简称请参照 https://www.qcloud.com/document/product/436/6224
    ClientConfig clientConfig = new ClientConfig(new Region("ap-beijing-1"));
    // 3 生成cos客户端
    COSClient cosclient = new COSClient(cred, clientConfig);
    // bucket名需包含appid
    String bucketName = "mybucket-1251668577";
    try {
        // 空key值
        String key = "";
        cosclient.deleteObject(bucketName, key);
    } catch (CosServiceException e) {
        // 如果是其他错误, 比如参数错误, 身份验证不过等会抛出CosServiceException
        e.printStackTrace();
    } catch (CosClientException e) {
        // 如果是客户端错误,比如连接不上COS
        e.printStackTrace();
    } catch (IllegalArgumentException e) {
        // 该测试用例的预期结果
        e.printStackTrace();
    }
    try {
        String key = "aaa/bbb.txt";
        cosclient.deleteObject(bucketName, key);
    } catch (CosServiceException e) {
        // 如果是其他错误, 比如参数错误, 身份验证不过等会抛出CosServiceException
        e.printStackTrace();
    } catch (CosClientException e) {
        // 如果是客户端错误,比如连接不上COS
        e.printStackTrace();
    }
    // 关闭客户端
    cosclient.shutdown();
}
Also used : COSClient(com.qcloud.cos.COSClient) COSCredentials(com.qcloud.cos.auth.COSCredentials) BasicCOSCredentials(com.qcloud.cos.auth.BasicCOSCredentials) CosServiceException(com.qcloud.cos.exception.CosServiceException) BasicCOSCredentials(com.qcloud.cos.auth.BasicCOSCredentials) CosClientException(com.qcloud.cos.exception.CosClientException) Region(com.qcloud.cos.region.Region) ClientConfig(com.qcloud.cos.ClientConfig)

Example 77 with CosClientException

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

the class COSClient method deleteObjects.

@Override
public DeleteObjectsResult deleteObjects(DeleteObjectsRequest deleteObjectsRequest) throws MultiObjectDeleteException, CosClientException, CosServiceException {
    rejectNull(deleteObjectsRequest, "The DeleteObjectsRequest parameter must be specified when deleting objects");
    rejectNull(clientConfig.getRegion(), "region is null, region in clientConfig must be specified when deleting objects");
    CosHttpRequest<DeleteObjectsRequest> request = createRequest(deleteObjectsRequest.getBucketName(), null, deleteObjectsRequest, HttpMethodName.POST);
    request.addParameter("delete", null);
    byte[] content = new MultiObjectDeleteXmlFactory().convertToXmlByteArray(deleteObjectsRequest);
    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);
    }
    @SuppressWarnings("unchecked") ResponseHeaderHandlerChain<DeleteObjectsResponse> responseHandler = new ResponseHeaderHandlerChain<DeleteObjectsResponse>(new Unmarshallers.DeleteObjectsResultUnmarshaller());
    DeleteObjectsResponse response = invoke(request, responseHandler);
    /*
         * If the result was only partially successful, throw an exception
         */
    if (!response.getErrors().isEmpty()) {
        Map<String, String> headers = responseHandler.getResponseHeaders();
        MultiObjectDeleteException ex = new MultiObjectDeleteException(response.getErrors(), response.getDeletedObjects());
        ex.setStatusCode(200);
        ex.setRequestId(headers.get(Headers.REQUEST_ID));
        throw ex;
    }
    DeleteObjectsResult result = new DeleteObjectsResult(response.getDeletedObjects());
    return result;
}
Also used : DeleteObjectsResponse(com.qcloud.cos.internal.DeleteObjectsResponse) Unmarshallers(com.qcloud.cos.internal.Unmarshallers) 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) MultiObjectDeleteXmlFactory(com.qcloud.cos.internal.MultiObjectDeleteXmlFactory) ByteArrayInputStream(java.io.ByteArrayInputStream) MultiObjectDeleteException(com.qcloud.cos.exception.MultiObjectDeleteException) ResponseHeaderHandlerChain(com.qcloud.cos.internal.ResponseHeaderHandlerChain)

Example 78 with CosClientException

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

the class COSClient method setBucketTaggingConfiguration.

@Override
public void setBucketTaggingConfiguration(SetBucketTaggingConfigurationRequest setBucketTaggingConfigurationRequest) {
    rejectNull(setBucketTaggingConfigurationRequest, "The set bucket tagging configuration request object must be specified.");
    String bucketName = setBucketTaggingConfigurationRequest.getBucketName();
    BucketTaggingConfiguration bucketTaggingConfiguration = setBucketTaggingConfigurationRequest.getTaggingConfiguration();
    rejectNull(bucketName, "The bucket name parameter must be specified when setting bucket tagging configuration.");
    rejectNull(bucketTaggingConfiguration, "The tagging configuration parameter must be specified when setting bucket tagging configuration.");
    CosHttpRequest<SetBucketTaggingConfigurationRequest> request = createRequest(bucketName, null, setBucketTaggingConfigurationRequest, HttpMethodName.PUT);
    request.addParameter("tagging", null);
    byte[] content = new BucketConfigurationXmlFactory().convertToXmlByteArray(bucketTaggingConfiguration);
    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 79 with CosClientException

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

the class InstanceCredentialsUtils method readResource.

public String readResource(URI endpoint, CredentialsEndpointRetryPolicy retryPolicy, Map<String, String> headers) throws IOException {
    int retriesAttempted = 0;
    InputStream inputStream = null;
    Map<String, String> fullHeader = addDefaultHeader(headers);
    while (true) {
        try {
            HttpURLConnection connection = this.connectionUtils.connectToEndpoint(endpoint, fullHeader);
            int statusCode = connection.getResponseCode();
            if (statusCode == HttpURLConnection.HTTP_OK) {
                inputStream = connection.getInputStream();
                return IOUtils.toString(inputStream);
            } else if (statusCode == HttpURLConnection.HTTP_NOT_FOUND) {
                String errorMsg = "The requested metadata is not found at " + connection.getURL();
                LOG.error(errorMsg);
                throw new CosClientException(errorMsg);
            } else {
                LOG.error("The response status code is:" + statusCode);
                inputStream = connection.getErrorStream();
                String errorMessage = null;
                String errorCode = null;
                if (null != inputStream) {
                    String errorResponse = IOUtils.toString(inputStream);
                    LOG.error("errorResponse:" + errorResponse);
                    try {
                        JsonNode node = Jackson.jsonNodeOf(errorResponse);
                        JsonNode code = node.get("code");
                        JsonNode message = node.get("message");
                        if (null != code) {
                            errorCode = code.asText();
                        }
                        if (null != message) {
                            errorMessage = message.asText();
                        }
                    } catch (Exception exception) {
                        LOG.error("Unable to parse errorResponse:" + errorResponse, exception);
                    }
                }
                if (!retryPolicy.shouldRetry(retriesAttempted++, CredentialsEndpointRetryParameters.builder().withStatusCode(statusCode).build())) {
                    CosServiceException cosServiceException = new CosServiceException(connection.getResponseMessage());
                    if (null != errorMessage) {
                        cosServiceException.setErrorMessage(errorMessage);
                    }
                    if (null != errorCode) {
                        cosServiceException.setErrorCode(errorCode);
                    }
                    throw cosServiceException;
                }
            }
        } catch (IOException e) {
            LOG.error("An IOException occurred, service endpoint:" + endpoint + ", exception:", e);
            if (!retryPolicy.shouldRetry(retriesAttempted++, CredentialsEndpointRetryParameters.builder().withException(e).build())) {
                throw e;
            }
        } finally {
            IOUtils.closeQuietly(inputStream, LOG);
        }
    }
}
Also used : HttpURLConnection(java.net.HttpURLConnection) CosServiceException(com.qcloud.cos.exception.CosServiceException) InputStream(java.io.InputStream) CosClientException(com.qcloud.cos.exception.CosClientException) JsonNode(com.fasterxml.jackson.databind.JsonNode) IOException(java.io.IOException) CosClientException(com.qcloud.cos.exception.CosClientException) CosServiceException(com.qcloud.cos.exception.CosServiceException) IOException(java.io.IOException)

Example 80 with CosClientException

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

the class MultipartUploadDemo method copyPartUploadDemo.

// 分块copy, 表示该块的数据来自另外一个文件的某一范围, 支持跨园区, 跨bucket copy
public static void copyPartUploadDemo(String uploadId) {
    // 1 初始化用户身份信息(secretId, secretKey)
    COSCredentials cred = new BasicCOSCredentials("AKIDXXXXXXXX", "1A2Z3YYYYYYYYYY");
    // 2 设置bucket的区域, COS地域的简称请参照 https://www.qcloud.com/document/product/436/6224
    ClientConfig clientConfig = new ClientConfig(new Region("ap-guangzhou"));
    // 3 生成cos客户端
    COSClient cosclient = new COSClient(cred, clientConfig);
    // bucket名需包含appid
    String bucketName = "mybucket-1251668577";
    String key = "aaa/bbb.txt";
    CopyPartRequest copyPartRequest = new CopyPartRequest();
    // 要拷贝的源文件所在的region
    copyPartRequest.setSourceBucketRegion(new Region("ap-guangzhou"));
    // 要拷贝的源文件的bucket名称
    copyPartRequest.setSourceBucketName(bucketName);
    // 要拷贝的源文件的路径
    copyPartRequest.setSourceKey("aaa/ccc.txt");
    // 指定要拷贝的源文件的数据范围(类似content-range)
    copyPartRequest.setFirstByte(0L);
    copyPartRequest.setLastByte(1048575L);
    // 目的bucket名称
    copyPartRequest.setDestinationBucketName(bucketName);
    // 目的路径名称
    copyPartRequest.setDestinationKey(key);
    copyPartRequest.setPartNumber(1);
    // uploadId
    copyPartRequest.setUploadId(uploadId);
    try {
        CopyPartResult copyPartResult = cosclient.copyPart(copyPartRequest);
        PartETag partETag = copyPartResult.getPartETag();
    } catch (CosServiceException e) {
        e.printStackTrace();
    } catch (CosClientException e) {
        e.printStackTrace();
    }
    cosclient.shutdown();
}
Also used : COSClient(com.qcloud.cos.COSClient) CopyPartRequest(com.qcloud.cos.model.CopyPartRequest) COSCredentials(com.qcloud.cos.auth.COSCredentials) BasicCOSCredentials(com.qcloud.cos.auth.BasicCOSCredentials) CosServiceException(com.qcloud.cos.exception.CosServiceException) BasicCOSCredentials(com.qcloud.cos.auth.BasicCOSCredentials) CosClientException(com.qcloud.cos.exception.CosClientException) Region(com.qcloud.cos.region.Region) ClientConfig(com.qcloud.cos.ClientConfig) CopyPartResult(com.qcloud.cos.model.CopyPartResult) PartETag(com.qcloud.cos.model.PartETag)

Aggregations

CosClientException (com.qcloud.cos.exception.CosClientException)111 CosServiceException (com.qcloud.cos.exception.CosServiceException)64 COSCredentials (com.qcloud.cos.auth.COSCredentials)41 ClientConfig (com.qcloud.cos.ClientConfig)39 BasicCOSCredentials (com.qcloud.cos.auth.BasicCOSCredentials)39 Region (com.qcloud.cos.region.Region)39 COSClient (com.qcloud.cos.COSClient)37 IOException (java.io.IOException)31 File (java.io.File)28 ByteArrayInputStream (java.io.ByteArrayInputStream)18 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)15 TransferManager (com.qcloud.cos.transfer.TransferManager)14 ExecutorService (java.util.concurrent.ExecutorService)14 ObjectMetadata (com.qcloud.cos.model.ObjectMetadata)13 URISyntaxException (java.net.URISyntaxException)13 MultiObjectDeleteException (com.qcloud.cos.exception.MultiObjectDeleteException)12 PutObjectRequest (com.qcloud.cos.model.PutObjectRequest)12 SecretKey (javax.crypto.SecretKey)12 MalformedURLException (java.net.MalformedURLException)11 PutObjectResult (com.qcloud.cos.model.PutObjectResult)10