Search in sources :

Example 31 with PutObjectRequest

use of com.qcloud.cos.model.PutObjectRequest in project jeesuite-libs by vakinge.

the class QcloudProvider method upload.

@Override
public CUploadResult upload(CUploadObject object) {
    PutObjectRequest request;
    String fileKey = object.getFileKey();
    String bucketName = buildBucketName(object.getBucketName());
    if (object.getFile() != null) {
        request = new PutObjectRequest(bucketName, fileKey, object.getFile());
    } else if (object.getBytes() != null) {
        ByteArrayInputStream inputStream = new ByteArrayInputStream(object.getBytes());
        ObjectMetadata objectMetadata = new ObjectMetadata();
        objectMetadata.setContentLength(object.getFileSize());
        request = new PutObjectRequest(bucketName, fileKey, inputStream, objectMetadata);
    } else if (object.getInputStream() != null) {
        ObjectMetadata objectMetadata = new ObjectMetadata();
        objectMetadata.setContentLength(object.getFileSize());
        request = new PutObjectRequest(bucketName, fileKey, object.getInputStream(), objectMetadata);
    } else {
        throw new IllegalArgumentException("upload object is NULL");
    }
    try {
        if (object.getFileSize() > conf.getMaxAllowdSingleFileSize()) {
            Upload upload = transferManager.upload(request);
            com.qcloud.cos.model.UploadResult result = upload.waitForUploadResult();
            return new CUploadResult(fileKey, getFullPath(object.getBucketName(), fileKey), result.getCrc64Ecma());
        } else {
            PutObjectResult result = cosclient.putObject(request);
            return new CUploadResult(fileKey, getFullPath(object.getBucketName(), fileKey), result.getContentMd5());
        }
    } catch (Exception e) {
        e.printStackTrace();
        throw new JeesuiteBaseException(500, buildMessage(bucketName, e));
    }
}
Also used : PutObjectResult(com.qcloud.cos.model.PutObjectResult) Upload(com.qcloud.cos.transfer.Upload) CosServiceException(com.qcloud.cos.exception.CosServiceException) IOException(java.io.IOException) JeesuiteBaseException(com.jeesuite.common.JeesuiteBaseException) CUploadResult(com.jeesuite.cos.CUploadResult) JeesuiteBaseException(com.jeesuite.common.JeesuiteBaseException) ByteArrayInputStream(java.io.ByteArrayInputStream) ObjectMetadata(com.qcloud.cos.model.ObjectMetadata) CObjectMetadata(com.jeesuite.cos.CObjectMetadata) PutObjectRequest(com.qcloud.cos.model.PutObjectRequest)

Example 32 with PutObjectRequest

use of com.qcloud.cos.model.PutObjectRequest in project litemall by linlinjava.

the class TencentStorage method store.

@Override
public void store(InputStream inputStream, long contentLength, String contentType, String keyName) {
    try {
        // 简单文件上传, 最大支持 5 GB, 适用于小文件上传, 建议 20M以下的文件使用该接口
        ObjectMetadata objectMetadata = new ObjectMetadata();
        objectMetadata.setContentLength(contentLength);
        objectMetadata.setContentType(contentType);
        // 对象键(Key)是对象在存储桶中的唯一标识。例如,在对象的访问域名 `bucket1-1250000000.cos.ap-guangzhou.myqcloud.com/doc1/pic1.jpg`
        // 中,对象键为 doc1/pic1.jpg, 详情参考 [对象键](https://cloud.tencent.com/document/product/436/13324)
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, keyName, inputStream, objectMetadata);
        getCOSClient().putObject(putObjectRequest);
    } catch (Exception ex) {
        logger.error(ex.getMessage(), ex);
    }
}
Also used : ObjectMetadata(com.qcloud.cos.model.ObjectMetadata) PutObjectRequest(com.qcloud.cos.model.PutObjectRequest) MalformedURLException(java.net.MalformedURLException)

Example 33 with PutObjectRequest

use of com.qcloud.cos.model.PutObjectRequest in project hadoop-cos by tencentyun.

the class CosNativeFileSystemStore method callCOSClientWithRetry.

// posix bucket mkdir if the middle part exist will return the 500 error,
// and the rename if the dst exist will return the 500 status too,
// which make the related 5** retry useless. mo improve the resp info to filter.
private <X> Object callCOSClientWithRetry(X request) throws CosServiceException, IOException {
    String sdkMethod = "";
    int retryIndex = 1;
    int l5ErrorCodeRetryIndex = 1;
    while (true) {
        try {
            if (request instanceof PutObjectRequest) {
                sdkMethod = "putObject";
                if (((PutObjectRequest) request).getInputStream().markSupported()) {
                    ((PutObjectRequest) request).getInputStream().mark((int) ((PutObjectRequest) request).getMetadata().getContentLength());
                }
                return this.cosClient.putObject((PutObjectRequest) request);
            } else if (request instanceof UploadPartRequest) {
                sdkMethod = "uploadPart";
                if (((UploadPartRequest) request).getInputStream().markSupported()) {
                    ((UploadPartRequest) request).getInputStream().mark((int) ((UploadPartRequest) request).getPartSize());
                }
                return this.cosClient.uploadPart((UploadPartRequest) request);
            } else if (request instanceof CopyPartRequest) {
                sdkMethod = "copyPartRequest";
                return this.cosClient.copyPart((CopyPartRequest) request);
            } else if (request instanceof HeadBucketRequest) {
                // use for checking bucket type
                sdkMethod = "headBucket";
                return this.cosClient.headBucket((HeadBucketRequest) request);
            } else if (request instanceof RenameRequest) {
                sdkMethod = "rename";
                this.cosClient.rename((RenameRequest) request);
                return new Object();
            } else if (request instanceof GetObjectMetadataRequest) {
                sdkMethod = "queryObjectMeta";
                return this.cosClient.getObjectMetadata((GetObjectMetadataRequest) request);
            } else if (request instanceof DeleteObjectRequest) {
                sdkMethod = "deleteObject";
                this.cosClient.deleteObject((DeleteObjectRequest) request);
                return new Object();
            } else if (request instanceof CopyObjectRequest) {
                sdkMethod = "copyFile";
                return this.cosClient.copyObject((CopyObjectRequest) request);
            } else if (request instanceof GetObjectRequest) {
                sdkMethod = "getObject";
                return this.cosClient.getObject((GetObjectRequest) request);
            } else if (request instanceof ListObjectsRequest) {
                sdkMethod = "listObjects";
                return this.cosClient.listObjects((ListObjectsRequest) request);
            } else if (request instanceof InitiateMultipartUploadRequest) {
                sdkMethod = "initiateMultipartUpload";
                return this.cosClient.initiateMultipartUpload((InitiateMultipartUploadRequest) request);
            } else if (request instanceof CompleteMultipartUploadRequest) {
                sdkMethod = "completeMultipartUpload";
                return this.cosClient.completeMultipartUpload((CompleteMultipartUploadRequest) request);
            } else if (request instanceof AbortMultipartUploadRequest) {
                sdkMethod = "abortMultipartUpload";
                this.cosClient.abortMultipartUpload((AbortMultipartUploadRequest) request);
                return new Object();
            } else {
                throw new IOException("no such method");
            }
        } catch (ResponseNotCompleteException nce) {
            if (this.completeMPUCheckEnabled && request instanceof CompleteMultipartUploadRequest) {
                String key = ((CompleteMultipartUploadRequest) request).getKey();
                FileMetadata fileMetadata = this.queryObjectMetadata(key);
                if (null == fileMetadata) {
                    // if file not exist must throw the exception.
                    handleException(nce, key);
                }
                LOG.warn("Complete mpu resp not complete key [{}]", key);
                // todo: some other double check after cgi unified the ctime of mpu.
                return new CompleteMultipartUploadResult();
            } else {
                throw new IOException(nce);
            }
        } catch (CosServiceException cse) {
            String errMsg = String.format("all cos sdk failed, retryIndex: [%d / %d], " + "call method: %s, exception: %s", retryIndex, this.maxRetryTimes, sdkMethod, cse);
            int statusCode = cse.getStatusCode();
            String errorCode = cse.getErrorCode();
            LOG.debug("fail to retry statusCode {}, errorCode {}", statusCode, errorCode);
            // 对5xx错误进行重试
            if (request instanceof CopyObjectRequest && hasErrorCode(statusCode, errorCode)) {
                if (retryIndex <= this.maxRetryTimes) {
                    LOG.info(errMsg, cse);
                    ++retryIndex;
                } else {
                    LOG.error(errMsg, cse);
                    throw new IOException(errMsg);
                }
            } else if (request instanceof CompleteMultipartUploadRequest && hasErrorCode(statusCode, errorCode)) {
                // complete mpu error code might be in body when status code is 200
                // double check to head object only works in big data job case which key is not same.
                String key = ((CompleteMultipartUploadRequest) request).getKey();
                FileMetadata fileMetadata = this.queryObjectMetadata(key);
                if (null != fileMetadata) {
                    // if file exist direct return.
                    LOG.info("complete mpu error in body, error code {}, but key {} already exist, length {}", errorCode, key, fileMetadata.getLength());
                    return new CompleteMultipartUploadResult();
                }
                // here same like the copy request not setting the interval sleep for now
                if (retryIndex <= this.maxRetryTimes) {
                    LOG.info(errMsg, cse);
                    ++retryIndex;
                } else {
                    LOG.error(errMsg, cse);
                    throw new IOException(errMsg);
                }
            } else if (statusCode / 100 == 5) {
                if (retryIndex <= this.maxRetryTimes) {
                    if (statusCode == 503) {
                        if (useL5Id) {
                            if (l5ErrorCodeRetryIndex >= this.l5UpdateMaxRetryTimes) {
                                // L5上报,进行重试
                                l5EndpointResolver.updateRouteResult(-1);
                                l5ErrorCodeRetryIndex = 1;
                            } else {
                                l5ErrorCodeRetryIndex = l5ErrorCodeRetryIndex + 1;
                            }
                        }
                    }
                    LOG.info(errMsg, cse);
                    long sleepLeast = retryIndex * 300L;
                    long sleepBound = retryIndex * 500L;
                    try {
                        if (request instanceof PutObjectRequest) {
                            LOG.info("Try to reset the put object request input stream.");
                            if (((PutObjectRequest) request).getInputStream().markSupported()) {
                                ((PutObjectRequest) request).getInputStream().reset();
                            } else {
                                LOG.error("The put object request input stream can not be reset, so it can not be" + " retried.");
                                throw cse;
                            }
                        }
                        if (request instanceof UploadPartRequest) {
                            LOG.info("Try to reset the upload part request input stream.");
                            if (((UploadPartRequest) request).getInputStream().markSupported()) {
                                ((UploadPartRequest) request).getInputStream().reset();
                            } else {
                                LOG.error("The upload part request input stream can not be reset, so it can not " + "be retried" + ".");
                                throw cse;
                            }
                        }
                        // if direct retry may occur 403 not found the upload id.
                        if (request instanceof CompleteMultipartUploadRequest && statusCode == 503) {
                            String key = ((CompleteMultipartUploadRequest) request).getKey();
                            FileMetadata fileMetadata = this.queryObjectMetadata(key);
                            if (null != fileMetadata) {
                                // if file exist direct return.
                                LOG.info("complete mpu error might access time out, " + "but key {} already exist, length {}", key, fileMetadata.getLength());
                                return new CompleteMultipartUploadResult();
                            }
                        }
                        Thread.sleep(ThreadLocalRandom.current().nextLong(sleepLeast, sleepBound));
                        ++retryIndex;
                    } catch (InterruptedException e) {
                        throw new IOException(e.toString());
                    }
                } else {
                    LOG.error(errMsg, cse);
                    throw new IOException(errMsg);
                }
            } else {
                throw cse;
            }
        } catch (Exception e) {
            throw new IOException(e);
        }
    }
}
Also used : HeadBucketRequest(com.qcloud.cos.model.HeadBucketRequest) ResponseNotCompleteException(com.qcloud.cos.exception.ResponseNotCompleteException) InitiateMultipartUploadRequest(com.qcloud.cos.model.InitiateMultipartUploadRequest) UploadPartRequest(com.qcloud.cos.model.UploadPartRequest) AbortMultipartUploadRequest(com.qcloud.cos.model.AbortMultipartUploadRequest) IOException(java.io.IOException) CompleteMultipartUploadResult(com.qcloud.cos.model.CompleteMultipartUploadResult) ResponseNotCompleteException(com.qcloud.cos.exception.ResponseNotCompleteException) CosServiceException(com.qcloud.cos.exception.CosServiceException) CosClientException(com.qcloud.cos.exception.CosClientException) IOException(java.io.IOException) DeleteObjectRequest(com.qcloud.cos.model.DeleteObjectRequest) CopyPartRequest(com.qcloud.cos.model.CopyPartRequest) ListObjectsRequest(com.qcloud.cos.model.ListObjectsRequest) CopyObjectRequest(com.qcloud.cos.model.CopyObjectRequest) GetObjectMetadataRequest(com.qcloud.cos.model.GetObjectMetadataRequest) CosServiceException(com.qcloud.cos.exception.CosServiceException) RenameRequest(com.qcloud.cos.model.RenameRequest) COSObject(com.qcloud.cos.model.COSObject) GetObjectRequest(com.qcloud.cos.model.GetObjectRequest) PutObjectRequest(com.qcloud.cos.model.PutObjectRequest) CompleteMultipartUploadRequest(com.qcloud.cos.model.CompleteMultipartUploadRequest)

Example 34 with PutObjectRequest

use of com.qcloud.cos.model.PutObjectRequest in project hadoop-cos by tencentyun.

the class CosNativeFileSystemStore method storeFileWithRetry.

private void storeFileWithRetry(String key, InputStream inputStream, byte[] md5Hash, long length) throws IOException {
    try {
        ObjectMetadata objectMetadata = new ObjectMetadata();
        if (null != md5Hash) {
            objectMetadata.setContentMD5(Base64.encodeAsString(md5Hash));
        }
        objectMetadata.setContentLength(length);
        if (crc32cEnabled) {
            objectMetadata.setHeader(Constants.CRC32C_REQ_HEADER, Constants.CRC32C_REQ_HEADER_VAL);
        }
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, inputStream, objectMetadata);
        if (null != this.storageClass) {
            putObjectRequest.setStorageClass(this.storageClass);
        }
        if (this.trafficLimit >= 0) {
            putObjectRequest.setTrafficLimit(this.trafficLimit);
        }
        this.setEncryptionMetadata(putObjectRequest, objectMetadata);
        PutObjectResult putObjectResult = (PutObjectResult) callCOSClientWithRetry(putObjectRequest);
        LOG.debug("Store the file successfully. cos key: {}, ETag: {}.", key, putObjectResult.getETag());
    } catch (CosServiceException cse) {
        // 避免并发上传的问题
        int statusCode = cse.getStatusCode();
        if (statusCode == 409) {
            // Check一下这个文件是否已经存在
            FileMetadata fileMetadata = this.queryObjectMetadata(key);
            if (null == fileMetadata) {
                // 如果文件不存在,则需要抛出异常
                handleException(cse, key);
            }
            LOG.warn("Upload the cos key [{}] concurrently", key);
        } else {
            // 其他错误都要抛出来
            handleException(cse, key);
        }
    } catch (Exception e) {
        String errMsg = String.format("Store the file failed, cos key: %s, exception: %s.", key, e);
        handleException(new Exception(errMsg), key);
    }
}
Also used : CosServiceException(com.qcloud.cos.exception.CosServiceException) PutObjectResult(com.qcloud.cos.model.PutObjectResult) ObjectMetadata(com.qcloud.cos.model.ObjectMetadata) PutObjectRequest(com.qcloud.cos.model.PutObjectRequest) ResponseNotCompleteException(com.qcloud.cos.exception.ResponseNotCompleteException) CosServiceException(com.qcloud.cos.exception.CosServiceException) CosClientException(com.qcloud.cos.exception.CosClientException) IOException(java.io.IOException)

Example 35 with PutObjectRequest

use of com.qcloud.cos.model.PutObjectRequest in project cos-java-sdk-v5 by tencentyun.

the class RestoreObjectTest method restoreObject.

@Test
public void restoreObject() {
    InputStream input = new ByteArrayInputStream(new byte[10]);
    ObjectMetadata objectMetadata = new ObjectMetadata();
    objectMetadata.setContentLength(10);
    String key = "ut/aaa.txt";
    PutObjectRequest putObjectRequest = new PutObjectRequest(bucket, key, input, objectMetadata);
    putObjectRequest.setStorageClass(StorageClass.Archive);
    cosclient.putObject(putObjectRequest);
    RestoreObjectRequest restoreObjectRequest = new RestoreObjectRequest(bucket, key, 1);
    cosclient.restoreObject(restoreObjectRequest);
    cosclient.deleteObject(bucket, key);
}
Also used : ByteArrayInputStream(java.io.ByteArrayInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) RestoreObjectRequest(com.qcloud.cos.model.RestoreObjectRequest) ObjectMetadata(com.qcloud.cos.model.ObjectMetadata) PutObjectRequest(com.qcloud.cos.model.PutObjectRequest) Test(org.junit.Test)

Aggregations

PutObjectRequest (com.qcloud.cos.model.PutObjectRequest)45 File (java.io.File)30 PutObjectResult (com.qcloud.cos.model.PutObjectResult)25 CosServiceException (com.qcloud.cos.exception.CosServiceException)17 ObjectMetadata (com.qcloud.cos.model.ObjectMetadata)17 CosClientException (com.qcloud.cos.exception.CosClientException)15 COSClient (com.qcloud.cos.COSClient)13 ClientConfig (com.qcloud.cos.ClientConfig)13 Region (com.qcloud.cos.region.Region)13 BasicCOSCredentials (com.qcloud.cos.auth.BasicCOSCredentials)12 COSCredentials (com.qcloud.cos.auth.COSCredentials)12 Upload (com.qcloud.cos.transfer.Upload)12 GetObjectRequest (com.qcloud.cos.model.GetObjectRequest)10 UploadResult (com.qcloud.cos.model.UploadResult)10 ByteArrayInputStream (java.io.ByteArrayInputStream)8 LinkedList (java.util.LinkedList)8 Test (org.junit.Test)8 CIObject (com.qcloud.cos.model.ciModel.persistence.CIObject)7 CIUploadResult (com.qcloud.cos.model.ciModel.persistence.CIUploadResult)7 PicOperations (com.qcloud.cos.model.ciModel.persistence.PicOperations)7