Search in sources :

Example 31 with PutObjectResult

use of com.aliyun.oss.model.PutObjectResult in project spring-boot-quick by vector4wang.

the class OSSUnit method uploadObject2OSS.

/**
 * 向阿里云的OSS存储中存储文件  --file也可以用InputStream替代
 * @param client OSS客户端
 * @param file 上传文件
 * @param bucketName bucket名称
 * @param diskName 上传文件的目录  --bucket下文件的路径
 * @return String 唯一MD5数字签名
 */
public static final String uploadObject2OSS(OSSClient client, File file, String bucketName, String diskName) {
    String resultStr = null;
    try {
        InputStream is = new FileInputStream(file);
        String fileName = file.getName();
        Long fileSize = file.length();
        // 创建上传Object的Metadata
        ObjectMetadata metadata = new ObjectMetadata();
        metadata.setContentLength(is.available());
        metadata.setCacheControl("no-cache");
        metadata.setHeader("Pragma", "no-cache");
        metadata.setContentEncoding("utf-8");
        metadata.setContentType(getContentType(fileName));
        metadata.setContentDisposition("filename/filesize=" + fileName + "/" + fileSize + "Byte.");
        // 上传文件
        PutObjectResult putResult = client.putObject(bucketName, diskName + fileName, is, metadata);
        // 解析结果
        resultStr = putResult.getETag();
    } catch (Exception e) {
        LOG.error("上传阿里云OSS服务器异常." + e.getMessage(), e);
    }
    return resultStr;
}
Also used : PutObjectResult(com.aliyun.oss.model.PutObjectResult) ObjectMetadata(com.aliyun.oss.model.ObjectMetadata)

Example 32 with PutObjectResult

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

the class UrlSignatureTest method testPutObject.

@Ignore
public void testPutObject() {
    OSS client = new OSSClientBuilder().build(endpoint, accessId, accessKey);
    try {
        Date expiration = DateUtil.parseRfc822Date("Thu, 19 Mar 2015 18:00:00 GMT");
        GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(bucketName, key, HttpMethod.PUT);
        request.setExpiration(expiration);
        request.setContentType("application/octet-stream");
        request.addUserMetadata("author", "aliy");
        URL signedUrl = client.generatePresignedUrl(request);
        System.out.println("signed url for putObject: " + signedUrl);
        File f = new File(filePath);
        FileInputStream fin = new FileInputStream(f);
        Map<String, String> customHeaders = new HashMap<String, String>();
        customHeaders.put("Content-Type", "application/octet-stream");
        customHeaders.put("x-oss-meta-author", "aliy");
        PutObjectResult result = client.putObject(signedUrl, fin, f.length(), customHeaders);
        fin = new FileInputStream(f);
        byte[] binaryData = IOUtils.readStreamAsByteArray(fin);
        String expectedETag = BinaryUtil.encodeMD5(binaryData);
        String actualETag = result.getETag();
        Assert.assertEquals(expectedETag, actualETag);
    } catch (Exception e) {
        Assert.fail(e.getMessage());
    }
}
Also used : HashMap(java.util.HashMap) PutObjectResult(com.aliyun.oss.model.PutObjectResult) OSS(com.aliyun.oss.OSS) Date(java.util.Date) URL(java.net.URL) FileInputStream(java.io.FileInputStream) IOException(java.io.IOException) GeneratePresignedUrlRequest(com.aliyun.oss.model.GeneratePresignedUrlRequest) File(java.io.File) OSSClientBuilder(com.aliyun.oss.OSSClientBuilder) Ignore(org.junit.Ignore)

Example 33 with PutObjectResult

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

the class UploadPartCopyTest method testUnormalUploadPartCopy.

@Test
public void testUnormalUploadPartCopy() {
    final String sourceBucket = super.bucketName + "-" + "unormal-upload-part-copy-source";
    final String targetBucket = super.bucketName + "-" + "unormal-upload-part-copy-target";
    final String sourceKey = "unormal-upload-part-copy-object-source";
    final String targetKey = "unormal-upload-part-copy-object-target";
    // Set length of parts less than minimum limit(100KB)
    // 64KB
    final long partSize = 64 * 1024;
    try {
        ossClient.createBucket(sourceBucket);
        ossClient.createBucket(targetBucket);
        waitForCacheExpiration(5);
        // Put object into source bucket
        String eTag = null;
        try {
            InputStream instream = genFixedLengthInputStream(partSize);
            PutObjectResult result = ossClient.putObject(sourceBucket, sourceKey, instream, null);
            eTag = result.getETag();
        } catch (Exception e) {
            Assert.fail(e.getMessage());
        }
        // Claim upload id for target bucket
        String uploadId = claimUploadId(ossClient, targetBucket, targetKey);
        // Copy part under non-existent source bucket
        final String nonexistentSourceBucket = "nonexistent-source-bucket";
        final int partNumber = 1;
        try {
            UploadPartCopyRequest uploadPartCopyRequest = new UploadPartCopyRequest(nonexistentSourceBucket, sourceKey, targetBucket, targetKey);
            uploadPartCopyRequest.setPartNumber(partNumber);
            uploadPartCopyRequest.setUploadId(uploadId);
            ossClient.uploadPartCopy(uploadPartCopyRequest);
            Assert.fail("Upload part copy should not be successfuly");
        } catch (OSSException e) {
            Assert.assertEquals(OSSErrorCode.NO_SUCH_BUCKET, e.getErrorCode());
            Assert.assertTrue(e.getMessage().startsWith(NO_SUCH_BUCKET_ERR));
        }
        // Copy part from non-existent source key
        final String nonexistentSourceKey = "nonexistent-source-key";
        try {
            UploadPartCopyRequest uploadPartCopyRequest = new UploadPartCopyRequest(sourceBucket, nonexistentSourceKey, targetBucket, targetKey);
            uploadPartCopyRequest.setPartNumber(partNumber);
            uploadPartCopyRequest.setUploadId(uploadId);
            ossClient.uploadPartCopy(uploadPartCopyRequest);
            Assert.fail("Upload part copy should not be successfuly");
        } catch (OSSException e) {
            Assert.assertEquals(OSSErrorCode.NO_SUCH_KEY, e.getErrorCode());
            Assert.assertTrue(e.getMessage().startsWith(NO_SUCH_KEY_ERR));
        }
        // Copy part to non-existent target bucket
        final String nonexistentTargetBucket = "nonexistent-target-key";
        try {
            UploadPartCopyRequest uploadPartCopyRequest = new UploadPartCopyRequest(sourceBucket, sourceKey, nonexistentTargetBucket, targetKey);
            uploadPartCopyRequest.setPartNumber(partNumber);
            uploadPartCopyRequest.setUploadId(uploadId);
            ossClient.uploadPartCopy(uploadPartCopyRequest);
            Assert.fail("Upload part copy should not be successfuly");
        } catch (OSSException e) {
            Assert.assertEquals(OSSErrorCode.NO_SUCH_BUCKET, e.getErrorCode());
            Assert.assertTrue(e.getMessage().startsWith(NO_SUCH_BUCKET_ERR));
        }
        // Upload part copy
        List<PartETag> partETags = new ArrayList<PartETag>();
        try {
            UploadPartCopyRequest uploadPartCopyRequest = new UploadPartCopyRequest(sourceBucket, sourceKey, targetBucket, targetKey);
            uploadPartCopyRequest.setPartNumber(partNumber);
            uploadPartCopyRequest.setUploadId(uploadId);
            UploadPartCopyResult uploadPartCopyResult = ossClient.uploadPartCopy(uploadPartCopyRequest);
            partETags.add(uploadPartCopyResult.getPartETag());
            Assert.assertEquals(eTag, uploadPartCopyResult.getETag());
            Assert.assertEquals(partNumber, uploadPartCopyResult.getPartNumber());
            uploadPartCopyRequest = new UploadPartCopyRequest(sourceBucket, sourceKey, targetBucket, targetKey);
            uploadPartCopyRequest.setPartNumber(partNumber + 1);
            uploadPartCopyRequest.setUploadId(uploadId);
            uploadPartCopyResult = ossClient.uploadPartCopy(uploadPartCopyRequest);
            partETags.add(uploadPartCopyResult.getPartETag());
            Assert.assertEquals(eTag, uploadPartCopyResult.getETag());
            Assert.assertEquals(partNumber + 1, uploadPartCopyResult.getPartNumber());
            ListPartsRequest listPartsRequest = new ListPartsRequest(targetBucket, targetKey, uploadId);
            PartListing partListing = ossClient.listParts(listPartsRequest);
            Assert.assertEquals(2, partListing.getParts().size());
            Assert.assertEquals(targetBucket, partListing.getBucketName());
            Assert.assertEquals(targetKey, partListing.getKey());
            Assert.assertEquals(uploadId, partListing.getUploadId());
            Assert.assertEquals(LIST_PART_MAX_RETURNS, partListing.getMaxParts().intValue());
            Assert.assertNotNull(partListing.getNextPartNumberMarker());
            Assert.assertFalse(partListing.isTruncated());
        } catch (Exception e) {
            Assert.fail(e.getMessage());
        }
        // Try to complete multipart upload with all uploaded parts
        try {
            CompleteMultipartUploadRequest completeMultipartUploadRequest = new CompleteMultipartUploadRequest(targetBucket, targetKey, uploadId, partETags);
            ossClient.completeMultipartUpload(completeMultipartUploadRequest);
            Assert.fail("Upload part copy should not be successfuly");
        } catch (OSSException e) {
            Assert.assertEquals(OSSErrorCode.ENTITY_TOO_SMALL, e.getErrorCode());
            Assert.assertTrue(e.getMessage().startsWith(ENTITY_TOO_SMALL_ERR));
        }
        // Abort the incompleted multipart upload
        try {
            AbortMultipartUploadRequest abortMultipartUploadRequest = new AbortMultipartUploadRequest(targetBucket, targetKey, uploadId);
            ossClient.abortMultipartUpload(abortMultipartUploadRequest);
        } catch (Exception e) {
            Assert.fail(e.getMessage());
        }
    } catch (Exception e) {
        Assert.fail(e.getMessage());
    } finally {
        deleteBucketWithObjects(ossClient, sourceBucket);
        deleteBucketWithObjects(ossClient, targetBucket);
    }
}
Also used : PutObjectResult(com.aliyun.oss.model.PutObjectResult) TestUtils.genFixedLengthInputStream(com.aliyun.oss.integrationtests.TestUtils.genFixedLengthInputStream) InputStream(java.io.InputStream) ArrayList(java.util.ArrayList) OSSException(com.aliyun.oss.OSSException) AbortMultipartUploadRequest(com.aliyun.oss.model.AbortMultipartUploadRequest) OSSException(com.aliyun.oss.OSSException) PartETag(com.aliyun.oss.model.PartETag) PartListing(com.aliyun.oss.model.PartListing) ListPartsRequest(com.aliyun.oss.model.ListPartsRequest) UploadPartCopyResult(com.aliyun.oss.model.UploadPartCopyResult) UploadPartCopyRequest(com.aliyun.oss.model.UploadPartCopyRequest) CompleteMultipartUploadRequest(com.aliyun.oss.model.CompleteMultipartUploadRequest) Test(org.junit.Test)

Example 34 with PutObjectResult

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

the class UploadPartCopyTest method testNormalUploadPartCopy.

@Test
public void testNormalUploadPartCopy() {
    final String sourceBucket = super.bucketName + "-" + "normal-upload-part-copy-source";
    final String targetBucket = super.bucketName + "-" + "normal-upload-part-copy-target";
    final String sourceKey = "normal-upload-part-copy-object-source";
    final String targetKey = "normal-upload-part-copy-object-target";
    // 128KB
    final long partSize = 128 * 1024;
    try {
        ossClient.createBucket(sourceBucket);
        ossClient.createBucket(targetBucket);
        waitForCacheExpiration(5);
        // Put object into source bucket
        String eTag = null;
        try {
            InputStream instream = genFixedLengthInputStream(partSize);
            PutObjectResult result = ossClient.putObject(sourceBucket, sourceKey, instream, null);
            eTag = result.getETag();
        } catch (Exception e) {
            Assert.fail(e.getMessage());
        }
        // Claim upload id for target bucket
        String uploadId = claimUploadId(ossClient, targetBucket, targetKey);
        // Upload part copy
        final int partNumber = 1;
        List<PartETag> partETags = new ArrayList<PartETag>();
        UploadPartCopyRequest uploadPartCopyRequest = new UploadPartCopyRequest(sourceBucket, sourceKey, targetBucket, targetKey);
        uploadPartCopyRequest.setPartNumber(partNumber);
        uploadPartCopyRequest.setUploadId(uploadId);
        UploadPartCopyResult uploadPartCopyResult = ossClient.uploadPartCopy(uploadPartCopyRequest);
        partETags.add(uploadPartCopyResult.getPartETag());
        Assert.assertEquals(eTag, uploadPartCopyResult.getETag());
        Assert.assertEquals(partNumber, uploadPartCopyResult.getPartNumber());
        Assert.assertEquals(uploadPartCopyResult.getRequestId().length(), REQUEST_ID_LEN);
        ListPartsRequest listPartsRequest = new ListPartsRequest(targetBucket, targetKey, uploadId);
        PartListing partListing = ossClient.listParts(listPartsRequest);
        Assert.assertEquals(1, partListing.getParts().size());
        Assert.assertEquals(targetBucket, partListing.getBucketName());
        Assert.assertEquals(targetKey, partListing.getKey());
        Assert.assertEquals(uploadId, partListing.getUploadId());
        Assert.assertEquals(LIST_PART_MAX_RETURNS, partListing.getMaxParts().intValue());
        Assert.assertNotNull(partListing.getNextPartNumberMarker());
        Assert.assertFalse(partListing.isTruncated());
        Assert.assertEquals(partListing.getRequestId().length(), REQUEST_ID_LEN);
        // Complete multipart upload
        CompleteMultipartUploadRequest completeMultipartUploadRequest = new CompleteMultipartUploadRequest(targetBucket, targetKey, uploadId, partETags);
        CompleteMultipartUploadResult completeMultipartUploadResult = ossClient.completeMultipartUpload(completeMultipartUploadRequest);
        Assert.assertEquals(composeLocation(ossClient, OSS_TEST_ENDPOINT, targetBucket, targetKey), completeMultipartUploadResult.getLocation());
        Assert.assertEquals(targetBucket, completeMultipartUploadResult.getBucketName());
        Assert.assertEquals(targetKey, completeMultipartUploadResult.getKey());
        Assert.assertEquals(calcMultipartsETag(partETags), completeMultipartUploadResult.getETag());
        Assert.assertEquals(completeMultipartUploadResult.getRequestId().length(), REQUEST_ID_LEN);
        // Get uploaded object
        OSSObject o = ossClient.getObject(targetBucket, targetKey);
        final long objectSize = 1 * partSize;
        Assert.assertEquals(objectSize, o.getObjectMetadata().getContentLength());
        Assert.assertEquals(calcMultipartsETag(partETags), o.getObjectMetadata().getETag());
        Assert.assertEquals(o.getRequestId().length(), REQUEST_ID_LEN);
    } catch (Exception e) {
        Assert.fail(e.getMessage());
    } finally {
        deleteBucketWithObjects(ossClient, sourceBucket);
        deleteBucketWithObjects(ossClient, targetBucket);
    }
}
Also used : OSSObject(com.aliyun.oss.model.OSSObject) PutObjectResult(com.aliyun.oss.model.PutObjectResult) TestUtils.genFixedLengthInputStream(com.aliyun.oss.integrationtests.TestUtils.genFixedLengthInputStream) InputStream(java.io.InputStream) ArrayList(java.util.ArrayList) CompleteMultipartUploadResult(com.aliyun.oss.model.CompleteMultipartUploadResult) OSSException(com.aliyun.oss.OSSException) PartETag(com.aliyun.oss.model.PartETag) PartListing(com.aliyun.oss.model.PartListing) ListPartsRequest(com.aliyun.oss.model.ListPartsRequest) UploadPartCopyResult(com.aliyun.oss.model.UploadPartCopyResult) UploadPartCopyRequest(com.aliyun.oss.model.UploadPartCopyRequest) CompleteMultipartUploadRequest(com.aliyun.oss.model.CompleteMultipartUploadRequest) Test(org.junit.Test)

Example 35 with PutObjectResult

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

the class ObjectEncryptionTest method testNormalObject.

private void testNormalObject(SSEAlgorithm algorithm, DataEncryptionAlgorithm dataEncryptionAlgorithm) throws Exception {
    for (int i = 0; i < ITERATIONS; ++i) {
        final String keyPrefix = "normal-file-encryption-";
        // 1KB
        final String filePath = genFixedLengthFile(i * 1024 * 100 + 1024);
        try {
            // 1. put
            ObjectMetadata metadata = new ObjectMetadata();
            if (algorithm != null) {
                metadata.setServerSideEncryption(algorithm.toString());
            }
            if (dataEncryptionAlgorithm != null) {
                metadata.setServerSideDataEncryption(dataEncryptionAlgorithm.toString());
            }
            PutObjectRequest request = new PutObjectRequest(bucketName, buildObjectKey(keyPrefix, i), new File(filePath), metadata);
            request.setProcess("");
            PutObjectResult result = ossClient.putObject(request);
            Map<String, String> headers = result.getResponse().getHeaders();
            Assert.assertEquals(algorithm != null, headers.containsKey(OSSHeaders.OSS_SERVER_SIDE_ENCRYPTION));
            if (algorithm != null) {
                Assert.assertEquals(headers.get(OSSHeaders.OSS_SERVER_SIDE_ENCRYPTION), algorithm.toString());
            }
            Assert.assertEquals(dataEncryptionAlgorithm != null, headers.containsKey(OSSHeaders.OSS_SERVER_SIDE_DATA_ENCRYPTION));
            if (dataEncryptionAlgorithm != null) {
                Assert.assertEquals(dataEncryptionAlgorithm.toString(), headers.get(OSSHeaders.OSS_SERVER_SIDE_DATA_ENCRYPTION));
            }
            // 2. get
            byte[] target = InputStream2ByteArray(filePath);
            checkObjectContent(target, buildObjectKey(keyPrefix, i), algorithm, dataEncryptionAlgorithm);
            // 3. copy without encryption
            copyObject(target, buildObjectKey(keyPrefix, i), buildObjectKey(keyPrefix + "copy-", i), null, null);
            // 4. copy with the same encryption
            copyObject(target, buildObjectKey(keyPrefix, i), buildObjectKey(keyPrefix + "copy-", i), algorithm, dataEncryptionAlgorithm);
            // 5. copy with different encryption
            if (dataEncryptionAlgorithm == null) {
                copyObject(target, buildObjectKey(keyPrefix, i), buildObjectKey(keyPrefix + "copy-", i), SSEAlgorithm.KMS, DataEncryptionAlgorithm.SM4);
            } else {
                copyObject(target, buildObjectKey(keyPrefix, i), buildObjectKey(keyPrefix + "copy-", i), SSEAlgorithm.KMS, null);
                copyObject(target, buildObjectKey(keyPrefix, i), buildObjectKey(keyPrefix + "copy-", i), SSEAlgorithm.SM4, null);
                copyObject(target, buildObjectKey(keyPrefix, i), buildObjectKey(keyPrefix + "copy-", i), SSEAlgorithm.AES256, null);
            }
        } catch (Exception ex) {
            Assert.fail(ex.getMessage());
        } finally {
            removeFile(filePath);
        }
    }
}
Also used : PutObjectResult(com.aliyun.oss.model.PutObjectResult) ObjectMetadata(com.aliyun.oss.model.ObjectMetadata) File(java.io.File) PutObjectRequest(com.aliyun.oss.model.PutObjectRequest)

Aggregations

PutObjectResult (com.aliyun.oss.model.PutObjectResult)56 Test (org.junit.Test)31 OSSException (com.aliyun.oss.OSSException)30 InputStream (java.io.InputStream)24 OSSObject (com.aliyun.oss.model.OSSObject)20 ObjectMetadata (com.aliyun.oss.model.ObjectMetadata)19 File (java.io.File)15 PutObjectRequest (com.aliyun.oss.model.PutObjectRequest)13 TestUtils.genFixedLengthInputStream (com.aliyun.oss.integrationtests.TestUtils.genFixedLengthInputStream)10 ByteArrayInputStream (java.io.ByteArrayInputStream)10 ArrayList (java.util.ArrayList)10 FileInputStream (java.io.FileInputStream)9 Callback (com.aliyun.oss.model.Callback)8 GetObjectRequest (com.aliyun.oss.model.GetObjectRequest)7 Date (java.util.Date)7 CopyObjectResult (com.aliyun.oss.model.CopyObjectResult)6 IOException (java.io.IOException)6 Ignore (org.junit.Ignore)6 OSS (com.aliyun.oss.OSS)5 CompleteMultipartUploadRequest (com.aliyun.oss.model.CompleteMultipartUploadRequest)5