Search in sources :

Example 21 with CosClientException

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

the class COSClient method getObjectUrl.

public URL getObjectUrl(GetObjectRequest getObjectRequest) {
    rejectNull(clientConfig.getRegion(), "region is null, region in clientConfig must be specified when generating a pre-signed URL");
    rejectNull(getObjectRequest, "The request parameter must be specified when generating a pre-signed URL");
    final String bucketName = getObjectRequest.getBucketName();
    final String key = getObjectRequest.getKey();
    CosHttpRequest<GetObjectRequest> request = createRequest(bucketName, key, getObjectRequest, HttpMethodName.GET);
    addParameterIfNotNull(request, "versionId", getObjectRequest.getVersionId());
    COSCredentials cred = fetchCredential();
    StringBuilder strBuilder = new StringBuilder();
    strBuilder.append(clientConfig.getHttpProtocol().toString()).append("://");
    strBuilder.append(clientConfig.getEndpointBuilder().buildGeneralApiEndpoint(formatBucket(bucketName, cred.getCOSAppId())));
    strBuilder.append(UrlEncoderUtils.encodeUrlPath(formatKey(key)));
    boolean hasAppendFirstParameter = false;
    for (Entry<String, String> entry : request.getParameters().entrySet()) {
        String paramKey = entry.getKey();
        String paramValue = entry.getValue();
        if (!hasAppendFirstParameter) {
            strBuilder.append("?");
            hasAppendFirstParameter = true;
        } else {
            strBuilder.append("&");
        }
        strBuilder.append(UrlEncoderUtils.encode(paramKey));
        if (paramValue != null) {
            strBuilder.append("=").append(UrlEncoderUtils.encode(paramValue));
        }
    }
    try {
        return new URL(strBuilder.toString());
    } catch (MalformedURLException e) {
        throw new CosClientException(e.toString());
    }
}
Also used : MalformedURLException(java.net.MalformedURLException) COSCredentials(com.qcloud.cos.auth.COSCredentials) CosClientException(com.qcloud.cos.exception.CosClientException) URL(java.net.URL)

Example 22 with CosClientException

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

the class COSClient method doUploadPart.

private UploadPartResult doUploadPart(final String bucketName, final String key, final String uploadId, final int partNumber, final long partSize, CosHttpRequest<UploadPartRequest> request, InputStream inputStream, MD5DigestCalculatingInputStream md5DigestStream) {
    try {
        request.setContent(inputStream);
        ObjectMetadata metadata = invoke(request, new CosMetadataResponseHandler());
        final String etag = metadata.getETag();
        if (md5DigestStream != null && !skipMd5CheckStrategy.skipClientSideValidationPerUploadPartResponse(metadata)) {
            byte[] clientSideHash = md5DigestStream.getMd5Digest();
            byte[] serverSideHash = BinaryUtils.fromHex(etag);
            if (!Arrays.equals(clientSideHash, serverSideHash)) {
                final String info = "bucketName: " + bucketName + ", key: " + key + ", uploadId: " + uploadId + ", partNumber: " + partNumber + ", partSize: " + partSize;
                throw new CosClientException("Unable to verify integrity of data upload.  " + "Client calculated content hash (contentMD5: " + BinaryUtils.toHex(clientSideHash) + " in hex) didn't match hash (etag: " + etag + " in hex) calculated by Qcloud COS.  " + "You may need to delete the data stored in Qcloud COS. " + "(" + info + ")");
            }
        }
        UploadPartResult result = new UploadPartResult();
        result.setETag(etag);
        result.setPartNumber(partNumber);
        result.setSSEAlgorithm(metadata.getSSEAlgorithm());
        result.setSSECustomerAlgorithm(metadata.getSSECustomerAlgorithm());
        result.setSSECustomerKeyMd5(metadata.getSSECustomerKeyMd5());
        result.setCrc64Ecma(metadata.getCrc64Ecma());
        return result;
    } catch (Throwable t) {
        throw Throwables.failure(t);
    }
}
Also used : CosClientException(com.qcloud.cos.exception.CosClientException) CosMetadataResponseHandler(com.qcloud.cos.internal.CosMetadataResponseHandler)

Example 23 with CosClientException

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

the class COSClient method setBucketRefererConfiguration.

@Override
public void setBucketRefererConfiguration(SetBucketRefererConfigurationRequest setBucketRefererConfigurationRequest) throws CosClientException, CosServiceException {
    rejectNull(setBucketRefererConfigurationRequest, "The request object parameter setBucketRefererConfigurationRequest must be specified.");
    String bucketName = setBucketRefererConfigurationRequest.getBucketName();
    BucketRefererConfiguration configuration = setBucketRefererConfigurationRequest.getConfiguration();
    rejectNull(bucketName, "The bucket name parameter must be specified when setting a bucket's referer configuration");
    rejectNull(configuration, "The bucket domain configuration parameter must be specified when setting a bucket's referer configuration");
    CosHttpRequest<SetBucketRefererConfigurationRequest> request = createRequest(bucketName, null, setBucketRefererConfigurationRequest, HttpMethodName.PUT);
    request.addParameter("referer", null);
    request.addHeader("Content-Type", "application/xml");
    byte[] bytes = new BucketConfigurationXmlFactory().convertToXmlByteArray(configuration);
    request.setContent(new ByteArrayInputStream(bytes));
    try {
        byte[] md5 = Md5Utils.computeMD5Hash(bytes);
        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 24 with CosClientException

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

the class UploadMonitor method call.

@Override
public UploadResult call() throws Exception {
    try {
        UploadResult result = multipartUploadCallable.call();
        /**
         * If the result is null, it is a mutli part parellel upload. So, an new task is
         * submitted for initiating a complete multi part upload request.
         */
        if (result == null) {
            futures.addAll(multipartUploadCallable.getFutures());
            futureReference.set(threadPool.submit(new CompleteMultipartUpload(multipartUploadCallable.getMultipartUploadId(), cos, origReq, futures, multipartUploadCallable.getETags(), listener, this)));
            /**
             * if the logic get here. the upload part task has been summited. if it failed, we
             * won't can abort, so you can call save the PersistableUpload.
             */
            PersistableUpload persistableUploadInfo = this.multipartUploadCallable.getPersistableUpload();
            if (persistableUploadInfo != null) {
                this.transfer.setPersistableUploadInfo(persistableUploadInfo);
                this.transfer.setResumeableMultipartUploadAfterFailed(true);
            }
        } else {
            uploadComplete();
        }
        return result;
    } catch (CancellationException e) {
        transfer.setState(TransferState.Canceled);
        publishProgress(listener, ProgressEventType.TRANSFER_CANCELED_EVENT);
        throw new CosClientException("Upload canceled");
    } catch (Exception e) {
        uploadFailed();
        throw e;
    }
}
Also used : CancellationException(java.util.concurrent.CancellationException) CosClientException(com.qcloud.cos.exception.CosClientException) UploadResult(com.qcloud.cos.model.UploadResult) CosClientException(com.qcloud.cos.exception.CosClientException) CancellationException(java.util.concurrent.CancellationException)

Example 25 with CosClientException

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

the class BatchDeleteTest method batchDeletePartExistFileForVersionSuspended.

@Test
public void batchDeletePartExistFileForVersionSuspended() throws IOException, InterruptedException {
    if (!judgeUserInfoValid()) {
        return;
    }
    BucketVersioningConfiguration bucketVersioningEnabled = new BucketVersioningConfiguration(BucketVersioningConfiguration.SUSPENDED);
    cosclient.setBucketVersioningConfiguration(new SetBucketVersioningConfigurationRequest(bucket, bucketVersioningEnabled));
    Thread.sleep(5000L);
    DeleteObjectsRequest deleteObjectsRequest = new DeleteObjectsRequest(bucket);
    ArrayList<KeyVersion> keyList = new ArrayList<>();
    long deleteFileCount = 5;
    for (long fileIndex = 0; fileIndex < deleteFileCount; ++fileIndex) {
        File localFile = buildTestFile(fileIndex * 1024);
        String key = "ut/" + localFile.getName();
        PutObjectResult putObjectResult = putObjectFromLocalFile(localFile, key);
        keyList.add(new KeyVersion(key, "null"));
    }
    keyList.add(new KeyVersion("ut/not_exist_key.txt", "null"));
    deleteObjectsRequest.setKeys(keyList);
    try {
        DeleteObjectsResult deleteObjectsResult = cosclient.deleteObjects(deleteObjectsRequest);
        List<DeletedObject> deleteObjectResultArray = deleteObjectsResult.getDeletedObjects();
    } catch (MultiObjectDeleteException mde) {
        List<DeletedObject> deleteObjects = mde.getDeletedObjects();
        List<DeleteError> deleteErrors = mde.getErrors();
    } catch (CosServiceException e) {
        e.printStackTrace();
    } catch (CosClientException e) {
        e.printStackTrace();
    }
}
Also used : PutObjectResult(com.qcloud.cos.model.PutObjectResult) KeyVersion(com.qcloud.cos.model.DeleteObjectsRequest.KeyVersion) CosClientException(com.qcloud.cos.exception.CosClientException) ArrayList(java.util.ArrayList) DeleteObjectsResult(com.qcloud.cos.model.DeleteObjectsResult) DeleteObjectsRequest(com.qcloud.cos.model.DeleteObjectsRequest) CosServiceException(com.qcloud.cos.exception.CosServiceException) MultiObjectDeleteException(com.qcloud.cos.exception.MultiObjectDeleteException) SetBucketVersioningConfigurationRequest(com.qcloud.cos.model.SetBucketVersioningConfigurationRequest) BucketVersioningConfiguration(com.qcloud.cos.model.BucketVersioningConfiguration) ArrayList(java.util.ArrayList) List(java.util.List) File(java.io.File) DeletedObject(com.qcloud.cos.model.DeleteObjectsResult.DeletedObject) Test(org.junit.Test)

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