5 | * 版权所有 (C)阿里巴巴云计算,2015 6 | */ 7 | 8 | package com.alibaba.sdk.android.oss; 9 | 10 | import com.alibaba.sdk.android.oss.common.OSSLog; 11 | 12 | /** 13 | *
14 | * The client side exceptions when accessing OSS service 15 | *
16 | *17 | *
18 | * {@link ClientException} means there're errors occurred when sending request to OSS or parsing the response from OSS. 19 | * For example when the network is unavailable, this exception will be thrown. 20 | *
21 | *22 | *
23 | * {@link ServiceException} means there're errors occurred in OSS service side. For example, the Access Id 24 | * does not exist for authentication, then {@link ServiceException} or its subclass is thrown. 25 | * The ServiceException has the error code for the caller to have some specific handling. 26 | *
27 | *28 | *
29 | * Generally speaking, the caller only needs to handle {@link ServiceException} as it means the request 30 | * has reached OSS, but there're some errors occurred. This error in most of cases are expected due to 31 | * wrong parameters int the request or some wrong settings in user's account. The error code is very helpful 32 | * for troubleshooting. 33 | *
34 | */ 35 | public class ClientException extends Exception { 36 | 37 | private Boolean canceled = false; 38 | 39 | /** 40 | * Constructor 41 | */ 42 | public ClientException() { 43 | super(); 44 | } 45 | 46 | /** 47 | * Constructor with message 48 | * 49 | * @param message the error message 50 | */ 51 | public ClientException(String message) { 52 | super("[ErrorMessage]: " + message); 53 | } 54 | 55 | /** 56 | * Constructor with exception 57 | * 58 | * @param cause the exception 59 | */ 60 | public ClientException(Throwable cause) { 61 | super(cause); 62 | } 63 | 64 | /** 65 | * Constructor with error message and exception instance 66 | * 67 | * @param message Error message 68 | * @param cause The exception instance 69 | */ 70 | public ClientException(String message, Throwable cause) { 71 | this(message, cause, false); 72 | } 73 | 74 | /** 75 | * Constructor with error message, exception instance and isCancelled flag 76 | */ 77 | public ClientException(String message, Throwable cause, Boolean isCancelled) { 78 | super("[ErrorMessage]: " + message, cause); 79 | this.canceled = isCancelled; 80 | OSSLog.logThrowable2Local(this); 81 | } 82 | 83 | /** 84 | * Checks if the exception is due to the cancellation 85 | * 86 | * @return 87 | */ 88 | public Boolean isCanceledException() { 89 | return canceled; 90 | } 91 | 92 | 93 | @Override 94 | public String getMessage() { 95 | String base = super.getMessage(); 96 | return getCause() == null ? base : getCause().getMessage() + "\n" + base; 97 | } 98 | } 99 | -------------------------------------------------------------------------------- /oss-android-sdk/src/main/java/com/alibaba/sdk/android/oss/TaskCancelException.java: -------------------------------------------------------------------------------- 1 | package com.alibaba.sdk.android.oss; 2 | 3 | /** 4 | * Created by huaixu on 2018/2/9. 5 | */ 6 | 7 | public class TaskCancelException extends Exception { 8 | /** 9 | * Constructor 10 | */ 11 | public TaskCancelException() { 12 | super(); 13 | } 14 | 15 | /** 16 | * Constructor with message 17 | * 18 | * @param message the error message 19 | */ 20 | public TaskCancelException(String message) { 21 | super("[ErrorMessage]: " + message); 22 | } 23 | 24 | /** 25 | * Constructor with exception 26 | * 27 | * @param cause the exception 28 | */ 29 | public TaskCancelException(Throwable cause) { 30 | super(cause); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /oss-android-sdk/src/main/java/com/alibaba/sdk/android/oss/callback/OSSCompletedCallback.java: -------------------------------------------------------------------------------- 1 | package com.alibaba.sdk.android.oss.callback; 2 | 3 | import com.alibaba.sdk.android.oss.ClientException; 4 | import com.alibaba.sdk.android.oss.ServiceException; 5 | import com.alibaba.sdk.android.oss.model.OSSRequest; 6 | import com.alibaba.sdk.android.oss.model.OSSResult; 7 | 8 | /** 9 | * Created by zhouzhuo on 11/19/15. 10 | */ 11 | public interface OSSCompletedCallback
5 | * 版权所有 (C)阿里巴巴云计算,2015
6 | */
7 |
8 | package com.alibaba.sdk.android.oss.common;
9 |
10 | /**
11 | * HTTP METHOD ENUM
12 | */
13 | public enum HttpMethod {
14 | /**
15 | * HTTP DELETE
16 | */
17 | DELETE,
18 |
19 | /**
20 | * HTTP GET
21 | */
22 | GET,
23 |
24 | /**
25 | * HTTP HEAD
26 | */
27 | HEAD,
28 |
29 | /**
30 | * HTTP POST
31 | */
32 | POST,
33 |
34 | /**
35 | * HTTP PUT
36 | */
37 | PUT,
38 |
39 | /**
40 | * HTTP OPTION
41 | */
42 | OPTIONS
43 | }
--------------------------------------------------------------------------------
/oss-android-sdk/src/main/java/com/alibaba/sdk/android/oss/common/HttpProtocol.java:
--------------------------------------------------------------------------------
1 | package com.alibaba.sdk.android.oss.common;
2 |
3 | public enum HttpProtocol {
4 | HTTP("http"),
5 | HTTPS("https");
6 | private final String httpProtocol;
7 |
8 | private HttpProtocol(String protocol) {
9 | httpProtocol = protocol;
10 | }
11 |
12 | public String toString() {
13 | return httpProtocol;
14 | }
15 | }
16 |
--------------------------------------------------------------------------------
/oss-android-sdk/src/main/java/com/alibaba/sdk/android/oss/common/LogLevel.java:
--------------------------------------------------------------------------------
1 | package com.alibaba.sdk.android.oss.common;
2 |
3 | public enum LogLevel {
4 | INFO,
5 | VERBOSE,
6 | WARN,
7 | DEBUG,
8 | ERROR
9 | }
10 |
--------------------------------------------------------------------------------
/oss-android-sdk/src/main/java/com/alibaba/sdk/android/oss/common/LogPrinter.java:
--------------------------------------------------------------------------------
1 | package com.alibaba.sdk.android.oss.common;
2 |
3 | public interface LogPrinter {
4 | void log(LogLevel level, String message);
5 | }
6 |
--------------------------------------------------------------------------------
/oss-android-sdk/src/main/java/com/alibaba/sdk/android/oss/common/LogThreadPoolManager.java:
--------------------------------------------------------------------------------
1 | package com.alibaba.sdk.android.oss.common;
2 |
3 | import java.util.LinkedList;
4 | import java.util.Queue;
5 | import java.util.concurrent.ArrayBlockingQueue;
6 | import java.util.concurrent.Executors;
7 | import java.util.concurrent.RejectedExecutionHandler;
8 | import java.util.concurrent.ScheduledExecutorService;
9 | import java.util.concurrent.ScheduledFuture;
10 | import java.util.concurrent.ThreadFactory;
11 | import java.util.concurrent.ThreadPoolExecutor;
12 | import java.util.concurrent.TimeUnit;
13 |
14 | /**
15 | * Created by jingdan on 2017/9/5.
16 | * ThreadPool For Log
17 | */
18 |
19 | public class LogThreadPoolManager {
20 | private static final int SIZE_CORE_POOL = 1;
21 | private static final int SIZE_MAX_POOL = 1;
22 | private static final int TIME_KEEP_ALIVE = 5000;
23 | private static final int SIZE_WORK_QUEUE = 500;
24 | private static final int PERIOD_TASK_QOS = 1000;
25 | private static final int SIZE_CACHE_QUEUE = 200;
26 | private static LogThreadPoolManager sThreadPoolManager = new LogThreadPoolManager();
27 | private final Queue
5 | * 版权所有 (C)阿里巴巴云计算,2015
6 | */
7 |
8 | package com.alibaba.sdk.android.oss.common.auth;
9 |
10 | import com.alibaba.sdk.android.oss.common.OSSLog;
11 | import com.alibaba.sdk.android.oss.common.utils.BinaryUtil;
12 |
13 | import java.io.UnsupportedEncodingException;
14 | import java.security.InvalidKeyException;
15 | import java.security.NoSuchAlgorithmException;
16 |
17 | import javax.crypto.Mac;
18 | import javax.crypto.spec.SecretKeySpec;
19 |
20 | /**
21 | * Hmac-SHA1 signature
22 | */
23 | public class HmacSHA1Signature {
24 | private static final String DEFAULT_ENCODING = "UTF-8"; // Default encoding
25 | private static final String ALGORITHM = "HmacSHA1"; // Signature method.
26 | private static final String VERSION = "1"; // Signature version.
27 | private static final Object LOCK = new Object();
28 | private static Mac macInstance; // Prototype of the Mac instance.
29 |
30 | public HmacSHA1Signature() {
31 | }
32 |
33 | public String getAlgorithm() {
34 | return ALGORITHM;
35 | }
36 |
37 | public String getVersion() {
38 | return VERSION;
39 | }
40 |
41 | public String computeSignature(String key, String data) {
42 | OSSLog.logDebug(getAlgorithm(), false);
43 | OSSLog.logDebug(getVersion(), false);
44 | String sign = null;
45 | try {
46 | OSSLog.logDebug("sign start");
47 | byte[] signData = sign(
48 | key.getBytes(DEFAULT_ENCODING),
49 | data.getBytes(DEFAULT_ENCODING));
50 | OSSLog.logDebug("base64 start");
51 | sign = BinaryUtil.toBase64String(signData);
52 | } catch (UnsupportedEncodingException ex) {
53 | throw new RuntimeException("Unsupported algorithm: " + DEFAULT_ENCODING);
54 | }
55 | return sign;
56 | }
57 |
58 |
59 | private byte[] sign(byte[] key, byte[] data) {
60 | byte[] sign = null;
61 | try {
62 | // Because Mac.getInstance(String) calls a synchronized method,
63 | // it could block on invoked concurrently.
64 | // SO use prototype pattern to improve perf.
65 | if (macInstance == null) {
66 | synchronized (LOCK) {
67 | if (macInstance == null) {
68 | macInstance = Mac.getInstance(getAlgorithm());
69 | }
70 | }
71 | }
72 |
73 | Mac mac;
74 | try {
75 | mac = (Mac) macInstance.clone();
76 | } catch (CloneNotSupportedException e) {
77 | // If it is not clonable, create a new one.
78 | mac = Mac.getInstance(getAlgorithm());
79 | }
80 | mac.init(new SecretKeySpec(key, getAlgorithm()));
81 | sign = mac.doFinal(data);
82 | } catch (NoSuchAlgorithmException ex) {
83 | throw new RuntimeException("Unsupported algorithm: " + ALGORITHM);
84 | } catch (InvalidKeyException ex) {
85 | throw new RuntimeException("key must not be null");
86 | }
87 | return sign;
88 | }
89 | }
--------------------------------------------------------------------------------
/oss-android-sdk/src/main/java/com/alibaba/sdk/android/oss/common/auth/OSSAuthCredentialsProvider.java:
--------------------------------------------------------------------------------
1 | package com.alibaba.sdk.android.oss.common.auth;
2 |
3 | import com.alibaba.sdk.android.oss.ClientException;
4 | import com.alibaba.sdk.android.oss.common.OSSConstants;
5 | import com.alibaba.sdk.android.oss.common.utils.IOUtils;
6 |
7 | import org.json.JSONObject;
8 |
9 | import java.io.InputStream;
10 | import java.net.HttpURLConnection;
11 | import java.net.URL;
12 |
13 | /**
14 | * Created by jingdan on 2017/11/15.
15 | * Authentication server issued under the agreement of the official website agreement, you can directly use the provider
16 | */
17 |
18 | public class OSSAuthCredentialsProvider extends OSSFederationCredentialProvider {
19 |
20 | private String mAuthServerUrl;
21 | private AuthDecoder mDecoder;
22 |
23 | public OSSAuthCredentialsProvider(String authServerUrl) {
24 | this.mAuthServerUrl = authServerUrl;
25 | }
26 |
27 | /**
28 | * set auth server url
29 | *
30 | * @param authServerUrl
31 | */
32 | public void setAuthServerUrl(String authServerUrl) {
33 | this.mAuthServerUrl = authServerUrl;
34 | }
35 |
36 | /**
37 | * set response data decoder
38 | *
39 | * @param decoder
40 | */
41 | public void setDecoder(AuthDecoder decoder) {
42 | this.mDecoder = decoder;
43 | }
44 |
45 | @Override
46 | public OSSFederationToken getFederationToken() throws ClientException {
47 | OSSFederationToken authToken;
48 | String authData;
49 | try {
50 | URL stsUrl = new URL(mAuthServerUrl);
51 | HttpURLConnection conn = (HttpURLConnection) stsUrl.openConnection();
52 | conn.setConnectTimeout(10000);
53 | InputStream input = conn.getInputStream();
54 | authData = IOUtils.readStreamAsString(input, OSSConstants.DEFAULT_CHARSET_NAME);
55 | if (mDecoder != null) {
56 | authData = mDecoder.decode(authData);
57 | }
58 | JSONObject jsonObj = new JSONObject(authData);
59 | int statusCode = jsonObj.getInt("StatusCode");
60 | if (statusCode == 200) {
61 | String ak = jsonObj.getString("AccessKeyId");
62 | String sk = jsonObj.getString("AccessKeySecret");
63 | String token = jsonObj.getString("SecurityToken");
64 | String expiration = jsonObj.getString("Expiration");
65 | authToken = new OSSFederationToken(ak, sk, token, expiration);
66 | } else {
67 | String errorCode = jsonObj.getString("ErrorCode");
68 | String errorMessage = jsonObj.getString("ErrorMessage");
69 | throw new ClientException("ErrorCode: " + errorCode + "| ErrorMessage: " + errorMessage);
70 | }
71 | return authToken;
72 | } catch (Exception e) {
73 | throw new ClientException(e);
74 | }
75 | }
76 |
77 | public interface AuthDecoder {
78 | String decode(String data);
79 | }
80 | }
81 |
--------------------------------------------------------------------------------
/oss-android-sdk/src/main/java/com/alibaba/sdk/android/oss/common/auth/OSSCredentialProvider.java:
--------------------------------------------------------------------------------
1 | package com.alibaba.sdk.android.oss.common.auth;
2 |
3 | import com.alibaba.sdk.android.oss.ClientException;
4 |
5 | /**
6 | * Created by zhouzhuo on 11/4/15.
7 | */
8 | public interface OSSCredentialProvider {
9 |
10 | /**
11 | * get OSSFederationToken instance
12 | *
13 | * @return
14 | */
15 | OSSFederationToken getFederationToken() throws ClientException;
16 | }
17 |
--------------------------------------------------------------------------------
/oss-android-sdk/src/main/java/com/alibaba/sdk/android/oss/common/auth/OSSCustomSignerCredentialProvider.java:
--------------------------------------------------------------------------------
1 | package com.alibaba.sdk.android.oss.common.auth;
2 |
3 | /**
4 | * Created by zhouzhuo on 11/4/15.
5 | */
6 | public abstract class OSSCustomSignerCredentialProvider implements OSSCredentialProvider {
7 | /**
8 | * Custom content sign method. Considering the AccessKeyId/AccessKeySecret is not likely be stored in mobile device,
9 | * this method is supposed to talk to customer's app servers and get the signature of the content.
10 | * The typical implementation could be that it posts the content to an app servers and the server has the AK information
11 | * and sign the content then return the signature.
12 | *
13 | * The sign algorithm:http://help.aliyun.com/document_detail/oss/api-reference/access-control/signature-header.html
14 | * signature = "OSS " + AccessKeyId + ":" + base64(hmac-sha1(AccessKeySecret, content))
15 | *
16 | *
17 | * content is the final text to sign which comes from the URL parameters, headers and the actual content payload.
18 | *
19 | * @param content The final text to sign, which is concated from url parameters, url headers and body.
20 | * @return "OSS " + AccessKeyId + ":" + base64(hmac-sha1(AccessKeySecret, content))
21 | */
22 | public abstract String signContent(String content);
23 |
24 | @Override
25 | public OSSFederationToken getFederationToken() {
26 | return null;
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/oss-android-sdk/src/main/java/com/alibaba/sdk/android/oss/common/auth/OSSFederationCredentialProvider.java:
--------------------------------------------------------------------------------
1 | package com.alibaba.sdk.android.oss.common.auth;
2 |
3 | import com.alibaba.sdk.android.oss.ClientException;
4 | import com.alibaba.sdk.android.oss.common.OSSLog;
5 | import com.alibaba.sdk.android.oss.common.utils.DateUtil;
6 |
7 | /**
8 | * Created by zhouzhuo on 11/4/15.
9 | */
10 | public abstract class OSSFederationCredentialProvider implements OSSCredentialProvider {
11 |
12 | private volatile OSSFederationToken cachedToken;
13 |
14 | /**
15 | * Gets the valid STS token. The subclass needs to implement this function.
16 | *
17 | * @return The valid STS Token
18 | */
19 | public abstract OSSFederationToken getFederationToken() throws ClientException;
20 |
21 | public synchronized OSSFederationToken getValidFederationToken() throws ClientException {
22 | // Checks if the STS token is expired. To avoid returning staled data, here we pre-fetch the token 5 minutes a head of the real expiration.
23 | // The minimal expiration time is 15 minutes
24 | if (cachedToken == null
25 | || DateUtil.getFixedSkewedTimeMillis() / 1000 > cachedToken.getExpiration() - 5 * 60) {
26 |
27 | if (cachedToken != null) {
28 | OSSLog.logDebug("token expired! current time: " + DateUtil.getFixedSkewedTimeMillis() / 1000 + " token expired: " + cachedToken.getExpiration());
29 | }
30 | cachedToken = getFederationToken();
31 | }
32 |
33 | return cachedToken;
34 | }
35 |
36 | public OSSFederationToken getCachedToken() {
37 | return cachedToken;
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/oss-android-sdk/src/main/java/com/alibaba/sdk/android/oss/common/auth/OSSPlainTextAKSKCredentialProvider.java:
--------------------------------------------------------------------------------
1 | package com.alibaba.sdk.android.oss.common.auth;
2 |
3 | /**
4 | * Created by zhouzhuo on 11/4/15.
5 | * Edited by zhuoqin on 7/12/17.
6 | * Mobile devices are not the trusted environment. It's very risky to save the AccessKeyId and AccessKeySecret in mobile devices for accessing OSS.
7 | * We recommend to use STS authentication or custom authentication.
8 | */
9 | @Deprecated
10 | public class OSSPlainTextAKSKCredentialProvider implements OSSCredentialProvider {
11 | private String accessKeyId;
12 | private String accessKeySecret;
13 |
14 | /**
15 | * 用阿里云提供的AccessKeyId, AccessKeySecret构造一个凭证提供器
16 | *
17 | * @param accessKeyId
18 | * @param accessKeySecret
19 | */
20 | public OSSPlainTextAKSKCredentialProvider(String accessKeyId, String accessKeySecret) {
21 | setAccessKeyId(accessKeyId.trim());
22 | setAccessKeySecret(accessKeySecret.trim());
23 | }
24 |
25 | public String getAccessKeyId() {
26 | return accessKeyId;
27 | }
28 |
29 | public void setAccessKeyId(String accessKeyId) {
30 | this.accessKeyId = accessKeyId;
31 | }
32 |
33 | public String getAccessKeySecret() {
34 | return accessKeySecret;
35 | }
36 |
37 | public void setAccessKeySecret(String accessKeySecret) {
38 | this.accessKeySecret = accessKeySecret;
39 | }
40 |
41 | @Override
42 | public OSSFederationToken getFederationToken() {
43 | return null;
44 | }
45 | }
46 |
--------------------------------------------------------------------------------
/oss-android-sdk/src/main/java/com/alibaba/sdk/android/oss/common/auth/OSSStsTokenCredentialProvider.java:
--------------------------------------------------------------------------------
1 | package com.alibaba.sdk.android.oss.common.auth;
2 |
3 | /**
4 | * Created by zhouzhuo on 1/22/16.
5 | */
6 | public class OSSStsTokenCredentialProvider implements OSSCredentialProvider {
7 |
8 | private String accessKeyId;
9 | private String secretKeyId;
10 | private String securityToken;
11 |
12 | /**
13 | * Creates an instance of StsTokenCredentialProvider with the STS token got from RAM.
14 | * STS token has four entities: AccessKey, SecretKeyId, SecurityToken, Expiration.
15 | * If the authentication is in this way, SDK will not refresh the token once it's expired.
16 | *
17 | * @param accessKeyId
18 | * @param secretKeyId
19 | * @param securityToken
20 | */
21 | public OSSStsTokenCredentialProvider(String accessKeyId, String secretKeyId, String securityToken) {
22 | setAccessKeyId(accessKeyId.trim());
23 | setSecretKeyId(secretKeyId.trim());
24 | setSecurityToken(securityToken.trim());
25 | }
26 |
27 | public OSSStsTokenCredentialProvider(OSSFederationToken token) {
28 | setAccessKeyId(token.getTempAK().trim());
29 | setSecretKeyId(token.getTempSK().trim());
30 | setSecurityToken(token.getSecurityToken().trim());
31 | }
32 |
33 | public String getAccessKeyId() {
34 | return accessKeyId;
35 | }
36 |
37 | public void setAccessKeyId(String accessKeyId) {
38 | this.accessKeyId = accessKeyId;
39 | }
40 |
41 | public String getSecretKeyId() {
42 | return secretKeyId;
43 | }
44 |
45 | public void setSecretKeyId(String secretKeyId) {
46 | this.secretKeyId = secretKeyId;
47 | }
48 |
49 | public String getSecurityToken() {
50 | return securityToken;
51 | }
52 |
53 | public void setSecurityToken(String securityToken) {
54 | this.securityToken = securityToken;
55 | }
56 |
57 | public OSSFederationToken getFederationToken() {
58 | return new OSSFederationToken(accessKeyId, secretKeyId, securityToken, Long.MAX_VALUE);
59 | }
60 | }
61 |
--------------------------------------------------------------------------------
/oss-android-sdk/src/main/java/com/alibaba/sdk/android/oss/common/utils/CaseInsensitiveHashMap.java:
--------------------------------------------------------------------------------
1 | package com.alibaba.sdk.android.oss.common.utils;
2 |
3 | import java.util.HashMap;
4 |
5 | /**
6 | * Created by wangzheng on 2018/7/12.
7 | */
8 |
9 | public class CaseInsensitiveHashMap
5 | * 版权所有 (C)阿里巴巴云计算,2015
6 | */
7 |
8 | package com.alibaba.sdk.android.oss.common.utils;
9 |
10 | /**
11 | * Contains the common HTTP headers.
12 | */
13 | public interface HttpHeaders {
14 |
15 | public static final String AUTHORIZATION = "Authorization";
16 | public static final String CACHE_CONTROL = "Cache-Control";
17 | public static final String CONTENT_DISPOSITION = "Content-Disposition";
18 | public static final String CONTENT_ENCODING = "Content-Encoding";
19 | public static final String CONTENT_LENGTH = "Content-Length";
20 | public static final String CONTENT_MD5 = "Content-MD5";
21 | public static final String CONTENT_TYPE = "Content-Type";
22 | public static final String DATE = "Date";
23 | public static final String ETAG = "ETag";
24 | public static final String EXPIRES = "Expires";
25 | public static final String HOST = "Host";
26 | public static final String LAST_MODIFIED = "Last-Modified";
27 | public static final String RANGE = "Range";
28 | public static final String LOCATION = "Location";
29 | public static final String USER_AGENT = "User-Agent";
30 |
31 | }
32 |
--------------------------------------------------------------------------------
/oss-android-sdk/src/main/java/com/alibaba/sdk/android/oss/common/utils/IOUtils.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright (C) Alibaba Cloud Computing, 2015
3 | * All rights reserved.
4 | *
5 | * 版权所有 (C)阿里巴巴云计算,2015
6 | */
7 |
8 | package com.alibaba.sdk.android.oss.common.utils;
9 |
10 | import java.io.BufferedReader;
11 | import java.io.ByteArrayOutputStream;
12 | import java.io.IOException;
13 | import java.io.InputStream;
14 | import java.io.InputStreamReader;
15 | import java.io.OutputStream;
16 | import java.io.Reader;
17 | import java.io.StringWriter;
18 | import java.io.Writer;
19 |
20 | public class IOUtils {
21 |
22 | private final static int BUFFER_SIZE = 4 * 1024;
23 |
24 | public static String readStreamAsString(InputStream in, String charset)
25 | throws IOException {
26 | if (in == null)
27 | return "";
28 |
29 | Reader reader = null;
30 | Writer writer = new StringWriter();
31 | String result;
32 |
33 | char[] buffer = new char[BUFFER_SIZE];
34 | try {
35 | reader = new BufferedReader(
36 | new InputStreamReader(in, charset));
37 |
38 | int n;
39 | while ((n = reader.read(buffer)) > 0) {
40 | writer.write(buffer, 0, n);
41 | }
42 |
43 | result = writer.toString();
44 | } finally {
45 | safeClose(in);
46 | if (reader != null) {
47 | reader.close();
48 | }
49 | if (writer != null) {
50 | writer.close();
51 | }
52 | }
53 |
54 | return result;
55 | }
56 |
57 | public static byte[] readStreamAsBytesArray(InputStream in)
58 | throws IOException {
59 | if (in == null) {
60 | return new byte[0];
61 | }
62 |
63 | ByteArrayOutputStream output = new ByteArrayOutputStream();
64 | byte[] buffer = new byte[BUFFER_SIZE];
65 | int len;
66 | while ((len = in.read(buffer)) > -1) {
67 | output.write(buffer, 0, len);
68 | }
69 | output.flush();
70 | safeClose(output);
71 | return output.toByteArray();
72 | }
73 |
74 | public static byte[] readStreamAsBytesArray(InputStream in, int readLength)
75 | throws IOException {
76 | if (in == null) {
77 | return new byte[0];
78 | }
79 |
80 | ByteArrayOutputStream output = new ByteArrayOutputStream();
81 | byte[] buffer = new byte[BUFFER_SIZE];
82 | int len;
83 | long readed = 0;
84 | while (readed < readLength && (len = in.read(buffer, 0, Math.min(2048, (int) (readLength - readed)))) > -1) {
85 | output.write(buffer, 0, len);
86 | readed += len;
87 | }
88 | output.flush();
89 | safeClose(output);
90 | return output.toByteArray();
91 | }
92 |
93 | public static void safeClose(InputStream inputStream) {
94 | if (inputStream != null) {
95 | try {
96 | inputStream.close();
97 | } catch (IOException e) {
98 | }
99 | }
100 | }
101 |
102 | public static void safeClose(OutputStream outputStream) {
103 | if (outputStream != null) {
104 | try {
105 | outputStream.close();
106 | } catch (IOException e) {
107 | }
108 | }
109 | }
110 | }
111 |
--------------------------------------------------------------------------------
/oss-android-sdk/src/main/java/com/alibaba/sdk/android/oss/common/utils/OSSSharedPreferences.java:
--------------------------------------------------------------------------------
1 | package com.alibaba.sdk.android.oss.common.utils;
2 |
3 | import android.content.Context;
4 | import android.content.SharedPreferences;
5 |
6 | /**
7 | * Created by jingdan on 2017/12/6.
8 | */
9 |
10 | public class OSSSharedPreferences {
11 |
12 | private static OSSSharedPreferences sInstance;
13 | private SharedPreferences mSp;
14 |
15 | private OSSSharedPreferences(Context context) {
16 | mSp = context.getSharedPreferences("oss_android_sdk_sp", Context.MODE_PRIVATE);
17 | }
18 |
19 |
20 | public static OSSSharedPreferences instance(Context context) {
21 | if (sInstance == null) {
22 | synchronized (OSSSharedPreferences.class) {
23 | if (sInstance == null) {
24 | sInstance = new OSSSharedPreferences(context);
25 | }
26 | }
27 | }
28 | return sInstance;
29 | }
30 |
31 | public void setStringValue(String key, String value) {
32 | SharedPreferences.Editor edit = mSp.edit();
33 | edit.putString(key, value);
34 | edit.commit();
35 | }
36 |
37 | public String getStringValue(String key) {
38 | return mSp.getString(key, "");
39 | }
40 |
41 | public void removeKey(String key) {
42 | SharedPreferences.Editor edit = mSp.edit();
43 | edit.remove(key);
44 | edit.commit();
45 | }
46 |
47 | public boolean contains(String key) {
48 | return mSp.contains(key);
49 | }
50 | }
51 |
--------------------------------------------------------------------------------
/oss-android-sdk/src/main/java/com/alibaba/sdk/android/oss/common/utils/ServiceConstants.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright (C) Alibaba Cloud Computing, 2015
3 | * All rights reserved.
4 | *
5 | * 版权所有 (C)阿里巴巴云计算,2015
6 | */
7 |
8 | package com.alibaba.sdk.android.oss.common.utils;
9 |
10 | public interface ServiceConstants {
11 |
12 | public static final String DEFAULT_ENCODING = "utf-8";
13 |
14 | public static final String RESOURCE_NAME_COMMON = "common";
15 | }
16 |
--------------------------------------------------------------------------------
/oss-android-sdk/src/main/java/com/alibaba/sdk/android/oss/common/utils/VersionInfoUtils.java:
--------------------------------------------------------------------------------
1 | /**
2 | * Copyright (C) Alibaba Cloud Computing, 2015
3 | * All rights reserved.
4 | *
5 | * 版权所有 (C)阿里巴巴云计算,2015
6 | */
7 |
8 | package com.alibaba.sdk.android.oss.common.utils;
9 |
10 | import android.os.Build;
11 |
12 | import com.alibaba.sdk.android.oss.common.OSSConstants;
13 | import com.alibaba.sdk.android.oss.common.OSSLog;
14 |
15 | public class VersionInfoUtils {
16 | private static String userAgent = null;
17 |
18 | /*
19 | * UA sample : aliyun-sdk-java/2.0.5(Windows 7/6.1/amd64;1.7.0_55)/oss-import
20 | */
21 | public static String getUserAgent(String customInfo) {
22 | if (OSSUtils.isEmptyString(userAgent)) {
23 | userAgent = "aliyun-sdk-android/" + getVersion() + getSystemInfo();
24 | }
25 |
26 | if (OSSUtils.isEmptyString(customInfo)) {
27 | return userAgent;
28 | } else {
29 | return userAgent + "/" + customInfo;
30 | }
31 | }
32 |
33 | public static String getVersion() {
34 | return OSSConstants.SDK_VERSION;
35 | }
36 |
37 |
38 | /**
39 | * 获取系统+用户自定义的UA值,添加至最后位置
40 | *
41 | * @return
42 | */
43 | private static String getSystemInfo() {
44 | StringBuilder customUA = new StringBuilder();
45 | customUA.append("(");
46 | customUA.append(System.getProperty("os.name"));
47 | customUA.append("/Android " + Build.VERSION.RELEASE);
48 | customUA.append("/");
49 | //build may has chinese
50 | customUA.append(HttpUtil.urlEncode(Build.MODEL, OSSConstants.DEFAULT_CHARSET_NAME) + ";" + HttpUtil.urlEncode(Build.ID, OSSConstants.DEFAULT_CHARSET_NAME));
51 | customUA.append(")");
52 | String ua = customUA.toString();
53 | OSSLog.logDebug("user agent : " + ua);
54 | if (OSSUtils.isEmptyString(ua)) {
55 | String propertyUA = System.getProperty("http.agent");
56 | ua = propertyUA.replaceAll("[^\\p{ASCII}]", "?");
57 | }
58 | return ua;
59 | }
60 | }
61 |
--------------------------------------------------------------------------------
/oss-android-sdk/src/main/java/com/alibaba/sdk/android/oss/exception/InconsistentException.java:
--------------------------------------------------------------------------------
1 | package com.alibaba.sdk.android.oss.exception;
2 |
3 | import java.io.IOException;
4 |
5 | /**
6 | * Created by jingdan on 2017/11/29.
7 | */
8 |
9 | public class InconsistentException extends IOException {
10 |
11 | private Long clientChecksum;
12 | private Long serverChecksum;
13 | private String requestId;
14 |
15 | public InconsistentException(Long clientChecksum, Long serverChecksum, String requestId) {
16 | super();
17 | this.clientChecksum = clientChecksum;
18 | this.serverChecksum = serverChecksum;
19 | this.requestId = requestId;
20 | }
21 |
22 | @Override
23 | public String getMessage() {
24 | return "InconsistentException: inconsistent object"
25 | + "\n[RequestId]: " + requestId
26 | + "\n[ClientChecksum]: " + clientChecksum
27 | + "\n[ServerChecksum]: " + serverChecksum;
28 | }
29 | }
30 |
--------------------------------------------------------------------------------
/oss-android-sdk/src/main/java/com/alibaba/sdk/android/oss/internal/CheckCRC64DownloadInputStream.java:
--------------------------------------------------------------------------------
1 | package com.alibaba.sdk.android.oss.internal;
2 |
3 | import com.alibaba.sdk.android.oss.common.utils.OSSUtils;
4 |
5 | import java.io.IOException;
6 | import java.io.InputStream;
7 | import java.util.zip.CheckedInputStream;
8 | import java.util.zip.Checksum;
9 |
10 | /**
11 | * Created by jingdan on 2017/11/29.
12 | */
13 |
14 | public class CheckCRC64DownloadInputStream extends CheckedInputStream {
15 |
16 | private long mTotalBytesRead;
17 | private long mTotalLength;
18 | private long mServerCRC64;
19 | private String mRequestId;
20 | private long mClientCRC64;
21 |
22 | /**
23 | * Constructs a new {@code CheckedInputStream} on {@code InputStream}
24 | * {@code is}. The checksum will be calculated using the algorithm
25 | * implemented by {@code csum}.
26 | *
27 | * Warning: passing a null source creates an invalid
28 | * {@code CheckedInputStream}. All operations on such a stream will fail.
29 | *
30 | * @param is the input stream to calculate checksum from.
31 | * @param csum
32 | */
33 | public CheckCRC64DownloadInputStream(InputStream is, Checksum csum, long total, long serverCRC64, String requestId) {
34 | super(is, csum);
35 | this.mTotalLength = total;
36 | this.mServerCRC64 = serverCRC64;
37 | this.mRequestId = requestId;
38 | }
39 |
40 | @Override
41 | public int read() throws IOException {
42 | int read = super.read();
43 | checkCRC64(read);
44 | return read;
45 | }
46 |
47 | @Override
48 | public int read(byte[] buffer, int byteOffset, int byteCount) throws IOException {
49 | int read = super.read(buffer, byteOffset, byteCount);
50 | checkCRC64(read);
51 | return read;
52 | }
53 |
54 | private void checkCRC64(int byteRead) throws IOException {
55 | mTotalBytesRead += byteRead;
56 | if (mTotalBytesRead >= mTotalLength) {
57 | this.mClientCRC64 = getChecksum().getValue();
58 | OSSUtils.checkChecksum(mClientCRC64, mServerCRC64, mRequestId);
59 | }
60 | }
61 |
62 | public long getClientCRC64() {
63 | return mClientCRC64;
64 | }
65 | }
66 |
--------------------------------------------------------------------------------
/oss-android-sdk/src/main/java/com/alibaba/sdk/android/oss/internal/HttpMessage.java:
--------------------------------------------------------------------------------
1 | package com.alibaba.sdk.android.oss.internal;
2 |
3 | import com.alibaba.sdk.android.oss.common.utils.CaseInsensitiveHashMap;
4 |
5 | import java.io.IOException;
6 | import java.io.InputStream;
7 | import java.util.HashMap;
8 | import java.util.Map;
9 |
10 | /**
11 | * Created by jingdan on 2017/11/27.
12 | */
13 |
14 | abstract class HttpMessage {
15 | private Map
38 | * OSS will stamp the MD5 value of the part content in ETag header.
39 | * This is for the integrity check to make sure the data is transferred successfully.
40 | * It's strongly recommended to calculate the MD5 value locally and compare with this value.
41 | * If it does not match, re-upload the data.
42 | *
53 | * OSS will stamp the MD5 value of the part content in ETag header.
54 | * This is for the integrity check to make sure the data is transferred successfully.
55 | * It's strongly recommended to calculate the MD5 value locally and compare with this value.
56 | * If it does not match, re-upload the data.
57 | *