Search in sources :

Example 1 with OSSClientBuilder

use of com.aliyun.oss.OSSClientBuilder 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 OSSClientBuilder

use of com.aliyun.oss.OSSClientBuilder 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 OSSClientBuilder

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

the class EnvironmentVariableCredentialsProviderTest method testGetEnvironmentVariableCredentialsInOss.

@Test
public void testGetEnvironmentVariableCredentialsInOss() {
    try {
        // unset evn
        List<String> envSet = new ArrayList<String>();
        envSet.add(AuthUtils.ACCESS_KEY_ENV_VAR);
        envSet.add(AuthUtils.SECRET_KEY_ENV_VAR);
        envSet.add(AuthUtils.SESSION_TOKEN_ENV_VAR);
        unsetEnv(envSet);
        // set env
        Map<String, String> env = new HashMap<String, String>(System.getenv());
        env.put(AuthUtils.ACCESS_KEY_ENV_VAR, TestConfig.ROOT_ACCESS_KEY_ID);
        env.put(AuthUtils.SECRET_KEY_ENV_VAR, TestConfig.ROOT_ACCESS_KEY_SECRET);
        setEnv(env);
        // env provider
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        String key = "test.txt";
        String content = "HelloOSS";
        // oss put
        OSS ossClient = new OSSClientBuilder().build(TestConfig.OSS_ENDPOINT, credentialsProvider);
        ossClient.putObject(TestConfig.OSS_BUCKET, key, new ByteArrayInputStream(content.getBytes()));
        ossClient.shutdown();
    } catch (Exception e) {
        e.printStackTrace();
        Assert.fail(e.getMessage());
    }
}
Also used : EnvironmentVariableCredentialsProvider(com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider) HashMap(java.util.HashMap) ByteArrayInputStream(java.io.ByteArrayInputStream) ArrayList(java.util.ArrayList) OSS(com.aliyun.oss.OSS) OSSClientBuilder(com.aliyun.oss.OSSClientBuilder) Test(org.junit.Test)

Example 4 with OSSClientBuilder

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

the class InstanceProfileCredentialsProviderTest method testGetOssCredentialsOnEcs.

/**
 * NOTE: Run this case on ecs.
 */
@Ignore
public void testGetOssCredentialsOnEcs() {
    try {
        // TODO: Establish a simulated ECS metadata service
        CredentialsProvider credentialsProvider = CredentialsProviderFactory.newInstanceProfileCredentialsProvider(TestConfig.RAM_REGION_ID);
        String key = "test.txt";
        String content = "HelloOSS";
        OSS ossClient = new OSSClientBuilder().build(TestConfig.OSS_ENDPOINT, credentialsProvider);
        ossClient.putObject(TestConfig.OSS_BUCKET, key, new ByteArrayInputStream(content.getBytes()));
        ossClient.shutdown();
    } catch (Exception e) {
        e.printStackTrace();
        Assert.fail(e.getMessage());
    }
}
Also used : ByteArrayInputStream(java.io.ByteArrayInputStream) InstanceProfileCredentialsProvider(com.aliyun.oss.common.auth.InstanceProfileCredentialsProvider) CredentialsProvider(com.aliyun.oss.common.auth.CredentialsProvider) OSS(com.aliyun.oss.OSS) OSSClientBuilder(com.aliyun.oss.OSSClientBuilder) Ignore(org.junit.Ignore)

Example 5 with OSSClientBuilder

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

the class SystemPropertiesCredentialsProviderTest method testSystemPropertiesCredentialsProviderInOss.

@Test
public void testSystemPropertiesCredentialsProviderInOss() {
    try {
        System.setProperty(AuthUtils.ACCESS_KEY_SYSTEM_PROPERTY, TestConfig.ROOT_ACCESS_KEY_ID);
        System.setProperty(AuthUtils.SECRET_KEY_SYSTEM_PROPERTY, TestConfig.ROOT_ACCESS_KEY_SECRET);
        System.setProperty(AuthUtils.SESSION_TOKEN_SYSTEM_PROPERTY, "");
        SystemPropertiesCredentialsProvider credentialsProvider = CredentialsProviderFactory.newSystemPropertiesCredentialsProvider();
        String key = "test.txt";
        String content = "HelloOSS";
        OSS ossClient = new OSSClientBuilder().build(TestConfig.OSS_ENDPOINT, credentialsProvider);
        ossClient.putObject(TestConfig.OSS_BUCKET, key, new ByteArrayInputStream(content.getBytes()));
        ossClient.shutdown();
    } catch (Exception e) {
        e.printStackTrace();
        Assert.fail(e.getMessage());
    }
}
Also used : SystemPropertiesCredentialsProvider(com.aliyun.oss.common.auth.SystemPropertiesCredentialsProvider) ByteArrayInputStream(java.io.ByteArrayInputStream) OSS(com.aliyun.oss.OSS) OSSClientBuilder(com.aliyun.oss.OSSClientBuilder) Test(org.junit.Test)

Aggregations

OSSClientBuilder (com.aliyun.oss.OSSClientBuilder)48 OSS (com.aliyun.oss.OSS)39 ByteArrayInputStream (java.io.ByteArrayInputStream)23 Test (org.junit.Test)22 ClientException (com.aliyun.oss.ClientException)19 OSSException (com.aliyun.oss.OSSException)19 ClientBuilderConfiguration (com.aliyun.oss.ClientBuilderConfiguration)13 OSSObject (com.aliyun.oss.model.OSSObject)10 InputStream (java.io.InputStream)10 ObjectMetadata (com.aliyun.oss.model.ObjectMetadata)9 Ignore (org.junit.Ignore)8 PutObjectRequest (com.aliyun.oss.model.PutObjectRequest)7 ArrayList (java.util.ArrayList)7 OSSClient (com.aliyun.oss.OSSClient)5 Credentials (com.aliyun.oss.common.auth.Credentials)5 CredentialsProvider (com.aliyun.oss.common.auth.CredentialsProvider)5 BucketInfo (com.aliyun.oss.model.BucketInfo)5 GetObjectRequest (com.aliyun.oss.model.GetObjectRequest)5 File (java.io.File)5 DefaultCredentialProvider (com.aliyun.oss.common.auth.DefaultCredentialProvider)4