Search in sources :

Example 36 with OSSClientBuilder

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

the class CustomSessionCredentialsProviderTest method testGetCredentialsFromAuthInOss.

@Test
public void testGetCredentialsFromAuthInOss() {
    try {
        CustomSessionCredentialsProvider credentialsProvider = new CustomSessionCredentialsProvider(TestConfig.OSS_AUTH_SERVER_HOST);
        Credentials credentials = credentialsProvider.getCredentials();
        Assert.assertEquals(credentials.getAccessKeyId().length(), 29);
        Assert.assertEquals(credentials.getSecretAccessKey().length(), 44);
        Assert.assertEquals(credentials.getSecurityToken().length(), 516);
        Assert.assertTrue(credentials.useSecurityToken());
        String key = "test.txt";
        String content = "HelloOSS";
        OSS ossClient = new OSSClientBuilder().build(TestConfig.OSS_ENDPOINT, credentials.getAccessKeyId(), credentials.getSecretAccessKey(), credentials.getSecurityToken());
        ossClient.putObject(TestConfig.OSS_BUCKET, key, new ByteArrayInputStream(content.getBytes()));
        ossClient.shutdown();
    } catch (Exception e) {
        e.printStackTrace();
        Assert.fail(e.getMessage());
    }
}
Also used : CustomSessionCredentialsProvider(com.aliyun.oss.common.auth.CustomSessionCredentialsProvider) ByteArrayInputStream(java.io.ByteArrayInputStream) BasicCredentials(com.aliyun.oss.common.auth.BasicCredentials) Credentials(com.aliyun.oss.common.auth.Credentials) OSS(com.aliyun.oss.OSS) OSSClientBuilder(com.aliyun.oss.OSSClientBuilder) Test(org.junit.Test)

Example 37 with OSSClientBuilder

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

the class CustomSessionCredentialsProviderTest method testGetCredentialsUseInOss.

@Test
public void testGetCredentialsUseInOss() {
    try {
        CustomSessionCredentialsProvider credentialsProvider = CredentialsProviderFactory.newCustomSessionCredentialsProvider(TestConfig.OSS_AUTH_SERVER_HOST);
        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()));
        Thread.sleep(1000 * 10);
        ossClient.putObject(TestConfig.OSS_BUCKET, key, new ByteArrayInputStream(content.getBytes()));
        ossClient.shutdown();
    } catch (Exception e) {
        e.printStackTrace();
        Assert.fail(e.getMessage());
    }
}
Also used : CustomSessionCredentialsProvider(com.aliyun.oss.common.auth.CustomSessionCredentialsProvider) ByteArrayInputStream(java.io.ByteArrayInputStream) OSS(com.aliyun.oss.OSS) OSSClientBuilder(com.aliyun.oss.OSSClientBuilder) Test(org.junit.Test)

Example 38 with OSSClientBuilder

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

the class ImageSample method main.

public static void main(String[] args) throws IOException {
    OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
    try {
        // resize
        String style = "image/resize,m_fixed,w_100,h_100";
        GetObjectRequest request = new GetObjectRequest(bucketName, key);
        request.setProcess(style);
        ossClient.getObject(request, new File("example-resize.jpg"));
        // crop
        style = "image/crop,w_100,h_100,x_100,y_100,r_1";
        request = new GetObjectRequest(bucketName, key);
        request.setProcess(style);
        ossClient.getObject(request, new File("example-crop.jpg"));
        // rotate
        style = "image/rotate,90";
        request = new GetObjectRequest(bucketName, key);
        request.setProcess(style);
        ossClient.getObject(request, new File("example-rotate.jpg"));
        // sharpen
        style = "image/sharpen,100";
        request = new GetObjectRequest(bucketName, key);
        request.setProcess(style);
        ossClient.getObject(request, new File("example-sharpen.jpg"));
        // add watermark into the image
        style = "image/watermark,text_SGVsbG8g5Zu-54mH5pyN5YqhIQ";
        request = new GetObjectRequest(bucketName, key);
        request.setProcess(style);
        ossClient.getObject(request, new File("example-watermark.jpg"));
        // convert format
        style = "image/format,png";
        request = new GetObjectRequest(bucketName, key);
        request.setProcess(style);
        ossClient.getObject(request, new File("example-format.png"));
        // image information
        style = "image/info";
        request = new GetObjectRequest(bucketName, key);
        request.setProcess(style);
        ossClient.getObject(request, new File("example-info.txt"));
    } 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());
    } catch (Throwable e) {
        e.printStackTrace();
    } finally {
        ossClient.shutdown();
    }
}
Also used : OSSException(com.aliyun.oss.OSSException) ClientException(com.aliyun.oss.ClientException) GetObjectRequest(com.aliyun.oss.model.GetObjectRequest) File(java.io.File) OSS(com.aliyun.oss.OSS) OSSClientBuilder(com.aliyun.oss.OSSClientBuilder)

Example 39 with OSSClientBuilder

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

the class MultipartUploadSample method main.

public static void main(String[] args) throws IOException {
    /*
         * Constructs a client instance with your account for accessing OSS
         */
    ClientBuilderConfiguration conf = new ClientBuilderConfiguration();
    conf.setIdleConnectionTime(1000);
    client = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret, conf);
    try {
        /*
             * Claim a upload id firstly
             */
        String uploadId = claimUploadId();
        System.out.println("Claiming a new upload id " + uploadId + "\n");
        /*
             * Calculate how many parts to be divided
             */
        // 5MB
        final long partSize = 5 * 1024 * 1024L;
        final File sampleFile = createSampleFile();
        long fileLength = sampleFile.length();
        int partCount = (int) (fileLength / partSize);
        if (fileLength % 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 to your bucket
             */
        System.out.println("Begin to upload multiparts to OSS from a file\n");
        for (int i = 0; i < partCount; i++) {
            long startPos = i * partSize;
            long curPartSize = (i + 1 == partCount) ? (fileLength - startPos) : partSize;
            executorService.execute(new PartUploader(sampleFile, startPos, curPartSize, i + 1, uploadId));
        }
        /*
             * Waiting for all parts finished
             */
        executorService.shutdown();
        while (!executorService.isTerminated()) {
            try {
                executorService.awaitTermination(5, TimeUnit.SECONDS);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        /*
             * Verify whether all parts are finished
             */
        if (partETags.size() != partCount) {
            throw new IllegalStateException("Upload multiparts fail due to some parts are not finished yet");
        } else {
            System.out.println("Succeed to complete multiparts into an object named " + key + "\n");
        }
        /*
             * View all parts uploaded recently
             */
        listAllParts(uploadId);
        /*
             * Complete to upload multiparts
             */
        completeMultipartUpload(uploadId);
        /*
             * Fetch the object that newly created at the step below.
             */
        System.out.println("Fetching an object");
        client.getObject(new GetObjectRequest(bucketName, key), 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.
             */
        if (client != null) {
            client.shutdown();
        }
    }
}
Also used : OSSException(com.aliyun.oss.OSSException) ClientBuilderConfiguration(com.aliyun.oss.ClientBuilderConfiguration) ClientException(com.aliyun.oss.ClientException) File(java.io.File) GetObjectRequest(com.aliyun.oss.model.GetObjectRequest) OSSClientBuilder(com.aliyun.oss.OSSClientBuilder)

Example 40 with OSSClientBuilder

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

the class EnvironmentVariableCredentialsProviderTest method testGetEnvironmentVariableStsCredentialsInOss.

@Test
public void testGetEnvironmentVariableStsCredentialsInOss() {
    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);
        CredentialsProvider assumeRoleCredProvider = CredentialsProviderFactory.newSTSAssumeRoleSessionCredentialsProvider(TestConfig.RAM_REGION_ID, TestConfig.USER_ACCESS_KEY_ID, TestConfig.USER_ACCESS_KEY_SECRET, TestConfig.RAM_ROLE_ARN);
        // set env
        Credentials assumeRoleCred = assumeRoleCredProvider.getCredentials();
        Map<String, String> envMap = new HashMap<String, String>(System.getenv());
        envMap.put(AuthUtils.ACCESS_KEY_ENV_VAR, assumeRoleCred.getAccessKeyId());
        envMap.put(AuthUtils.SECRET_KEY_ENV_VAR, assumeRoleCred.getSecretAccessKey());
        envMap.put(AuthUtils.SESSION_TOKEN_ENV_VAR, assumeRoleCred.getSecurityToken());
        setEnv(envMap);
        // env provider
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        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 : EnvironmentVariableCredentialsProvider(com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider) HashMap(java.util.HashMap) ByteArrayInputStream(java.io.ByteArrayInputStream) ArrayList(java.util.ArrayList) EnvironmentVariableCredentialsProvider(com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider) CredentialsProvider(com.aliyun.oss.common.auth.CredentialsProvider) Credentials(com.aliyun.oss.common.auth.Credentials) 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