Search in sources :

Example 1 with PutObjectRequest

use of com.aliyun.oss.model.PutObjectRequest in project CBEC-B2B by A-Cubic.

the class OSSUtils method uploadOSSToInputStream.

public static void uploadOSSToInputStream(InputStream in, String filename) {
    OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
    try {
        if (!ossClient.doesBucketExist(bucketName)) {
            System.out.println("Creating bucket " + bucketName + "\n");
            ossClient.createBucket(bucketName);
            CreateBucketRequest createBucketRequest = new CreateBucketRequest(bucketName);
            createBucketRequest.setCannedACL(CannedAccessControlList.PublicRead);
            ossClient.createBucket(createBucketRequest);
        }
        ossClient.putObject(new PutObjectRequest(bucketName, key + "/" + filename, in));
    } catch (Exception e) {
        logger.error("上传oss失败,原因:" + e.getMessage());
    } finally {
        ossClient.shutdown();
    }
}
Also used : CreateBucketRequest(com.aliyun.oss.model.CreateBucketRequest) OSS(com.aliyun.oss.OSS) OSSClientBuilder(com.aliyun.oss.OSSClientBuilder) PutObjectRequest(com.aliyun.oss.model.PutObjectRequest)

Example 2 with PutObjectRequest

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

the class UploadPartCopySample method main.

public static void main(String[] args) throws IOException {
    /*
         * Constructs a client instance with your account for accessing OSS
         */
    client = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
    try {
        /*
             * Upload an object to your source bucket
             */
        System.out.println("Uploading a new object to OSS from a file\n");
        client.putObject(new PutObjectRequest(sourceBucketName, sourceKey, createSampleFile()));
        /*
             * Claim a new upload id for your target bucket
             */
        InitiateMultipartUploadRequest initiateMultipartUploadRequest = new InitiateMultipartUploadRequest(targetBucketName, targetKey);
        InitiateMultipartUploadResult initiateMultipartUploadResult = client.initiateMultipartUpload(initiateMultipartUploadRequest);
        String uploadId = initiateMultipartUploadResult.getUploadId();
        /*
             * Calculate how many parts to be divided
             */
        // 5MB
        final long partSize = 5 * 1024 * 1024L;
        ObjectMetadata metadata = client.getObjectMetadata(sourceBucketName, sourceKey);
        long objectSize = metadata.getContentLength();
        int partCount = (int) (objectSize / partSize);
        if (objectSize % partSize != 0) {
            partCount++;
        }
        if (partCount > 10000) {
            throw new RuntimeException("Total parts count should not exceed 10000");
        } else {
            System.out.println("Total parts count " + partCount + "\n");
        }
        /*
             * Upload multiparts by copy mode
             */
        System.out.println("Begin to upload multiparts by copy mode to OSS\n");
        List<PartETag> partETags = new ArrayList<PartETag>();
        for (int i = 0; i < partCount; i++) {
            long startPos = i * partSize;
            long curPartSize = (i + 1 == partCount) ? (objectSize - startPos) : partSize;
            ;
            UploadPartCopyRequest uploadPartCopyRequest = new UploadPartCopyRequest(sourceBucketName, sourceKey, targetBucketName, targetKey);
            uploadPartCopyRequest.setUploadId(uploadId);
            uploadPartCopyRequest.setPartSize(curPartSize);
            uploadPartCopyRequest.setBeginIndex(startPos);
            uploadPartCopyRequest.setPartNumber(i + 1);
            UploadPartCopyResult uploadPartCopyResult = client.uploadPartCopy(uploadPartCopyRequest);
            System.out.println("\tPart#" + uploadPartCopyResult.getPartNumber() + " done\n");
            partETags.add(uploadPartCopyResult.getPartETag());
        }
        /*
             * Complete to upload multiparts
             */
        System.out.println("Completing to upload multiparts\n");
        CompleteMultipartUploadRequest completeMultipartUploadRequest = new CompleteMultipartUploadRequest(targetBucketName, targetKey, uploadId, partETags);
        client.completeMultipartUpload(completeMultipartUploadRequest);
        /*
             * Fetch the object that newly created at the step below.
             */
        System.out.println("Fetching an object");
        client.getObject(new GetObjectRequest(targetBucketName, targetKey), new File(localFilePath));
    } catch (OSSException oe) {
        System.out.println("Caught an OSSException, which means your request made it to OSS, " + "but was rejected with an error response for some reason.");
        System.out.println("Error Message: " + oe.getErrorCode());
        System.out.println("Error Code:       " + oe.getErrorCode());
        System.out.println("Request ID:      " + oe.getRequestId());
        System.out.println("Host ID:           " + oe.getHostId());
    } catch (ClientException ce) {
        System.out.println("Caught an ClientException, which means the client encountered " + "a serious internal problem while trying to communicate with OSS, " + "such as not being able to access the network.");
        System.out.println("Error Message: " + ce.getMessage());
    } finally {
        /*
             * Do not forget to shut down the client finally to release all allocated resources.
             */
        client.shutdown();
    }
}
Also used : InitiateMultipartUploadResult(com.aliyun.oss.model.InitiateMultipartUploadResult) InitiateMultipartUploadRequest(com.aliyun.oss.model.InitiateMultipartUploadRequest) ArrayList(java.util.ArrayList) OSSException(com.aliyun.oss.OSSException) PartETag(com.aliyun.oss.model.PartETag) UploadPartCopyResult(com.aliyun.oss.model.UploadPartCopyResult) UploadPartCopyRequest(com.aliyun.oss.model.UploadPartCopyRequest) ClientException(com.aliyun.oss.ClientException) ObjectMetadata(com.aliyun.oss.model.ObjectMetadata) GetObjectRequest(com.aliyun.oss.model.GetObjectRequest) File(java.io.File) OSSClientBuilder(com.aliyun.oss.OSSClientBuilder) PutObjectRequest(com.aliyun.oss.model.PutObjectRequest) CompleteMultipartUploadRequest(com.aliyun.oss.model.CompleteMultipartUploadRequest)

Example 3 with PutObjectRequest

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

the class OSSClientRequestTest method testPutObjectRequest.

@SuppressWarnings("serial")
@Test
public void testPutObjectRequest() {
    String content = "中English混合的Content。\n" + "This is the 2nd line.";
    byte[] contentBuffer = null;
    try {
        contentBuffer = content.getBytes(OSSConstants.DEFAULT_CHARSET_NAME);
    } catch (UnsupportedEncodingException e) {
        fail(e.getMessage());
    }
    final ByteArrayInputStream input = new ByteArrayInputStream(contentBuffer);
    final ObjectMetadata metadata = new ObjectMetadata();
    metadata.setContentLength(contentBuffer.length);
    TestAction test1 = new TestAction() {

        public void run() throws Exception {
            objectOp.putObject(new PutObjectRequest(bucketName, objectKey, input, metadata));
        }
    };
    executeTest(test1, HttpMethod.PUT, bucketName + "." + endpoint.getHost(), objectKey, new HashMap<String, String>() {

        {
            put("Content-Type", "application/octet-stream");
            put("Content-Length", Long.toString(metadata.getContentLength()));
        }
    }, content, contentBuffer.length);
    metadata.setContentType("text/plain");
    metadata.setContentEncoding(OSSConstants.DEFAULT_CHARSET_NAME);
    metadata.setCacheControl("no-cache");
    metadata.setServerSideEncryption(ObjectMetadata.AES_256_SERVER_SIDE_ENCRYPTION);
    metadata.setUserMetadata(new HashMap<String, String>() {

        {
            put("my", "my");
        }
    });
    final ByteArrayInputStream input2 = new ByteArrayInputStream(contentBuffer);
    TestAction test2 = new TestAction() {

        public void run() throws Exception {
            objectOp.putObject(new PutObjectRequest(bucketName, objectKey, input2, metadata));
        }
    };
    executeTest(test2, HttpMethod.PUT, bucketName + "." + endpoint.getHost(), objectKey, new HashMap<String, String>() {

        {
            put("Content-Type", metadata.getContentType());
            put("Content-Length", Long.toString(metadata.getContentLength()));
            put("Content-Encoding", metadata.getContentEncoding());
            put("Cache-Control", metadata.getCacheControl());
            put("x-oss-server-side-encryption", metadata.getServerSideEncryption());
            put("x-oss-meta-my", "my");
        }
    }, content, contentBuffer.length);
}
Also used : ByteArrayInputStream(java.io.ByteArrayInputStream) UnsupportedEncodingException(java.io.UnsupportedEncodingException) ObjectMetadata(com.aliyun.oss.model.ObjectMetadata) PutObjectRequest(com.aliyun.oss.model.PutObjectRequest) Test(org.junit.Test)

Example 4 with PutObjectRequest

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

the class SimpleGetObjectSample method main.

public static void main(String[] args) throws IOException {
    /*
         * Constructs a client instance with your account for accessing OSS
         */
    OSS client = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
    try {
        /**
         * Note that there are two ways of uploading an object to your bucket, the one
         * by specifying an input stream as content source, the other by specifying a file.
         */
        /*
             * Upload an object to your bucket from an input stream
             */
        System.out.println("Uploading a new object to OSS from an input stream\n");
        String content = "Thank you for using Aliyun Object Storage Service";
        client.putObject(bucketName, key, new ByteArrayInputStream(content.getBytes()));
        /*
             * Upload an object to your bucket from a file
             */
        System.out.println("Uploading a new object to OSS from a file\n");
        client.putObject(new PutObjectRequest(bucketName, key, createSampleFile()));
        /*
             * Download an object from your bucket
             */
        System.out.println("Downloading an object");
        OSSObject object = client.getObject(new GetObjectRequest(bucketName, key));
        System.out.println("Content-Type: " + object.getObjectMetadata().getContentType());
        displayTextInputStream(object.getObjectContent());
    } catch (OSSException oe) {
        System.out.println("Caught an OSSException, which means your request made it to OSS, " + "but was rejected with an error response for some reason.");
        System.out.println("Error Message: " + oe.getErrorCode());
        System.out.println("Error Code:       " + oe.getErrorCode());
        System.out.println("Request ID:      " + oe.getRequestId());
        System.out.println("Host ID:           " + oe.getHostId());
    } catch (ClientException ce) {
        System.out.println("Caught an ClientException, which means the client encountered " + "a serious internal problem while trying to communicate with OSS, " + "such as not being able to access the network.");
        System.out.println("Error Message: " + ce.getMessage());
    } finally {
        /*
             * Do not forget to shut down the client finally to release all allocated resources.
             */
        client.shutdown();
    }
}
Also used : OSSObject(com.aliyun.oss.model.OSSObject) ByteArrayInputStream(java.io.ByteArrayInputStream) OSSException(com.aliyun.oss.OSSException) ClientException(com.aliyun.oss.ClientException) GetObjectRequest(com.aliyun.oss.model.GetObjectRequest) OSS(com.aliyun.oss.OSS) OSSClientBuilder(com.aliyun.oss.OSSClientBuilder) PutObjectRequest(com.aliyun.oss.model.PutObjectRequest)

Example 5 with PutObjectRequest

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

the class ConcurrentGetObjectSample method main.

public static void main(String[] args) throws IOException {
    /*
         * Constructs a client instance with your account for accessing OSS
         */
    client = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
    try {
        /*
             * Upload an object to your bucket
             */
        System.out.println("Uploading a new object to OSS from a file\n");
        client.putObject(new PutObjectRequest(bucketName, key, createSampleFile()));
        /*
             * Get size of the object and pre-create a random access file to hold object data
             */
        ObjectMetadata metadata = client.getObjectMetadata(bucketName, key);
        long objectSize = metadata.getContentLength();
        RandomAccessFile raf = new RandomAccessFile(localFilePath, "rw");
        raf.setLength(objectSize);
        raf.close();
        /*
             * Calculate how many blocks to be divided
             */
        // 5MB
        final long blockSize = 5 * 1024 * 1024L;
        int blockCount = (int) (objectSize / blockSize);
        if (objectSize % blockSize != 0) {
            blockCount++;
        }
        System.out.println("Total blocks count " + blockCount + "\n");
        /*
             * Download the object concurrently
             */
        System.out.println("Start to download " + key + "\n");
        for (int i = 0; i < blockCount; i++) {
            long startPos = i * blockSize;
            long endPos = (i + 1 == blockCount) ? objectSize : (i + 1) * blockSize;
            executorService.execute(new BlockFetcher(startPos, endPos, i + 1));
        }
        /*
             * Waiting for all blocks finished
             */
        executorService.shutdown();
        while (!executorService.isTerminated()) {
            try {
                executorService.awaitTermination(5, TimeUnit.SECONDS);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        /*
             * Verify whether all blocks are finished
             */
        if (completedBlocks.intValue() != blockCount) {
            throw new IllegalStateException("Download fails due to some blocks are not finished yet");
        } else {
            System.out.println("Succeed to download object " + key);
        }
    } catch (OSSException oe) {
        System.out.println("Caught an OSSException, which means your request made it to OSS, " + "but was rejected with an error response for some reason.");
        System.out.println("Error Message: " + oe.getErrorCode());
        System.out.println("Error Code:       " + oe.getErrorCode());
        System.out.println("Request ID:      " + oe.getRequestId());
        System.out.println("Host ID:           " + oe.getHostId());
    } catch (ClientException ce) {
        System.out.println("Caught an ClientException, which means the client encountered " + "a serious internal problem while trying to communicate with OSS, " + "such as not being able to access the network.");
        System.out.println("Error Message: " + ce.getMessage());
    } finally {
        /*
             * Do not forget to shut down the client finally to release all allocated resources.
             */
        if (client != null) {
            client.shutdown();
        }
    }
}
Also used : RandomAccessFile(java.io.RandomAccessFile) OSSException(com.aliyun.oss.OSSException) ClientException(com.aliyun.oss.ClientException) ObjectMetadata(com.aliyun.oss.model.ObjectMetadata) OSSClientBuilder(com.aliyun.oss.OSSClientBuilder) PutObjectRequest(com.aliyun.oss.model.PutObjectRequest)

Aggregations

PutObjectRequest (com.aliyun.oss.model.PutObjectRequest)24 OSSException (com.aliyun.oss.OSSException)18 Test (org.junit.Test)14 OSSObject (com.aliyun.oss.model.OSSObject)13 PutObjectResult (com.aliyun.oss.model.PutObjectResult)9 TestUtils.genFixedLengthInputStream (com.aliyun.oss.integrationtests.TestUtils.genFixedLengthInputStream)8 Callback (com.aliyun.oss.model.Callback)8 GetObjectRequest (com.aliyun.oss.model.GetObjectRequest)8 InputStream (java.io.InputStream)8 OSSClientBuilder (com.aliyun.oss.OSSClientBuilder)7 ObjectMetadata (com.aliyun.oss.model.ObjectMetadata)7 IOException (java.io.IOException)6 ClientException (com.aliyun.oss.ClientException)5 OSS (com.aliyun.oss.OSS)5 ByteArrayInputStream (java.io.ByteArrayInputStream)5 File (java.io.File)5 TestUtils.genFixedLengthFile (com.aliyun.oss.integrationtests.TestUtils.genFixedLengthFile)3 ParseException (java.text.ParseException)3 TestUtils.genRandomLengthFile (com.aliyun.oss.integrationtests.TestUtils.genRandomLengthFile)2 TestUtils.removeFile (com.aliyun.oss.integrationtests.TestUtils.removeFile)2