diff --git a/library/src/androidTest/java/com/qiniu/android/common/CollectConfigTest.java b/library/src/androidTest/java/com/qiniu/android/common/CollectConfigTest.java index fe9bfcd59..97de62444 100644 --- a/library/src/androidTest/java/com/qiniu/android/common/CollectConfigTest.java +++ b/library/src/androidTest/java/com/qiniu/android/common/CollectConfigTest.java @@ -20,7 +20,7 @@ public void testQuick(){ @Test public void testNormal(){ Config.normal(); - assertTrue(Config.uploadThreshold == 4*1024); + assertTrue(Config.uploadThreshold == 16*1024); assertTrue(Config.interval == 10); } diff --git a/library/src/main/java/com/qiniu/android/bigdata/Configuration.java b/library/src/main/java/com/qiniu/android/bigdata/Configuration.java index 42e1a29b5..4f8b458cb 100644 --- a/library/src/main/java/com/qiniu/android/bigdata/Configuration.java +++ b/library/src/main/java/com/qiniu/android/bigdata/Configuration.java @@ -4,11 +4,20 @@ /** * Created by long on 2017/7/25. + * + * @hidden */ public final class Configuration implements Cloneable { + + /** + * pipelineHost + */ public String pipelineHost = "https://pipeline.qiniu.com"; + /** + * 请求 proxy + */ public ProxyConfiguration proxy; @@ -22,6 +31,18 @@ public final class Configuration implements Cloneable { */ public int responseTimeout = 10; + /** + * 构造函数 + */ + public Configuration() { + } + + /** + * Configuration copy + * + * @param config 待 copy 对象 + * @return Configuration + */ public static Configuration copy(Configuration config) { if (config == null) { return new Configuration(); @@ -33,6 +54,11 @@ public static Configuration copy(Configuration config) { } } + /** + * Configuration clone + * + * @return Configuration + */ public Configuration clone() throws CloneNotSupportedException { return (Configuration) super.clone(); } diff --git a/library/src/main/java/com/qiniu/android/bigdata/client/Client.java b/library/src/main/java/com/qiniu/android/bigdata/client/Client.java index db378a2ae..b10cd4aae 100644 --- a/library/src/main/java/com/qiniu/android/bigdata/client/Client.java +++ b/library/src/main/java/com/qiniu/android/bigdata/client/Client.java @@ -41,19 +41,49 @@ /** * Created by bailong on 15/11/12. + * + * @hidden */ public final class Client { + /** + * HTTP 请求头:Content-Type + */ public static final String ContentTypeHeader = "Content-Type"; + + /** + * HTTP 请求默认的 MimeType + */ public static final String DefaultMime = "application/octet-stream"; + + /** + * HTTP 请求 Json 的 MimeType + */ public static final String JsonMime = "application/json"; + + /** + * HTTP 请求 FormMime 的 MimeType + */ public static final String FormMime = "application/x-www-form-urlencoded"; + private final UrlConverter converter; private OkHttpClient httpClient; + /** + * 构造方法 + */ public Client() { this(null, 10, 30, null, null); } + /** + * 构造函数 + * + * @param proxy 请求代理 + * @param connectTimeout 请求建立连接超时时间 + * @param responseTimeout 请求接收数据超时时间 + * @param converter 请求 Url 拦截器 + * @param dns 请求的 Dns 解析器 + */ public Client(ProxyConfiguration proxy, int connectTimeout, int responseTimeout, UrlConverter converter, final Dns dns) { this.converter = converter; OkHttpClient.Builder builder = new OkHttpClient.Builder(); @@ -71,9 +101,9 @@ public List lookup(String hostname) throws UnknownHostException { List networkAddressList = DnsPrefetcher.getInstance().getInetAddressByHost(hostname); if (networkAddressList != null && networkAddressList.size() > 0) { List inetAddressList = new ArrayList<>(); - for (IDnsNetworkAddress networkAddress : networkAddressList){ + for (IDnsNetworkAddress networkAddress : networkAddressList) { InetAddress address = null; - if (networkAddress.getIpValue() != null && (address = InetAddress.getByName(networkAddress.getIpValue())) != null){ + if (networkAddress.getIpValue() != null && (address = InetAddress.getByName(networkAddress.getIpValue())) != null) { inetAddressList.add(address); } } @@ -210,6 +240,15 @@ public void run() { }); } + /** + * 异步请求 + * + * @param requestBuilder 请求构造器 + * @param headers 请求头 + * @param upToken 上传 Token + * @param totalSize 请求体大小 + * @param complete 结束回调 + */ public void asyncSend(final Request.Builder requestBuilder, StringMap headers, final UpToken upToken, final long totalSize, final CompletionHandler complete) { if (headers != null) { @@ -259,6 +298,18 @@ public void onResponse(Call call, okhttp3.Response response) throws IOException }); } + /** + * 异步 POST 请求 + * + * @param url 请求 url + * @param body 请求 body + * @param headers 请求 header + * @param upToken 上传 token + * @param totalSize 请求总大小 + * @param progressHandler 请求进度回调 + * @param completionHandler 结束回调 + * @param c 取消回调 + */ public void asyncPost(String url, byte[] body, StringMap headers, final UpToken upToken, final long totalSize, ProgressHandler progressHandler, @@ -266,6 +317,20 @@ public void asyncPost(String url, byte[] body, asyncPost(url, body, 0, body.length, headers, upToken, totalSize, progressHandler, completionHandler, c); } + /** + * 异步 POST 请求 + * + * @param url 请求 Url + * @param body 请求体 + * @param offset 请求体偏移量 + * @param size 请求体大小 + * @param headers 请求 Header + * @param upToken 上传 Token + * @param totalSize 请求体总大小 + * @param progressHandler 进度回调 + * @param completionHandler 完成回调 + * @param c 取消回调 + */ public void asyncPost(String url, byte[] body, int offset, int size, StringMap headers, final UpToken upToken, final long totalSize, ProgressHandler progressHandler, @@ -295,6 +360,16 @@ public void asyncPost(String url, byte[] body, int offset, int size, asyncSend(requestBuilder, headers, upToken, totalSize, completionHandler); } + /** + * 异步表单请求 + * + * @param url 请求 Url + * @param args 请求参数 + * @param upToken 上传的 Token + * @param progressHandler 进度回调 + * @param completionHandler 完成回答 + * @param c 取消回调 + */ public void asyncMultipartPost(String url, PostArgs args, final UpToken upToken, @@ -343,12 +418,27 @@ public void accept(String key, Object value) { asyncSend(requestBuilder, null, upToken, totalSize, completionHandler); } + /** + * 异步 GET 请求 + * + * @param url 请求 Url + * @param headers 请求 Header + * @param upToken 上传的 Token + * @param completionHandler 请求完成回调 + */ public void asyncGet(String url, StringMap headers, final UpToken upToken, CompletionHandler completionHandler) { Request.Builder requestBuilder = new Request.Builder().get().url(url); asyncSend(requestBuilder, headers, upToken, 0, completionHandler); } + /** + * 同步 GET 请求 + * + * @param url 请求 Url + * @param headers 请求 Header + * @return ResponseInfo + */ public ResponseInfo syncGet(String url, StringMap headers) { Request.Builder requestBuilder = new Request.Builder().get().url(url); return send(requestBuilder, headers); @@ -379,8 +469,15 @@ public void accept(String key, Object value) { return buildResponseInfo(res, tag.ip, tag.duration, null, 0); } - public ResponseInfo syncMultipartPost(String url, PostArgs args, - final UpToken upToken) { + /** + * 同步表单请求 + * + * @param url 请求 Url + * @param args 请求参数 + * @param upToken 上传 Token + * @return ResponseInfo + */ + public ResponseInfo syncMultipartPost(String url, PostArgs args, final UpToken upToken) { RequestBody file; long totalSize; if (args.file != null) { @@ -414,6 +511,15 @@ public void accept(String key, Object value) { return syncSend(requestBuilder, null, upToken, totalSize); } + /** + * 同步请求 + * + * @param requestBuilder 请求构造器 + * @param headers 请求 Header + * @param upToken 上传的 Token + * @param totalSize 请求体大小 + * @return ResponseInfo + */ public ResponseInfo syncSend(final Request.Builder requestBuilder, StringMap headers, final UpToken upToken, final long totalSize) { if (headers != null) { diff --git a/library/src/main/java/com/qiniu/android/bigdata/client/CompletionHandler.java b/library/src/main/java/com/qiniu/android/bigdata/client/CompletionHandler.java index 9f976b747..85d010203 100644 --- a/library/src/main/java/com/qiniu/android/bigdata/client/CompletionHandler.java +++ b/library/src/main/java/com/qiniu/android/bigdata/client/CompletionHandler.java @@ -6,6 +6,8 @@ /** * 定义请求完成后续动作的处理接口 + * + * @hidden */ public interface CompletionHandler { /** diff --git a/library/src/main/java/com/qiniu/android/bigdata/client/PostArgs.java b/library/src/main/java/com/qiniu/android/bigdata/client/PostArgs.java index 5486dd304..8a7020c2c 100644 --- a/library/src/main/java/com/qiniu/android/bigdata/client/PostArgs.java +++ b/library/src/main/java/com/qiniu/android/bigdata/client/PostArgs.java @@ -6,6 +6,8 @@ /** * 定义请求参数列表 + * + * @hidden */ public final class PostArgs { /** @@ -29,4 +31,10 @@ public final class PostArgs { */ public String mimeType; + /** + * 构造函数 + */ + public PostArgs() { + } + } diff --git a/library/src/main/java/com/qiniu/android/bigdata/pipeline/Pipeline.java b/library/src/main/java/com/qiniu/android/bigdata/pipeline/Pipeline.java index 9ad6fec10..366c8f41d 100644 --- a/library/src/main/java/com/qiniu/android/bigdata/pipeline/Pipeline.java +++ b/library/src/main/java/com/qiniu/android/bigdata/pipeline/Pipeline.java @@ -14,46 +14,104 @@ /** * Created by long on 2017/7/25. + * + * @hidden */ - public final class Pipeline { private static final String HTTPHeaderAuthorization = "Authorization"; private static final String TEXT_PLAIN = "text/plain"; private final Configuration config; private final Client client; + /** + * 构造函数 + * + * @param config config + */ public Pipeline(Configuration config) { this.config = Configuration.copy(config); this.client = new Client(this.config.proxy, this.config.connectTimeout, this.config.responseTimeout, null, null); } + /** + * pump + * + * @param repo repo + * @param data data + * @param token token + * @param handler handler + * @param V + */ public void pump(String repo, Map data, String token, PumpCompleteHandler handler) { StringBuilder b = new StringBuilder(); Points.formatPoint(data, b); send(repo, b, token, handler); } + /** + * pump + * + * @param repo repo + * @param data data + * @param token token + * @param handler handler + */ public void pump(String repo, Object data, String token, PumpCompleteHandler handler) { StringBuilder b = new StringBuilder(); Points.formatPoint(data, b); send(repo, b, token, handler); } + /** + * pumpMulti + * + * @param repo repo + * @param data data + * @param token token + * @param handler handler + * @param V + */ public void pumpMulti(String repo, Map[] data, String token, PumpCompleteHandler handler) { StringBuilder b = Points.formatPoints(data); send(repo, b, token, handler); } + /** + * pumpMultiObjects + * + * @param repo repo + * @param data data + * @param token token + * @param handler handler + */ public void pumpMultiObjects(String repo, Object[] data, String token, PumpCompleteHandler handler) { StringBuilder b = Points.formatPoints(data); send(repo, b, token, handler); } + /** + * pumpMultiObjects + * + * @param repo repo + * @param data data + * @param token token + * @param handler handler + * @param V + */ public void pumpMultiObjects(String repo, List data, String token, PumpCompleteHandler handler) { StringBuilder b = Points.formatPointsObjects(data); send(repo, b, token, handler); } + /** + * pumpMulti + * + * @param repo repo + * @param data data + * @param token token + * @param handler handler + * @param V + */ public void pumpMulti(String repo, List> data, String token, PumpCompleteHandler handler) { StringBuilder b = Points.formatPoints(data); send(repo, b, token, handler); @@ -86,7 +144,18 @@ private String url(String repo) { return config.pipelineHost + "/v2/repos/" + repo + "/data"; } + /** + * Pump 完成回调 + * + * @hidden + */ public interface PumpCompleteHandler { + + /** + * Pump 完成回调 + * + * @param info info + */ void complete(ResponseInfo info); } diff --git a/library/src/main/java/com/qiniu/android/bigdata/pipeline/Points.java b/library/src/main/java/com/qiniu/android/bigdata/pipeline/Points.java index c7099e892..147d69269 100644 --- a/library/src/main/java/com/qiniu/android/bigdata/pipeline/Points.java +++ b/library/src/main/java/com/qiniu/android/bigdata/pipeline/Points.java @@ -17,8 +17,14 @@ /** * 数据点 + * + * @hidden */ public final class Points { + + private Points() { + } + private static String buildString(Object v) { if (v == null) { return null; @@ -41,6 +47,14 @@ private static String buildString(Object v) { return str; } + /** + * formatPoint + * + * @param data data + * @param builder builder + * @return StringBuilder + * @param V + */ public static StringBuilder formatPoint(Map data, StringBuilder builder) { for (Map.Entry it : data.entrySet()) { builder.append(it.getKey()).append("=").append(buildString(it.getValue())).append("\t"); @@ -49,6 +63,13 @@ public static StringBuilder formatPoint(Map data, StringBuilder b return builder; } + /** + * formatPoint + * + * @param obj obj + * @param builder builder + * @return StringBuilder + */ public static StringBuilder formatPoint(Object obj, StringBuilder builder) { Class cls = obj.getClass(); java.lang.reflect.Field[] fields = cls.getDeclaredFields(); @@ -67,6 +88,13 @@ public static StringBuilder formatPoint(Object obj, StringBuilder builder) { return formatPoint(map, builder); } + /** + * formatPoint + * + * @param data data + * @return StringBuilder + * @param V + */ public static StringBuilder formatPoints(Map[] data) { StringBuilder builder = new StringBuilder(); for (Map aData : data) { @@ -75,7 +103,12 @@ public static StringBuilder formatPoints(Map[] data) { return builder; } - + /** + * formatPoint + * + * @param data data + * @return StringBuilder + */ public static StringBuilder formatPoints(Object[] data) { StringBuilder builder = new StringBuilder(); for (Object aData : data) { @@ -84,6 +117,13 @@ public static StringBuilder formatPoints(Object[] data) { return builder; } + /** + * formatPoints + * + * @param data data + * @return StringBuilder + * @param V + */ public static StringBuilder formatPoints(List> data) { StringBuilder builder = new StringBuilder(); for (Map aData : data) { @@ -93,6 +133,13 @@ public static StringBuilder formatPoints(List> data) { } + /** + * formatPointsObjects + * + * @param data data + * @return StringBuilder + * @param V + */ public static StringBuilder formatPointsObjects(List data) { StringBuilder builder = new StringBuilder(); for (Object aData : data) { diff --git a/library/src/main/java/com/qiniu/android/collect/ReportConfig.java b/library/src/main/java/com/qiniu/android/collect/ReportConfig.java index f41cad1a5..61b66459b 100644 --- a/library/src/main/java/com/qiniu/android/collect/ReportConfig.java +++ b/library/src/main/java/com/qiniu/android/collect/ReportConfig.java @@ -3,6 +3,9 @@ import com.qiniu.android.common.Config; import com.qiniu.android.utils.Utils; +/** + * 记录配置 + */ public class ReportConfig { /** @@ -16,7 +19,7 @@ public class ReportConfig { public double interval; /** - * 记录文件大于 uploadThreshold 会触发上传,单位:字节 默认为16 * 1024 + * 记录文件大于 uploadThreshold 会触发上传,单位:字节 默认为16 * 1024 */ public long uploadThreshold; @@ -42,7 +45,7 @@ public class ReportConfig { private static ReportConfig instance = new ReportConfig(); - private ReportConfig(){ + private ReportConfig() { this.isReportEnable = Config.isRecord; this.interval = Config.interval; this.serverURL = Config.upLogURL; @@ -56,7 +59,12 @@ private ReportConfig(){ this.timeoutInterval = 10; } - public static ReportConfig getInstance(){ + /** + * 获取配置单例 + * + * @return 配置单例 + */ + public static ReportConfig getInstance() { return instance; } } diff --git a/library/src/main/java/com/qiniu/android/collect/ReportItem.java b/library/src/main/java/com/qiniu/android/collect/ReportItem.java index 97a2ba372..714851604 100644 --- a/library/src/main/java/com/qiniu/android/collect/ReportItem.java +++ b/library/src/main/java/com/qiniu/android/collect/ReportItem.java @@ -6,14 +6,29 @@ import java.util.HashMap; +/** + * 记录信息 + * + * @hidden + */ public class ReportItem { private HashMap keyValues = new HashMap<>(); - public ReportItem(){} + /** + * 构造函数 + */ + public ReportItem() { + } - public void setReport(Object value, String key){ - if (key == null || value == null){ + /** + * 添加记录内容 + * + * @param value 记录的内容 + * @param key 记录的 key + */ + public void setReport(Object value, String key) { + if (key == null || value == null) { return; } if (value instanceof String && ((String) value).length() > 1024) { @@ -22,161 +37,530 @@ public void setReport(Object value, String key){ keyValues.put(key, value); } - public void removeReportValue(String key){ - if (key == null){ + /** + * 移除记录 + * + * @param key 待移除记录的 key + */ + public void removeReportValue(String key) { + if (key == null) { return; } keyValues.remove(key); } - public String toJson(){ + /** + * 转 json + * + * @return Json 数据 + */ + public String toJson() { String jsonString = "{}"; - if (keyValues == null || keyValues.size() == 0){ + if (keyValues == null || keyValues.size() == 0) { return jsonString; } jsonString = new JSONObject(keyValues).toString(); return jsonString; } - // 日志类型 + /** + * request 记录类型 + */ public static final String LogTypeRequest = "request"; + + /** + * block 记录类型 + */ public static final String LogTypeBlock = "block"; + + /** + * quality 记录类型 + */ public static final String LogTypeQuality = "quality"; // 请求信息打点⽇志 + /** + * 请求记录 key:记录类型 + */ public static final String RequestKeyLogType = "log_type"; + + /** + * 请求记录 key:请求时间 + */ public static final String RequestKeyUpTime = "up_time"; + + /** + * 请求记录 key:请求状态码 + */ public static final String RequestKeyStatusCode = "status_code"; + + /** + * 请求记录 key:请求 ID + */ public static final String RequestKeyRequestId = "req_id"; + + /** + * 请求记录 key:请求域名 + */ public static final String RequestKeyHost = "host"; + + /** + * 请求记录 key:请求的 HTTP 版本 + */ public static final String RequestKeyHttpVersion = "http_version"; + + /** + * 请求记录 key:请求的服务端地址 + */ public static final String RequestKeyRemoteIp = "remote_ip"; + + /** + * 请求记录 key:请求的端口号 + */ public static final String RequestKeyPort = "port"; + + /** + * 请求记录 key:上传的 bucket + */ public static final String RequestKeyTargetBucket = "target_bucket"; + + /** + * 请求记录 key:上传保存的 key + */ public static final String RequestKeyTargetKey = "target_key"; + + /** + * 请求记录 key:请求总耗时 + */ public static final String RequestKeyTotalElapsedTime = "total_elapsed_time"; + + /** + * 请求记录 key:dns 耗时 + */ public static final String RequestKeyDnsElapsedTime = "dns_elapsed_time"; + + /** + * 请求记录 key:请求建立连接耗时 + */ public static final String RequestKeyConnectElapsedTime = "connect_elapsed_time"; + + /** + * 请求记录 key:请求 tls 耗时 + */ public static final String RequestKeyTLSConnectElapsedTime = "tls_connect_elapsed_time"; + + /** + * 请求记录 key:请求耗时 + */ public static final String RequestKeyRequestElapsedTime = "request_elapsed_time"; + + /** + * 请求记录 key:等待响应耗时 + */ public static final String RequestKeyWaitElapsedTime = "wait_elapsed_time"; + + /** + * 请求记录 key:响应耗时 + */ public static final String RequestKeyResponseElapsedTime = "response_elapsed_time"; + + /** + * 请求记录 key:上传文件偏移量 + */ public static final String RequestKeyFileOffset = "file_offset"; + + /** + * 请求记录 key:请求发送大小 + */ public static final String RequestKeyBytesSent = "bytes_sent"; + + /** + * 请求记录 key:请求大小 + */ public static final String RequestKeyBytesTotal = "bytes_total"; + + /** + * 请求记录 key:pid + */ public static final String RequestKeyPid = "pid"; + + /** + * 请求记录 key:tid + */ public static final String RequestKeyTid = "tid"; + + /** + * 请求记录 key:文件上传的目标区域 + */ public static final String RequestKeyTargetRegionId = "target_region_id"; + + /** + * 请求记录 key:当前上传的区域 + */ public static final String RequestKeyCurrentRegionId = "current_region_id"; + + /** + * 请求记录 key:请求错误类型 + */ public static final String RequestKeyErrorType = "error_type"; + + /** + * 请求记录 key:请求错误信息 + */ public static final String RequestKeyErrorDescription = "error_description"; + + /** + * 请求记录 key:上传类型 + */ public static final String RequestKeyUpType = "up_type"; + + /** + * 请求记录 key:操作系统 + */ public static final String RequestKeyOsName = "os_name"; + + /** + * 请求记录 key:操作系统版本 + */ public static final String RequestKeyOsVersion = "os_version"; + + /** + * 请求记录 key:SDK 名称 + */ public static final String RequestKeySDKName = "sdk_name"; + + /** + * 请求记录 key:SDK 版本 + */ public static final String RequestKeySDKVersion = "sdk_version"; + + /** + * 请求记录 key:客户端时间 + */ public static final String RequestKeyClientTime = "client_time"; + + /** + * 请求记录 key:客户端类型 + */ public static final String RequestKeyHttpClient = "http_client"; + + /** + * 请求记录 key:客户端版本 + */ public static final String RequestKeyHttpClientVersion = "http_client_version"; + + /** + * 请求记录 key:网络类型 + */ public static final String RequestKeyNetworkType = "network_type"; + + /** + * 请求记录 key:信号强度 + */ public static final String RequestKeySignalStrength = "signal_strength"; + + /** + * 请求记录 key:上次 DNS 解析源 + */ public static final String RequestKeyPrefetchedDnsSource = "prefetched_dns_source"; + + /** + * 请求记录 key:DNS 解析源 + */ public static final String RequestKeyDnsSource = "dns_source"; + + /** + * 请求记录 key:DNS 解析错误信息 + */ public static final String RequestKeyDnsErrorMessage = "dns_error_message"; + + /** + * 请求记录 key:是否为劫持 + */ public static final String RequestKeyHijacking = "hijacking"; + + /** + * 请求记录 key:DNS 解析时间 + */ public static final String RequestKeyPrefetchedBefore = "prefetched_before"; + + /** + * 请求记录 key:DNS 解析错误信息 + */ public static final String RequestKeyPrefetchedErrorMessage = "prefetched_error_message"; + + /** + * 请求记录 key:网络情况 + */ public static final String RequestKeyNetworkMeasuring = "network_measuring"; + + /** + * 请求记录 key:网络上传速度 + */ public static final String RequestKeyPerceptiveSpeed = "perceptive_speed"; // 分块上传统计⽇志 + /** + * 分块记录 key:日志类型 + */ public static final String BlockKeyLogType = "log_type"; + + /** + * 分块记录 key:上传时间 + */ public static final String BlockKeyUpTime = "up_time"; + + /** + * 分块记录 key:目标 Bucket + */ public static final String BlockKeyTargetBucket = "target_bucket"; + + /** + * 分块记录 key:存储的 key + */ public static final String BlockKeyTargetKey = "target_key"; + + /** + * 分块记录 key:目标区域 ID + */ public static final String BlockKeyTargetRegionId = "target_region_id"; + + /** + * 分块记录 key:当前区域 ID + */ public static final String BlockKeyCurrentRegionId = "current_region_id"; + + /** + * 分块记录 key:总耗时 + */ public static final String BlockKeyTotalElapsedTime = "total_elapsed_time"; + + /** + * 分块记录 key:上传字节大小 + */ public static final String BlockKeyBytesSent = "bytes_sent"; + + /** + * 分块记录 key:断点续传开始偏移 + */ public static final String BlockKeyRecoveredFrom = "recovered_from"; + + /** + * 分块记录 key:上传文件大小 + */ public static final String BlockKeyFileSize = "file_size"; + + /** + * 分块记录 key:pid + */ public static final String BlockKeyPid = "pid"; + + /** + * 分块记录 key:tid + */ public static final String BlockKeyTid = "tid"; + + /** + * 分块记录 key:上传的 api + */ public static final String BlockKeyUpApiVersion = "up_api_version"; + + /** + * 分块记录 key:客户端时间 + */ public static final String BlockKeyClientTime = "client_time"; + + /** + * 分块记录 key:系统名称 + */ public static final String BlockKeyOsName = "os_name"; + + /** + * 分块记录 key:系统版本 + */ public static final String BlockKeyOsVersion = "os_version"; + + /** + * 分块记录 key:SDK 名 + */ public static final String BlockKeySDKName = "sdk_name"; + + /** + * 分块记录 key:SDK 版本 + */ public static final String BlockKeySDKVersion = "sdk_version"; + + /** + * 分块记录 key:上传速度 + */ public static final String BlockKeyPerceptiveSpeed = "perceptive_speed"; + + /** + * 分块记录 key:是否被劫持 + */ public static final String BlockKeyHijacking = "hijacking"; // 上传质量统计 + /** + * 上传质量记录 key:日志类型 + */ public static final String QualityKeyLogType = "log_type"; + + /** + * 上传质量记录 key:上传类型 + */ public static final String QualityKeyUpType = "up_type"; + + /** + * 上传质量记录 key:上传时间 + */ public static final String QualityKeyUpTime = "up_time"; + + /** + * 上传质量记录 key:上传结果 + */ public static final String QualityKeyResult = "result"; + + /** + * 上传质量记录 key:上传的目标 Bucket + */ public static final String QualityKeyTargetBucket = "target_bucket"; + + /** + * 上传质量记录 key:存储的 key + */ public static final String QualityKeyTargetKey = "target_key"; + + /** + * 上传质量记录 key:上传总耗时 + */ public static final String QualityKeyTotalElapsedTime = "total_elapsed_time"; + + /** + * 上传质量记录 key:上传中 UC query 耗时 + */ public static final String QualityKeyUcQueryElapsedTime = "uc_query_elapsed_time"; + + /** + * 上传质量记录 key:上传使用的请求数量 + */ public static final String QualityKeyRequestsCount = "requests_count"; + + /** + * 上传质量记录 key:上传使用的区域数量 + */ public static final String QualityKeyRegionsCount = "regions_count"; + + /** + * 上传质量记录 key:上传的文件大小 + */ public static final String QualityKeyFileSize = "file_size"; + + /** + * 上传质量记录 key:上传发送的字节数 + */ public static final String QualityKeyBytesSent = "bytes_sent"; + + /** + * 上传质量记录 key:cloud 类型 + */ public static final String QualityKeyCloudType = "cloud_type"; + + /** + * 上传质量记录 key:上传的错误类型 + */ public static final String QualityKeyErrorType = "error_type"; + + /** + * 上传质量记录 key:上传的错误信息 + */ public static final String QualityKeyErrorDescription = "error_description"; + + /** + * 上传质量记录 key:操作系统名称 + */ public static final String QualityKeyOsName = "os_name"; + + /** + * 上传质量记录 key:操作系统版本 + */ public static final String QualityKeyOsVersion = "os_version"; + + /** + * 上传质量记录 key:SDK 名 + */ public static final String QualityKeySDKName = "sdk_name"; + + /** + * 上传质量记录 key:SDK 版本 + */ public static final String QualityKeySDKVersion = "sdk_version"; + + /** + * 上传质量记录 key:上传速度 + */ public static final String QualityKeyPerceptiveSpeed = "perceptive_speed"; + + /** + * 上传质量记录 key:是否劫持 + */ public static final String QualityKeyHijacking = "hijacking"; - public static String requestReportStatusCode(ResponseInfo responseInfo){ - if (responseInfo == null){ + /** + * 获取请求的状态码 + * + * @param responseInfo 请求响应 + * @return 请求的状态码 + */ + public static String requestReportStatusCode(ResponseInfo responseInfo) { + if (responseInfo == null) { return null; } else { return responseInfo.statusCode + ""; } } - public static String requestReportErrorType(ResponseInfo responseInfo){ - if (responseInfo == null){ + /** + * 获取请求错误类型 + * + * @param responseInfo 请求响应 + * @return 请求的错误类型 + */ + public static String requestReportErrorType(ResponseInfo responseInfo) { + if (responseInfo == null) { return "unknown_error"; } String errorType = null; if (responseInfo.statusCode > 199 && responseInfo.statusCode < 300) { - } else if (responseInfo.statusCode > 299){ + } else if (responseInfo.statusCode > 299) { errorType = "response_error"; - } else if (responseInfo.statusCode == ResponseInfo.NetworkError){ + } else if (responseInfo.statusCode == ResponseInfo.NetworkError) { errorType = "network_error"; - } else if (responseInfo.statusCode == ResponseInfo.TimedOut){ + } else if (responseInfo.statusCode == ResponseInfo.TimedOut) { errorType = "timeout"; - } else if (responseInfo.statusCode == ResponseInfo.UnknownHost){ + } else if (responseInfo.statusCode == ResponseInfo.UnknownHost) { errorType = "unknown_host"; - } else if (responseInfo.statusCode == ResponseInfo.CannotConnectToHost){ + } else if (responseInfo.statusCode == ResponseInfo.CannotConnectToHost) { errorType = "cannot_connect_to_host"; - } else if (responseInfo.statusCode == ResponseInfo.NetworkConnectionLost){ + } else if (responseInfo.statusCode == ResponseInfo.NetworkConnectionLost) { errorType = "transmission_error"; - } else if (responseInfo.statusCode == ResponseInfo.NetworkSSLError){ + } else if (responseInfo.statusCode == ResponseInfo.NetworkSSLError) { errorType = "ssl_error"; - } else if (responseInfo.statusCode == ResponseInfo.ParseError){ + } else if (responseInfo.statusCode == ResponseInfo.ParseError) { errorType = "parse_error"; - } else if (responseInfo.statusCode == ResponseInfo.MaliciousResponseError){ + } else if (responseInfo.statusCode == ResponseInfo.MaliciousResponseError) { errorType = "malicious_response"; - } else if (responseInfo.statusCode == ResponseInfo.Cancelled){ + } else if (responseInfo.statusCode == ResponseInfo.Cancelled) { errorType = "user_canceled"; - } else if (responseInfo.statusCode == ResponseInfo.LocalIOError){ + } else if (responseInfo.statusCode == ResponseInfo.LocalIOError) { errorType = "local_io_error"; - } else if (responseInfo.statusCode == ResponseInfo.NetworkProtocolError){ + } else if (responseInfo.statusCode == ResponseInfo.NetworkProtocolError) { errorType = "protocol_error"; - } else if (responseInfo.statusCode == ResponseInfo.NetworkSlow){ + } else if (responseInfo.statusCode == ResponseInfo.NetworkSlow) { errorType = "network_slow"; } else { errorType = "unknown_error"; @@ -184,8 +568,14 @@ public static String requestReportErrorType(ResponseInfo responseInfo){ return errorType; } - public static String qualityResult(ResponseInfo responseInfo){ - if (responseInfo == null){ + /** + * 获取上传的结果 + * + * @param responseInfo 请求响应 + * @return 上传的结果 + */ + public static String qualityResult(ResponseInfo responseInfo) { + if (responseInfo == null) { return "unknown_error"; } @@ -194,20 +584,20 @@ public static String qualityResult(ResponseInfo responseInfo){ if (responseInfo.statusCode > 199 && responseInfo.statusCode < 300) { result = "ok"; } else if (responseInfo.statusCode > 399 && - (responseInfo.statusCode < 500 || responseInfo.statusCode == 573 || responseInfo.statusCode == 579 || - responseInfo.statusCode == 608 || responseInfo.statusCode == 612 || responseInfo.statusCode == 614 || responseInfo.statusCode == 630 || responseInfo.statusCode == 631 || - responseInfo.statusCode == 701)) { + (responseInfo.statusCode < 500 || responseInfo.statusCode == 573 || responseInfo.statusCode == 579 || + responseInfo.statusCode == 608 || responseInfo.statusCode == 612 || responseInfo.statusCode == 614 || responseInfo.statusCode == 630 || responseInfo.statusCode == 631 || + responseInfo.statusCode == 701)) { result = "bad_request"; - } else if (responseInfo.statusCode == ResponseInfo.ZeroSizeFile){ + } else if (responseInfo.statusCode == ResponseInfo.ZeroSizeFile) { result = "zero_size_file"; - } else if (responseInfo.statusCode == ResponseInfo.InvalidFile){ + } else if (responseInfo.statusCode == ResponseInfo.InvalidFile) { result = "invalid_file"; } else if (responseInfo.statusCode == ResponseInfo.InvalidToken - || responseInfo.statusCode == ResponseInfo.InvalidArgument){ + || responseInfo.statusCode == ResponseInfo.InvalidArgument) { result = "invalid_args"; } - if (result == null){ + if (result == null) { result = requestReportErrorType(responseInfo); } diff --git a/library/src/main/java/com/qiniu/android/collect/UploadInfoReporter.java b/library/src/main/java/com/qiniu/android/collect/UploadInfoReporter.java index 0c25a6019..e2d57f1c4 100644 --- a/library/src/main/java/com/qiniu/android/collect/UploadInfoReporter.java +++ b/library/src/main/java/com/qiniu/android/collect/UploadInfoReporter.java @@ -29,6 +29,11 @@ import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; +/** + * 记录上报 + * + * @hidden + */ public class UploadInfoReporter { private static final String DelayReportTransactionName = "com.qiniu.uplog"; private ReportConfig config = ReportConfig.getInstance(); @@ -50,10 +55,21 @@ public class UploadInfoReporter { private UploadInfoReporter() { } + /** + * 获取上报单例 + * + * @return 上报单例 + */ public static UploadInfoReporter getInstance() { return instance; } + /** + * 上报记录 + * + * @param reportItem 记录信息 + * @param tokenString Token + */ public synchronized void report(final ReportItem reportItem, final String tokenString) { if (!checkReportAvailable() || reportItem == null || tokenString == null || tokenString.length() == 0) { return; @@ -76,6 +92,9 @@ public void run() { }); } + /** + * 清理 + */ public void clean() { cleanRecorderFile(); cleanTempLogFile(); @@ -151,7 +170,7 @@ private void saveReportJsonString(final String jsonString) { private void reportToServerIfNeeded(final String tokenString) { boolean needToReport = false; long currentTime = Utils.currentSecondTimestamp(); - final long interval = (long)(config.interval * 60); + final long interval = (long) (config.interval * 60); if (recorderTempFile.exists()) { needToReport = true; } else if ((lastReportTime == 0 || (currentTime - lastReportTime) >= interval || recorderFile.length() > config.uploadThreshold) && diff --git a/library/src/main/java/com/qiniu/android/common/AutoZone.java b/library/src/main/java/com/qiniu/android/common/AutoZone.java index 21f958ac1..22d22fd8c 100644 --- a/library/src/main/java/com/qiniu/android/common/AutoZone.java +++ b/library/src/main/java/com/qiniu/android/common/AutoZone.java @@ -40,23 +40,50 @@ public final class AutoZone extends Zone { .setVersion("v1") .builder(); - //私有云可能改变ucServer + /** + * 构造函数 + */ + public AutoZone() { + } + + /** + * 配置 UC 域名,此 UC 域名用于根据上传 bucket 查询对应的区域。 + * 公有云不用配置 + * + * @param ucServer UC 域名 + */ public void setUcServer(String ucServer) { if (ucServer != null) { this.ucServers = new String[]{ucServer}; } } + /** + * 配置 UC 域名,此 UC 域名用于根据上传 bucket 查询对应的区域。 + * 公有云不用配置 + * + * @param ucServers UC 域名,可以是多个,多个会进行主备重试 + */ public void setUcServers(String[] ucServers) { if (ucServers != null && ucServers.length > 0) { this.ucServers = ucServers; } } + /** + * 配置默认区域,在使用 AutoZone 进行上传时,当根据 bucket 查询 Zone 信息失败时如果默认区域存在会尝试使用默认区域进行上传。 + * + * @param zones 默认区域,可以是多个 + */ public void setDefaultZones(FixedZone[] zones) { defaultZone = FixedZone.combineZones(zones); } + /** + * 获取 UC 域名列表 + * + * @return UC 域名列表 + */ public List getUcServerList() { if (ucServers != null && ucServers.length > 0) { ArrayList serverList = new ArrayList<>(); @@ -67,6 +94,9 @@ public List getUcServerList() { } } + /** + * 清除区域存储缓存 + */ public static void clearCache() { zoneCache.clearMemoryCache(); zoneCache.clearDiskCache(); @@ -106,7 +136,7 @@ public void preQuery(final UpToken token, final QueryHandler completeHandler) { UploadRegionRequestMetrics localMetrics = new UploadRegionRequestMetrics(null); localMetrics.start(); - final String cacheKey = makeCacheKey(token.index()) ; + final String cacheKey = makeCacheKey(token.index()); ZonesInfo zonesInfo = null; Cache.Object object = zoneCache.cacheForKey(cacheKey); @@ -197,7 +227,7 @@ private String makeCacheKey(String akAndBucket) { hosts.append(host).append(":"); } - return UrlSafeBase64.encodeToString(hosts+akAndBucket); + return UrlSafeBase64.encodeToString(hosts + akAndBucket); } private RequestTransaction createUploadRequestTransaction(UpToken token) { diff --git a/library/src/main/java/com/qiniu/android/common/Config.java b/library/src/main/java/com/qiniu/android/common/Config.java index dc02e3bca..592bc354c 100644 --- a/library/src/main/java/com/qiniu/android/common/Config.java +++ b/library/src/main/java/com/qiniu/android/common/Config.java @@ -6,10 +6,12 @@ * Created by Simon on 11/22/16. */ public final class Config { + /** * 上传信息收集文件的地址 只保留域名部分 eg:uplog.qbox.me */ public final static String upLogURL = "uplog.qbox.me"; + /** * 是否记录上传状态信息。 true 表示记录,false 表示不记录。 *

@@ -20,6 +22,7 @@ public final class Config { * 记录文件大小 大于 maxRecordFileSize 时, 则暂停记录信息。 */ public static boolean isRecord = true; + /** * 是否上传记录的上传状态信息。true 表示上传,false 表示不上传。 *

@@ -32,6 +35,7 @@ public final class Config { * 上传成功后,清空记录文件文件 */ public static boolean isUpload = true; + /** * 上传信息记录文件保存的目录, 绝对路径。 * 默认使用当前应用的缓存目录: getCacheDir() @@ -49,7 +53,7 @@ public final class Config { /** * 记录上传信息文件最大值,单位:字节。 - * + *

* 记录文件大于此值后暂停记录上传信息。 */ public static int maxRecordFileSize = 20 * 1024 * 1024; @@ -69,10 +73,27 @@ public final class Config { * preQuery host */ public static String preQueryHost00 = "uc.qiniuapi.com"; + + /** + * preQuery host + */ public static String preQueryHost01 = "kodo-config.qiniuapi.com"; + + /** + * preQuery host + */ public static String preQueryHost02 = "uc.qbox.me"; + + /** + * preQuery host + */ public static String preQueryHost03 = "api.qiniu.com"; + /** + * 获取 preQuery hosts + * + * @return preQuery hosts + */ public static String[] preQueryHosts() { return new String[]{preQueryHost00, preQueryHost01, preQueryHost02, preQueryHost03}; } @@ -85,8 +106,11 @@ public static void quick() { interval = 2; } + /** + * 标准设置 + */ public static void normal() { - uploadThreshold = 4 * 1024; + uploadThreshold = 16 * 1024; interval = 10; } @@ -97,4 +121,7 @@ public static void slow() { uploadThreshold = 150 * 1024; interval = 300; } + + private Config() { + } } diff --git a/library/src/main/java/com/qiniu/android/common/Constants.java b/library/src/main/java/com/qiniu/android/common/Constants.java index 98a7f5e60..88977b8de 100644 --- a/library/src/main/java/com/qiniu/android/common/Constants.java +++ b/library/src/main/java/com/qiniu/android/common/Constants.java @@ -1,8 +1,21 @@ package com.qiniu.android.common; +/** + * 常量定义 + */ public final class Constants { + + /** + * SDK 版本号 + */ public static final String VERSION = "8.7.0"; + /** + * UTF-8 编码 + */ public static final String UTF_8 = "utf-8"; + + private Constants() { + } } diff --git a/library/src/main/java/com/qiniu/android/common/FixedZone.java b/library/src/main/java/com/qiniu/android/common/FixedZone.java index 37e9716da..6ae125c07 100644 --- a/library/src/main/java/com/qiniu/android/common/FixedZone.java +++ b/library/src/main/java/com/qiniu/android/common/FixedZone.java @@ -89,6 +89,11 @@ public static FixedZone createWithRegionId(String regionId) { private ZonesInfo zonesInfo; + /** + * 获取 SDK 中使用的 zone,用于重试,外部不可使用 + * + * @return FixedZone + */ @Deprecated public static FixedZone localsZoneInfo() { FixedZone[] localsZone = new FixedZone[]{ @@ -105,6 +110,12 @@ public static FixedZone localsZoneInfo() { return zone; } + /** + * 把多个 Zone 合并成一个 Zone Group,重试时会依次切换不同 Zone 进行重试 + * + * @param zones zones + * @return Zone Group + */ public static FixedZone combineZones(FixedZone[] zones) { if (zones == null || zones.length == 0) { return null; @@ -121,20 +132,41 @@ public static FixedZone combineZones(FixedZone[] zones) { return new FixedZone(zonesInfo); } + /** + * 构造方法 + * + * @param zoneInfo zone 信息 + */ public FixedZone(ZoneInfo zoneInfo) { ArrayList zoneInfoList = new ArrayList<>(); zoneInfoList.add(zoneInfo); this.zonesInfo = new ZonesInfo(zoneInfoList); } + /** + * 构造方法 + * + * @param zonesInfo zones 信息 + */ public FixedZone(ZonesInfo zonesInfo) { this.zonesInfo = zonesInfo; } + /** + * 构造方法 + * + * @param upDomains 上传域名 + */ public FixedZone(String[] upDomains) { this(upDomains, null); } + /** + * 构造方法 + * + * @param upDomains 上传域名 + * @param regionId 区域 ID + */ public FixedZone(String[] upDomains, String regionId) { this(upDomains, null, regionId); } diff --git a/library/src/main/java/com/qiniu/android/common/Zone.java b/library/src/main/java/com/qiniu/android/common/Zone.java index 9b92e883b..c2e6bb3aa 100644 --- a/library/src/main/java/com/qiniu/android/common/Zone.java +++ b/library/src/main/java/com/qiniu/android/common/Zone.java @@ -9,11 +9,39 @@ */ public abstract class Zone { + /** + * 构造函数 + */ + protected Zone() { + } + + /** + * 根据上传 token 获取 zone + * + * @param token 上传 token + * @return 区域信息 + */ public abstract ZonesInfo getZonesInfo(UpToken token); + /** + * 根据上传 token 对区域进行预查询 + * + * @param token 上传 token + * @param completeHandler 预查询结束回调 + */ public abstract void preQuery(UpToken token, QueryHandler completeHandler); + /** + * 预查询结束回调 + */ public interface QueryHandler { + /** + * 预查询结束回调 + * + * @param code 状态码 + * @param responseInfo 查询响应 + * @param metrics 查询指标 + */ void complete(int code, ResponseInfo responseInfo, UploadRegionRequestMetrics metrics); } } diff --git a/library/src/main/java/com/qiniu/android/common/ZoneInfo.java b/library/src/main/java/com/qiniu/android/common/ZoneInfo.java index 9a3374b3c..2b51e55ab 100644 --- a/library/src/main/java/com/qiniu/android/common/ZoneInfo.java +++ b/library/src/main/java/com/qiniu/android/common/ZoneInfo.java @@ -15,32 +15,87 @@ /** * Created by jemy on 17/04/2017. */ - public class ZoneInfo implements Cloneable { - // 只允许内部使用 + /** + * 默认 io host + * 只允许内部使用 + * + * @hidden + */ public final static String SDKDefaultIOHost = "sdkDefaultIOHost"; + + /** + * 未知 region id + * + * @hidden + */ public final static String EmptyRegionId = "unknown"; private static int DOMAIN_FROZEN_SECONDS = 10 * 60; + /** + * 有效时间 + */ public final int ttl; + + /** + * 是否允许 HTTP/3 + */ public final boolean http3Enabled; + + /** + * 是否是 IPv6 + */ public final boolean ipv6; + + /** + * 主要域名 + */ public final List domains; + + /** + * 备用域名 + */ public final List old_domains; + /** + * regionId + */ public final String regionId; + + /** + * 所有域名 + */ public List allHosts; + + /** + * detailInfo + */ public JSONObject detailInfo; private final Date buildDate; + /** + * 构造函数 + * + * @param mainHosts 主要域名 + * @param regionId 区域 ID + * @return ZoneInfo + */ public static ZoneInfo buildInfo(List mainHosts, String regionId) { return buildInfo(mainHosts, null, regionId); } + /** + * 构造函数 + * + * @param mainHosts 主要域名 + * @param oldHosts 备用域名 + * @param regionId 区域 ID + * @return ZoneInfo + */ public static ZoneInfo buildInfo(List mainHosts, List oldHosts, String regionId) { @@ -98,9 +153,11 @@ private ZoneInfo(int ttl, } /** + * 构造函数 + * * @param obj Not allowed to be null - * @return - * @throws JSONException + * @return ZoneInfo + * @throws JSONException 异常 */ public static ZoneInfo buildFromJson(JSONObject obj) throws JSONException { if (obj == null) { @@ -169,10 +226,20 @@ public static ZoneInfo buildFromJson(JSONObject obj) throws JSONException { return zoneInfo; } + /** + * 获取区域 ID + * + * @return 区域 ID + */ public String getRegionId() { return regionId; } + /** + * 转字符串 + * + * @return 字符串 + */ @Override public String toString() { Map m = new HashMap(); @@ -181,6 +248,11 @@ public String toString() { return new JSONObject(m).toString(); } + /** + * 是否有效 + * + * @return 是否有效 + */ public boolean isValid() { if (buildDate == null) { return false; @@ -191,6 +263,12 @@ public boolean isValid() { return ttl > (currentTimestamp - buildTimestamp); } + /** + * clone + * + * @return Object + * @throws CloneNotSupportedException 异常 + */ @Override protected Object clone() throws CloneNotSupportedException { ZoneInfo info = new ZoneInfo(ttl, http3Enabled, ipv6, regionId, domains, old_domains, buildDate); @@ -198,13 +276,38 @@ protected Object clone() throws CloneNotSupportedException { return info; } + /** + * server group + */ @Deprecated public static class UploadServerGroup { + + /** + * 备注信息 + */ public final String info; + + /** + * 主要域名 + */ public final ArrayList main; + + /** + * 备用域名 + */ public final ArrayList backup; + + /** + * 所有域名 + */ public final ArrayList allHosts; + /** + * 构造函数 + * + * @param jsonObject json + * @return UploadServerGroup + */ public static UploadServerGroup buildInfoFromJson(JSONObject jsonObject) { if (jsonObject == null) { return null; @@ -243,6 +346,14 @@ public static UploadServerGroup buildInfoFromJson(JSONObject jsonObject) { return new UploadServerGroup(info, main, backup, allHosts); } + /** + * 构造函数 + * + * @param info 备注信息 + * @param main 主要域名 + * @param backup 备用域名 + * @param allHosts 所有域名 + */ public UploadServerGroup(String info, ArrayList main, ArrayList backup, diff --git a/library/src/main/java/com/qiniu/android/common/ZonesInfo.java b/library/src/main/java/com/qiniu/android/common/ZonesInfo.java index 087dc334f..0160aecb8 100644 --- a/library/src/main/java/com/qiniu/android/common/ZonesInfo.java +++ b/library/src/main/java/com/qiniu/android/common/ZonesInfo.java @@ -8,15 +8,26 @@ import java.util.ArrayList; import java.util.List; +/** + * ZonesInfo + */ public class ZonesInfo implements Cloneable, Cache.Object { // 临时 zone,不建议长期使用 private boolean isTemporary; + /** + * zonesInfo + */ public final ArrayList zonesInfo = new ArrayList<>(); private JSONObject jsonInfo; + /** + * 构造函数 + * + * @param jsonObject jsonObject + */ public ZonesInfo(JSONObject jsonObject) { if (jsonObject == null) { return; @@ -40,19 +51,41 @@ public ZonesInfo(JSONObject jsonObject) { } } + /** + * 构造函数 + * + * @param zonesInfo zonesInfo + */ public ZonesInfo(List zonesInfo) { this(zonesInfo, false); } + /** + * 构造函数,内部使用 + * + * @param zonesInfo zonesInfo + * @param isTemporary 是否临时对象 + */ public ZonesInfo(List zonesInfo, boolean isTemporary) { this(createJsonWithZoneInfoList(zonesInfo)); this.isTemporary = isTemporary; } + /** + * 构造函数 + * + * @param jsonObject json + * @return ZonesInfo + */ public static ZonesInfo createZonesInfo(JSONObject jsonObject) { return new ZonesInfo(jsonObject); } + /** + * 是否有效 + * + * @return 是否有效 + */ public boolean isValid() { if (zonesInfo == null || zonesInfo.isEmpty()) { return false; @@ -68,17 +101,31 @@ public boolean isValid() { return valid; } + /** + * 是否是临时对象 + * + * @return 是否是临时对象 + */ @Deprecated // 是否为临时 zone, 临时 zone,不建议长期使用 public boolean isTemporary() { return isTemporary; } + /** + * 转为临时对象 + */ @Deprecated public void toTemporary() { isTemporary = true; } + /** + * clone + * + * @return Object + * @throws CloneNotSupportedException 异常 + */ @Override protected Object clone() throws CloneNotSupportedException { ArrayList infos = new ArrayList<>(); @@ -92,6 +139,11 @@ protected Object clone() throws CloneNotSupportedException { return info; } + /** + * 转 json + * + * @return json + */ @Override public JSONObject toJson() { return jsonInfo; diff --git a/library/src/main/java/com/qiniu/android/http/CancellationHandler.java b/library/src/main/java/com/qiniu/android/http/CancellationHandler.java index 7f5bc6d05..8bacb8fbc 100644 --- a/library/src/main/java/com/qiniu/android/http/CancellationHandler.java +++ b/library/src/main/java/com/qiniu/android/http/CancellationHandler.java @@ -2,6 +2,9 @@ import java.io.IOException; +/** + * 取消对调定义 + */ public interface CancellationHandler { /** @@ -11,6 +14,15 @@ public interface CancellationHandler { */ boolean isCancelled(); + /** + * 取消异常 + */ class CancellationException extends IOException { + + /** + * 构造函数 + */ + public CancellationException() { + } } } diff --git a/library/src/main/java/com/qiniu/android/http/Headers.java b/library/src/main/java/com/qiniu/android/http/Headers.java index 2153c8dae..64a3bb86f 100644 --- a/library/src/main/java/com/qiniu/android/http/Headers.java +++ b/library/src/main/java/com/qiniu/android/http/Headers.java @@ -49,6 +49,8 @@ * whitespace. * *

Instances of this class are immutable. Use {@link Builder} to create instances. + * + * @hidden */ public final class Headers { private final String[] namesAndValues; @@ -73,6 +75,9 @@ private static String get(String[] namesAndValues, String name) { /** * Returns headers for the alternating header names and values. There must be an even number of * arguments, and they must alternate between header names and values. + * + * @param namesAndValues header + * @return Headers */ public static Headers of(String... namesAndValues) { if (namesAndValues == null) throw new NullPointerException("namesAndValues == null"); @@ -101,9 +106,11 @@ public static Headers of(String... namesAndValues) { } - /** * Returns headers for the header names and values in the {@link Map}. + * + * @param headers headers + * @return Headers */ public static Headers of(Map headers) { if (headers == null) throw new NullPointerException("headers == null"); @@ -128,7 +135,12 @@ public static Headers of(Map headers) { return new Headers(namesAndValues); } - /** Returns the last value corresponding to the specified field, or null. */ + /** + * Returns the last value corresponding to the specified field, or null. + * + * @param name head name + * @return head value + */ public String get(String name) { return get(namesAndValues, name); } @@ -136,27 +148,48 @@ public String get(String name) { /** * Returns the last value corresponding to the specified field parsed as an HTTP date, or null if * either the field is absent or cannot be parsed as a date. + * + * @param name head name + * @return Date */ public Date getDate(String name) { return HttpDate.parse(get(name)); } - /** Returns the number of field values. */ + /** + * Returns the number of field values. + * + * @return the number of field values. + */ public int size() { return namesAndValues.length / 2; } - /** Returns the field at {@code position}. */ + /** + * Returns the field at {@code position}. + * + * @param index index + * @return the field at {@code position}. + */ public String name(int index) { return namesAndValues[index * 2]; } - /** Returns the value at {@code index}. */ + /** + * Returns the value at {@code index}. + * + * @param index index + * @return the value at {@code index}. + */ public String value(int index) { return namesAndValues[index * 2 + 1]; } - /** Returns an immutable case-insensitive set of header names. */ + /** + * Returns an immutable case-insensitive set of header names. + * + * @return an immutable case-insensitive set of header names. + */ public Set names() { TreeSet result = new TreeSet<>(String.CASE_INSENSITIVE_ORDER); for (int i = 0, size = size(); i < size; i++) { @@ -165,7 +198,12 @@ public Set names() { return Collections.unmodifiableSet(result); } - /** Returns an immutable list of the header values for {@code name}. */ + /** + * Returns an immutable list of the header values for {@code name}. + * + * @param name head name + * @return an immutable list of the header values for {@code name}. + */ public List values(String name) { List result = null; for (int i = 0, size = size(); i < size; i++) { @@ -183,6 +221,8 @@ public List values(String name) { * Returns the number of bytes required to encode these headers using HTTP/1.1. This is also the * approximate size of HTTP/2 headers before they are compressed with HPACK. This value is * intended to be used as a metric: smaller headers are more efficient to encode and transmit. + * + * @return the number of bytes required to encode these headers using HTTP/1.1. */ public long byteCount() { // Each header name has 2 bytes of overhead for ': ' and every header value has 2 bytes of @@ -196,6 +236,11 @@ public long byteCount() { return result; } + /** + * newBuilder + * + * @return newBuilder + */ public Builder newBuilder() { Builder result = new Builder(); Collections.addAll(result.namesAndValues, namesAndValues); @@ -224,9 +269,11 @@ public Builder newBuilder() { * Content-Type: text/html * Content-Length: 050 * } - * * Applications that require semantically equal headers should convert them into a canonical form * before comparing them for equality. + * + * @param other other + * @return equals */ @Override public boolean equals(Object other) { @@ -234,11 +281,21 @@ public boolean equals(Object other) { && Arrays.equals(((Headers) other).namesAndValues, namesAndValues); } + /** + * hashCode + * + * @return hashCode + */ @Override public int hashCode() { return Arrays.hashCode(namesAndValues); } + /** + * toString + * + * @return toString + */ @Override public String toString() { StringBuilder result = new StringBuilder(); @@ -248,6 +305,11 @@ public String toString() { return result.toString(); } + /** + * toMultimap + * + * @return Map + */ public Map> toMultimap() { Map> result = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); for (int i = 0, size = size(); i < size; i++) { @@ -262,9 +324,20 @@ public Map> toMultimap() { return result; } + /** + * Builder + * + * @hidden + */ public static final class Builder { final List namesAndValues = new ArrayList<>(20); + /** + * 构造函数 + */ + public Builder() { + } + /** * Add a header line without any validation. Only appropriate for headers from the remote peer * or cache. @@ -282,7 +355,12 @@ Builder addLenient(String line) { } } - /** Add an header line containing a field name, a literal colon, and a value. */ + /** + * Add an header line containing a field name, a literal colon, and a value. + * + * @param line line + * @return Builder + */ public Builder add(String line) { int index = line.indexOf(":"); if (index == -1) { @@ -293,6 +371,10 @@ public Builder add(String line) { /** * Add a header with the specified name and value. Does validation of header names and values. + * + * @param name name + * @param value value + * @return Builder */ public Builder add(String name, String value) { checkNameAndValue(name, value); @@ -301,6 +383,9 @@ public Builder add(String name, String value) { /** * Adds all headers from an existing collection. + * + * @param headers headers + * @return Builder */ public Builder addAll(Headers headers) { int size = headers.size(); @@ -314,6 +399,10 @@ public Builder addAll(Headers headers) { /** * Add a field with the specified value without any validation. Only appropriate for headers * from the remote peer or cache. + * + * @param name name + * @param value value + * @return Builder */ Builder addLenient(String name, String value) { namesAndValues.add(name); @@ -321,6 +410,12 @@ Builder addLenient(String name, String value) { return this; } + /** + * removeAll + * + * @param name name + * @return Builder + */ public Builder removeAll(String name) { for (int i = 0; i < namesAndValues.size(); i += 2) { if (name.equalsIgnoreCase(namesAndValues.get(i))) { @@ -335,6 +430,10 @@ public Builder removeAll(String name) { /** * Set a field with the specified value. If the field is not found, it is added. If the field is * found, the existing values are replaced. + * + * @param name name + * @param value value + * @return Builder */ public Builder set(String name, String value) { checkNameAndValue(name, value); @@ -364,7 +463,12 @@ private void checkNameAndValue(String name, String value) { } } - /** Equivalent to {@code build().get(name)}, but potentially faster. */ + /** + * Equivalent to {@code build().get(name)}, but potentially faster. + * + * @param name name + * @return value + */ public String get(String name) { for (int i = namesAndValues.size() - 2; i >= 0; i -= 2) { if (name.equalsIgnoreCase(namesAndValues.get(i))) { @@ -374,6 +478,11 @@ public String get(String name) { return null; } + /** + * build + * + * @return Headers + */ public Headers build() { return new Headers(this); } diff --git a/library/src/main/java/com/qiniu/android/http/HttpDate.java b/library/src/main/java/com/qiniu/android/http/HttpDate.java index f592fda17..07a25434c 100644 --- a/library/src/main/java/com/qiniu/android/http/HttpDate.java +++ b/library/src/main/java/com/qiniu/android/http/HttpDate.java @@ -12,6 +12,8 @@ /** * Best-effort parser for HTTP dates. + * + * @hidden */ public final class HttpDate { @@ -61,6 +63,9 @@ protected DateFormat initialValue() { /** * Returns the date for {@code value}. Returns null if the value couldn't be parsed. + * + * @param value value + * @return Date */ public static Date parse(String value) { if (TextUtils.isEmpty(value)) { @@ -99,7 +104,12 @@ public static Date parse(String value) { return null; } - /** Returns the string for {@code value}. */ + /** + * Returns the string for {@code value}. + * + * @param value Date + * @return the string for {@code value}. + */ public static String format(Date value) { return STANDARD_DATE_FORMAT.get().format(value); } diff --git a/library/src/main/java/com/qiniu/android/http/ProxyConfiguration.java b/library/src/main/java/com/qiniu/android/http/ProxyConfiguration.java index da9d12845..fac127e20 100644 --- a/library/src/main/java/com/qiniu/android/http/ProxyConfiguration.java +++ b/library/src/main/java/com/qiniu/android/http/ProxyConfiguration.java @@ -13,17 +13,39 @@ */ public final class ProxyConfiguration { + /** + * hostAddress + */ public final String hostAddress; + + /** + * port + */ public final int port; + + /** + * user + */ public final String user; + + /** + * password + */ public final String password; + + /** + * type + */ public final Proxy.Type type; /** + * 构造函数 + * * @param hostAddress 服务器域名或IP,比如proxy.com, 192.168.1.1 * @param port 端口 * @param user 用户名,无则填null * @param password 用户密码,无则填null + * @param type proxy type */ public ProxyConfiguration(String hostAddress, int port, String user, String password, java.net.Proxy.Type type) { this.hostAddress = hostAddress; @@ -33,14 +55,30 @@ public ProxyConfiguration(String hostAddress, int port, String user, String pass this.type = type; } + /** + * 构造函数 + * + * @param hostAddress 服务器域名或IP,比如proxy.com, 192.168.1.1 + * @param port 端口 + */ public ProxyConfiguration(String hostAddress, int port) { this(hostAddress, port, null, null, Proxy.Type.HTTP); } + /** + * 获取 proxy + * + * @return proxy + */ public Proxy proxy() { return new Proxy(type, new InetSocketAddress(hostAddress, port)); } + /** + * 获取 authenticator + * + * @return Authenticator + */ public Authenticator authenticator() { return new Authenticator() { @Override diff --git a/library/src/main/java/com/qiniu/android/http/ResponseInfo.java b/library/src/main/java/com/qiniu/android/http/ResponseInfo.java index 780ac6802..cfd5538f6 100644 --- a/library/src/main/java/com/qiniu/android/http/ResponseInfo.java +++ b/library/src/main/java/com/qiniu/android/http/ResponseInfo.java @@ -31,12 +31,15 @@ public final class ResponseInfo { */ public static final int UnexpectedSysCallError = -10; + /** + * 无可用于上传的 host, 所有主备 host 均已尝试 + */ @Deprecated public static final int NoUsableHostError = -9; /** * 在上传时,SDK 内部业务逻辑非预期。正常情况下,此错误并会被抛掷应用层。 - * + *

* 此错误出现的原因一般为某个上传流程异常请求导致,实际应该抛出请求,但因为调用异常未被抛出。 */ public static final int SDKInteriorError = -9; @@ -81,9 +84,15 @@ public final class ResponseInfo { */ public static final int NetworkError = -1; + /** + * 上传数据 crc32 校验失败 + */ @Deprecated public static final int Crc32NotMatch = -406; + /** + * 未知错误 + */ @Deprecated public static final int UnknownError = 10000; @@ -129,6 +138,9 @@ public final class ResponseInfo { */ public static final int ParseError = -1015; + /** + * 响应解析异常 + */ @Deprecated public static final int PasrseError = -1015; @@ -147,22 +159,27 @@ public final class ResponseInfo { * response 信息 */ public String message; + /** * 七牛日志扩展头 */ public final String reqId; + /** * 七牛日志扩展头 */ public final String xlog; + /** * cdn日志扩展头 */ public final String xvia; + /** * 错误信息 */ public final String error; + /** * 服务器域名 */ @@ -222,61 +239,148 @@ private ResponseInfo(JSONObject json, } } + /** + * 构造成功响应 + * + * @return ResponseInfo + */ public static ResponseInfo successResponse() { ResponseInfo responseInfo = new ResponseInfo(null, null, null, RequestSuccess, "inter:reqid", "inter:xlog", "inter:xvia", null, null); return responseInfo; } + /** + * 构造文件为空响应 + * + * @param desc 描述信息 + * @return ResponseInfo + */ public static ResponseInfo zeroSize(String desc) { return errorInfo(ZeroSizeFile, (desc != null ? desc : "data size is 0")); } + /** + * 构造取消响应 + * + * @return ResponseInfo + */ public static ResponseInfo cancelled() { return errorInfo(Cancelled, "cancelled by user"); } + /** + * 构造无效参数响应 + * + * @param desc 描述信息 + * @return ResponseInfo + */ public static ResponseInfo invalidArgument(String desc) { return errorInfo(InvalidArgument, desc); } + /** + * 构造无效 Token 响应 + * + * @param desc 描述信息 + * @return ResponseInfo + */ public static ResponseInfo invalidToken(String desc) { return errorInfo(InvalidToken, desc); } + /** + * 构造文件异常响应 + * + * @param e 异常信息 + * @return ResponseInfo + */ public static ResponseInfo fileError(Exception e) { return errorInfo(InvalidFile, e != null ? e.getMessage() : null); } + /** + * 构造网络异常响应 + * + * @param desc 描述信息 + * @return ResponseInfo + */ public static ResponseInfo networkError(String desc) { return errorInfo(NetworkError, desc); } + /** + * 构造本地调用异常响应 + * + * @param desc 描述信息 + * @return ResponseInfo + */ public static ResponseInfo localIOError(String desc) { return errorInfo(LocalIOError, desc); } + /** + * 构造异常响应 + * + * @param desc 描述信息 + * @return ResponseInfo + */ public static ResponseInfo maliciousResponseError(String desc) { return errorInfo(MaliciousResponseError, desc); } + /** + * 构造无上传域名异常响应 + * + * @param desc 描述信息 + * @return ResponseInfo + */ @Deprecated public static ResponseInfo noUsableHostError(String desc) { return errorInfo(NoUsableHostError, desc); } + /** + * 构造 SDK 内部异常响应 + * + * @param desc 描述信息 + * @return ResponseInfo + */ public static ResponseInfo sdkInteriorError(String desc) { return errorInfo(SDKInteriorError, desc); } + /** + * 构造系统调用异常响应 + * + * @param desc 描述信息 + * @return ResponseInfo + */ public static ResponseInfo unexpectedSysCallError(String desc) { return errorInfo(UnexpectedSysCallError, desc); } + /** + * 构造异常响应 + * + * @param statusCode 状态码 + * @param error 错误信息 + * @return ResponseInfo + */ public static ResponseInfo errorInfo(int statusCode, String error) { ResponseInfo responseInfo = new ResponseInfo(null, null, "", statusCode, null, null, null, null, error); return responseInfo; } + /** + * 构造响应 + * + * @param request 请求对象 + * @param responseCode 响应码 + * @param responseHeader 响应头 + * @param response 响应信息 + * @param errorMessage 错误信息 + * @return ResponseInfo + */ public static ResponseInfo create(Request request, int responseCode, Map responseHeader, @@ -285,6 +389,17 @@ public static ResponseInfo create(Request request, return create(request, null, responseCode, responseHeader, response, errorMessage); } + /** + * 构造响应 + * + * @param request 请求对象 + * @param httpVersion 请求版本信息 + * @param responseCode 响应码 + * @param responseHeader 响应头 + * @param response 响应信息 + * @param errorMessage 错误信息 + * @return ResponseInfo + */ public static ResponseInfo create(Request request, String httpVersion, int responseCode, @@ -312,6 +427,11 @@ public static ResponseInfo create(Request request, return responseInfo; } + /** + * 检查是否是异常请求 + * + * @return ResponseInfo + */ public ResponseInfo checkMaliciousResponse() { if (statusCode == 200 && (reqId == null && xlog == null)) { return new ResponseInfo(null, responseHeader, httpVersion, MaliciousResponseError, reqId, xlog, xvia, host, "this is a malicious response"); @@ -320,20 +440,41 @@ public ResponseInfo checkMaliciousResponse() { } } + /** + * 检查请求是否因网络问题而失败 + * + * @param code 请求响应的状态码 + * @return 是否因网络问题而失败 + */ public static boolean isStatusCodeForBrokenNetwork(int code) { return code == NetworkError || code == UnknownHost || code == CannotConnectToHost || code == TimedOut || code == NetworkConnectionLost; } + /** + * 请求是否被取消 + * + * @return 请求是否被取消 + */ public boolean isCancelled() { return statusCode == Cancelled; } + /** + * 请求是否成功 + * + * @return 请求是否成功 + */ public boolean isOK() { return statusCode == RequestSuccess && error == null && (hasReqId() || xlog != null); } + /** + * 请求是否需要重试 + * + * @return 请求是否需要重试 + */ public boolean couldRetry() { if (isNotQiniu()) { return true; @@ -357,6 +498,11 @@ public boolean couldRetry() { } } + /** + * 请求是否需要在区域间重试 + * + * @return 请求是否需要重试 + */ public boolean couldRegionRetry() { if (isNotQiniu()) { return true; @@ -376,6 +522,11 @@ public boolean couldRegionRetry() { } } + /** + * 请求是否需要在域名之间重试 + * + * @return 请求是否需要重试 + */ public boolean couldHostRetry() { if (isNotQiniu()) { return true; @@ -396,6 +547,11 @@ public boolean couldHostRetry() { } } + /** + * 请求是否发生 tls 异常 + * + * @return 是否发生 tls 异常 + */ public boolean isTlsError() { if (statusCode == NetworkSSLError) { return true; @@ -404,6 +560,11 @@ public boolean isTlsError() { } } + /** + * 请求是否连接到了服务 + * + * @return 是否连接到了服务 + */ public boolean canConnectToHost() { if (statusCode > 99 || isCancelled()) { return true; @@ -412,6 +573,11 @@ public boolean canConnectToHost() { } } + /** + * 请求的 host 是否不可用 + * + * @return host 是否不可用 + */ public boolean isHostUnavailable() { // 基本不可恢复,注:会影响下次请求,范围太大可能会造成大量的timeout if (statusCode == 502 || statusCode == 503 || statusCode == 504 || statusCode == 599) { @@ -421,28 +587,57 @@ public boolean isHostUnavailable() { } } - // 在断点续上传过程中,ctx 信息已过期。 + /** + * 在断点续上传过程中,ctx 信息是否已过期 + * + * @return ctx 信息是否已过期 + */ public boolean isCtxExpiredError() { return statusCode == 701 || (statusCode == 612 && error != null && error.contains("no such uploadId")); } + /** + * 请求是否因网络问题而失败 + * + * @return 请求是否因网络问题而失败 + */ public boolean isNetworkBroken() { return statusCode == NetworkError || statusCode == NetworkSlow; } + /** + * 请求是否是为服务端异常 + * + * @return 请求是否是为服务端异常 + */ public boolean isServerError() { return (statusCode >= 500 && statusCode < 600 && statusCode != 579) || statusCode == 996; } + /** + * 重试是否需要切换域名 + * + * @return 是否需要切换域名 + */ public boolean needSwitchServer() { return isNetworkBroken() || isServerError(); } + /** + * 是否需要重试 + * + * @return 是否需要重试 + */ public boolean needRetry() { return !isCancelled() && (needSwitchServer() || statusCode == 406 || (statusCode == 200 && error != null) || isNotQiniu()); } + /** + * 请求是否未到达七牛服务 + * + * @return 请求是否未到达七牛服务 + */ public boolean isNotQiniu() { return (statusCode == MaliciousResponseError) || (statusCode > 0 && (!hasReqId() && xlog == null)); } @@ -451,11 +646,21 @@ private boolean isQiniu() { return !isNotQiniu(); } + /** + * 获取 string 信息 + * + * @return string 信息 + */ public String toString() { return String.format(Locale.ENGLISH, "{ver:%s,ResponseInfo:%s,status:%d, reqId:%s, xlog:%s, xvia:%s, host:%s, time:%d,error:%s}", Constants.VERSION, id, statusCode, reqId, xlog, xvia, host, timeStamp, error); } + /** + * 是否有 reqId + * + * @return 是否有 reqId + */ public boolean hasReqId() { return reqId != null && reqId.length() > 0; } diff --git a/library/src/main/java/com/qiniu/android/http/UrlConverter.java b/library/src/main/java/com/qiniu/android/http/UrlConverter.java index 4a2a55f80..1b5d4600e 100644 --- a/library/src/main/java/com/qiniu/android/http/UrlConverter.java +++ b/library/src/main/java/com/qiniu/android/http/UrlConverter.java @@ -1,5 +1,15 @@ package com.qiniu.android.http; +/** + * url 拦截器 + */ public interface UrlConverter { + + /** + * url 拦截器,可以转换 url + * + * @param url url + * @return 转换后的 url + */ String convert(String url); } diff --git a/library/src/main/java/com/qiniu/android/http/UserAgent.java b/library/src/main/java/com/qiniu/android/http/UserAgent.java index bd20d21d5..7bc14e4fd 100644 --- a/library/src/main/java/com/qiniu/android/http/UserAgent.java +++ b/library/src/main/java/com/qiniu/android/http/UserAgent.java @@ -15,10 +15,20 @@ /** * Created by bailong on 15/6/23. + * + * @hidden */ public final class UserAgent { private static UserAgent _instance = new UserAgent(); + + /** + * id + */ public final String id; + + /** + * UserAgent + */ public final String ua; private UserAgent() { @@ -26,6 +36,11 @@ private UserAgent() { ua = getUserAgent(id); } + /** + * 获取 UserAgent 单例 + * + * @return UserAgent 单例 + */ public static UserAgent instance() { return _instance; } @@ -37,10 +52,16 @@ private static String genId() { static String getUserAgent(String id) { String addition = Utils.isDebug() ? "_Debug" : ""; - return format("QiniuAndroid%s/%s (%s; %s; %s",addition, Constants.VERSION, + return format("QiniuAndroid%s/%s (%s; %s; %s", addition, Constants.VERSION, Utils.systemVersion(), Utils.systemName(), id); } + /** + * 获取 UserAgent 字符串 + * + * @param part part + * @return UserAgent 字符串 + */ public String getUa(String part) { String _part = ("" + part).trim(); if (_part.length() > 15) { diff --git a/library/src/main/java/com/qiniu/android/http/connectCheck/ConnectChecker.java b/library/src/main/java/com/qiniu/android/http/connectCheck/ConnectChecker.java index e36d336a1..f27589ae1 100644 --- a/library/src/main/java/com/qiniu/android/http/connectCheck/ConnectChecker.java +++ b/library/src/main/java/com/qiniu/android/http/connectCheck/ConnectChecker.java @@ -17,15 +17,34 @@ import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; +/** + * 网络连接检查器 + * + * @hidden + */ public class ConnectChecker { private static ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor(); private static SingleFlight singleFlight = new SingleFlight<>(); + private ConnectChecker() { + } + + /** + * 根据请求 metrics 判断网络是否正常连接 + * + * @param metrics 请求 metrics + * @return 网络是否正常连接 + */ public static boolean isConnected(UploadSingleRequestMetrics metrics) { return metrics != null && metrics.getResponse() != null && metrics.getResponse().statusCode > 99; } + /** + * 检查网络是否正常连接 + * + * @return 网络是否正常连接 + */ public static UploadSingleRequestMetrics check() { final CheckResult result = new CheckResult(); diff --git a/library/src/main/java/com/qiniu/android/http/dns/Dns.java b/library/src/main/java/com/qiniu/android/http/dns/Dns.java index ecc3f91c6..0e551e4cb 100644 --- a/library/src/main/java/com/qiniu/android/http/dns/Dns.java +++ b/library/src/main/java/com/qiniu/android/http/dns/Dns.java @@ -4,8 +4,18 @@ import java.util.List; /** + * Dns 解析器 + * * Created by sxci on 03/04/2018. */ public interface Dns { + + /** + * Dns 解析 host 域名 + * + * @param hostname host 域名 + * @return 解析结果 + * @throws UnknownHostException 异常信息 + */ List lookup(String hostname) throws UnknownHostException; } diff --git a/library/src/main/java/com/qiniu/android/http/dns/DnsCacheFile.java b/library/src/main/java/com/qiniu/android/http/dns/DnsCacheFile.java index 46eed4ddb..88b6ae959 100644 --- a/library/src/main/java/com/qiniu/android/http/dns/DnsCacheFile.java +++ b/library/src/main/java/com/qiniu/android/http/dns/DnsCacheFile.java @@ -1,4 +1,5 @@ package com.qiniu.android.http.dns; + import com.qiniu.android.storage.Recorder; import java.io.File; @@ -8,13 +9,28 @@ /** * Created by jemy on 2019/9/17. + * + * @hidden */ public class DnsCacheFile implements Recorder { + /** + * dns 缓存路径 + */ public String directory; + + /** + * dns 缓存文件句柄 + */ public File f; + /** + * DnsCacheFile 构造函数 + * + * @param directory dns 缓存路径 + * @throws IOException 异常信息 + */ public DnsCacheFile(String directory) throws IOException { if (directory == null) { throw new IOException("directory invalid"); diff --git a/library/src/main/java/com/qiniu/android/http/dns/DnsCacheInfo.java b/library/src/main/java/com/qiniu/android/http/dns/DnsCacheInfo.java index e9f0133a9..7b77dd493 100644 --- a/library/src/main/java/com/qiniu/android/http/dns/DnsCacheInfo.java +++ b/library/src/main/java/com/qiniu/android/http/dns/DnsCacheInfo.java @@ -11,13 +11,32 @@ /** * Created by jemy on 2019/9/23. + * + * @hidden */ public class DnsCacheInfo implements java.io.Serializable { + /** + * DNS 缓存时间 + */ private String currentTime; + + /** + * 本地 IP + */ private String localIp; + + /** + * DNS 解析结果 + */ private ConcurrentHashMap> info; + /** + * 根据 json 数据构造 DnsCacheInfo + * + * @param jsonData json 数据 + * @return DnsCacheInfo + */ public static DnsCacheInfo createDnsCacheInfoByData(byte[] jsonData) { if (jsonData == null) { return null; @@ -49,7 +68,7 @@ public static DnsCacheInfo createDnsCacheInfoByData(byte[] jsonData) { } catch (Exception ignored) { } - if (currentTime == null || localIp == null || infoMapJSONObject == null){ + if (currentTime == null || localIp == null || infoMapJSONObject == null) { return null; } @@ -62,7 +81,7 @@ public static DnsCacheInfo createDnsCacheInfoByData(byte[] jsonData) { DnsNetworkAddress address = DnsNetworkAddress.address(addressJSONArray.getJSONObject(i)); addressList.add(address); } - if (addressList.size() > 0){ + if (addressList.size() > 0) { info.put(key, addressList); } } catch (Exception ignored) { @@ -72,9 +91,19 @@ public static DnsCacheInfo createDnsCacheInfoByData(byte[] jsonData) { return new DnsCacheInfo(currentTime, localIp, info); } + /** + * 构造方法 + */ public DnsCacheInfo() { } + /** + * 构造方法 + * + * @param currentTime 当前时间 + * @param localIp 本地 IP + * @param info DNS 缓存数据 + */ public DnsCacheInfo(String currentTime, String localIp, ConcurrentHashMap> info) { this.currentTime = currentTime; this.localIp = localIp; @@ -89,6 +118,11 @@ String getLocalIp() { return localIp; } + /** + * 获取缓存数据 + * + * @return 缓存数据 + */ public ConcurrentHashMap> getInfo() { return info; } @@ -101,14 +135,29 @@ void setLocalIp(String localIp) { this.localIp = localIp; } + /** + * 设置缓存数据 + * + * @param info 缓存数据 + */ public void setInfo(ConcurrentHashMap> info) { this.info = info; } + /** + * 获取缓存的 key + * + * @return 缓存的 key + */ public String cacheKey() { return localIp; } + /** + * 获取缓存的 json byte 数据 + * + * @return 缓存的 json byte 数据 + */ public byte[] toJsonData() { JSONObject cacheInfoJSONObject = new JSONObject(); try { @@ -150,6 +199,11 @@ public byte[] toJsonData() { return cacheInfoJSONObject.toString().getBytes(); } + /** + * toString + * + * @return String 信息 + */ @Override public String toString() { return "{\"currentTime\":\"" + currentTime + "\", \"localIp\":\"" + localIp + "\"}"; diff --git a/library/src/main/java/com/qiniu/android/http/dns/DnsPrefetchTransaction.java b/library/src/main/java/com/qiniu/android/http/dns/DnsPrefetchTransaction.java index d2c9b664e..341f076b9 100644 --- a/library/src/main/java/com/qiniu/android/http/dns/DnsPrefetchTransaction.java +++ b/library/src/main/java/com/qiniu/android/http/dns/DnsPrefetchTransaction.java @@ -6,11 +6,21 @@ /** * Created by yangsen on 2020/6/4 + * + * @hidden */ public class DnsPrefetchTransaction { private static boolean isDnsLoaded = false; + private DnsPrefetchTransaction() { + } + + /** + * 将 SDK 内部使用域名的 Dns 预解析操作添加到周期性的事务中 + * + * @return 添加是否成功 + */ public static synchronized boolean addDnsLocalLoadTransaction() { if (isDnsLoaded) { return false; @@ -33,7 +43,13 @@ public void run() { return true; } - + /** + * 将 zone 中使用域名的 Dns 预解析操作添加到周期性的事务中 + * + * @param currentZone zone + * @param token 上传 token + * @return 添加是否成功 + */ public static synchronized boolean addDnsCheckAndPrefetchTransaction(final Zone currentZone, final UpToken token) { if (!DnsPrefetcher.getInstance().isDnsOpen()) { return false; @@ -58,6 +74,12 @@ public void run() { return true; } + /** + * 将 hosts 中域名的 Dns 预解析操作添加到周期性的事务中 + * + * @param hosts 域名 + * @return 添加是否成功 + */ public static synchronized boolean addDnsCheckAndPrefetchTransaction(final String[] hosts) { if (!DnsPrefetcher.getInstance().isDnsOpen()) { return false; @@ -78,7 +100,11 @@ public void run() { return true; } - + /** + * 将检查缓存是否有效的操作添加到周期性事务中,无效则重新拉取 + * + * @return 添加是否成功 + */ public static synchronized boolean setDnsCheckWhetherCachedValidTransactionAction() { if (!DnsPrefetcher.getInstance().isDnsOpen()) { return false; diff --git a/library/src/main/java/com/qiniu/android/http/dns/DnsPrefetcher.java b/library/src/main/java/com/qiniu/android/http/dns/DnsPrefetcher.java index 433b2db78..7d7e4a74d 100644 --- a/library/src/main/java/com/qiniu/android/http/dns/DnsPrefetcher.java +++ b/library/src/main/java/com/qiniu/android/http/dns/DnsPrefetcher.java @@ -22,6 +22,8 @@ /** * Created by yangsen on 2020/5/28 + * + * @hidden */ public class DnsPrefetcher { @@ -40,12 +42,25 @@ private DnsPrefetcher() { systemDns = new SystemDns(GlobalConfiguration.getInstance().dnsResolveTimeout); } + /** + * 获取 DnsPrefetcher 单例 + * + * @return DnsPrefetcher 单例 + */ public static DnsPrefetcher getInstance() { return dnsPrefetcher; } + /** + * Dns 解析的最后一次异常信息 + */ public String lastPrefetchErrorMessage; + /** + * 从本地恢复缓存信息 + * + * @return 是否恢复成功 + */ public boolean recoverCache() { DnsCacheFile recorder = getDiskCache(); @@ -66,14 +81,30 @@ public boolean recoverCache() { return recoverDnsCache(data); } + /** + * 对 SDK 默认使用的域名进行 Dns 解析 + */ public void localFetch() { addPreFetchHosts(getLocalPreHost()); } + /** + * 周期性的对 Zone 内的域名进行 Dns 解析 + * + * @param currentZone zone + * @param token 上传 Token + * @return 是否配置成功 + */ public boolean checkAndPrefetchDnsIfNeed(Zone currentZone, UpToken token) { return addPreFetchHosts(getCurrentZoneHosts(currentZone, token)); } + /** + * 周期性的对 hosts 进行 Dns 解析 + * + * @param hosts 域名 + * @return 是否配置成功 + */ public boolean addPreFetchHosts(String[] hosts) { if (hosts == null) { return false; @@ -98,6 +129,11 @@ public boolean addPreFetchHosts(String[] hosts) { } } + /** + * 将内存中 address 对应的缓存设置为无效 + * + * @param address host dns 解析记录 + */ public void invalidNetworkAddress(IDnsNetworkAddress address) { if (address == null || address.getHostValue() == null) { return; @@ -125,6 +161,12 @@ private void invalidNetworkAddressOfHost(String host) { addressDictionary.remove(host); } + /** + * 获取 host 的 Dns 预解析结果 + * + * @param host 域名 + * @return Dns 预解析结果 + */ public List getInetAddressByHost(String host) { if (!isDnsOpen()) { return null; @@ -141,6 +183,13 @@ public List getInetAddressByHost(String host) { return null; } + /** + * 通过安全的 Dns 解析对 host 进行预解析并返回解析的方式 + * + * @param hostname 域名 + * @return 解析的方式 + * @throws UnknownHostException 异常信息 + */ public String lookupBySafeDns(String hostname) throws UnknownHostException { if (hostname == null || hostname.length() == 0) { return null; @@ -173,11 +222,19 @@ public String lookupBySafeDns(String hostname) throws UnknownHostException { return null; } + /** + * 清除 Dns 解析缓存 + * + * @throws IOException 异常信息 + */ public void clearDnsCache() throws IOException { clearMemoryCache(); clearDiskCache(); } + /** + * 检查 Host Dns 预解析的缓存信息是否有效 + */ public void checkWhetherCachedDnsValid() { if (!prepareToPreFetch()) { return; @@ -358,10 +415,18 @@ private boolean recorderDnsCache() { return true; } + /** + * 清除内存缓存 + */ public void clearMemoryCache() { addressDictionary.clear(); } + /** + * 清除磁盘缓存 + * + * @throws IOException 异常信息 + */ public void clearDiskCache() throws IOException { DnsCacheFile recorder = getDiskCache(); if (recorder == null) { @@ -407,10 +472,19 @@ private String[] getCacheHosts() { return prefetchHosts.toArray(new String[0]); } + /** + * 获取 Dns 配置是否打开 + * @return Dns 配置是否打开 + */ public boolean isDnsOpen() { return GlobalConfiguration.getInstance().isDnsOpen; } + /** + * 获取是否正在进行 Dns 预解析操作 + * + * @return 是否正在进行 Dns 预解析操作 + */ public synchronized boolean isPrefetching() { return isPrefetching; } diff --git a/library/src/main/java/com/qiniu/android/http/dns/DnsSource.java b/library/src/main/java/com/qiniu/android/http/dns/DnsSource.java index 3f502363f..a4728d3b9 100644 --- a/library/src/main/java/com/qiniu/android/http/dns/DnsSource.java +++ b/library/src/main/java/com/qiniu/android/http/dns/DnsSource.java @@ -1,29 +1,89 @@ package com.qiniu.android.http.dns; +/** + * Dns 解析源 + */ public class DnsSource { + + /** + * Doh 解析源 + */ public static final String Doh = "doh"; + + /** + * udp 方式的解析源 + */ public static final String Udp = "dns"; + + /** + * DnsPod 解析源 + */ public static final String Dnspod = "dnspod"; + + /** + * System 解析源 + */ public static final String System = "system"; + + /** + * 自定义解析源 + */ public static final String Custom = "customized"; + + /** + * 未知解析源 + */ public static final String None = "none"; + private DnsSource() { + } + + /** + * 判断解析源是否为 Doh + * + * @param source 解析源 + * @return 解析源是否为 Doh + */ public static boolean isDoh(String source) { return source != null && source.contains(Doh); } + /** + * 判断解析源是否为 Udp + * + * @param source 解析源 + * @return 解析源是否为 Udp + */ public static boolean isUdp(String source) { return source != null && source.contains(Udp); } + /** + * 判断解析源是否为 DnsPod + * + * @param source 解析源 + * @return 解析源是否为 DnsPod + */ public static boolean isDnspod(String source) { return source != null && source.contains(Dnspod); } + /** + * 判断解析源是否为系统的 + * + * @param source 解析源 + * @return 解析源是否为系统的 + */ public static boolean isSystem(String source) { return source != null && source.contains(System); } + /** + * 判断解析源是否为自定义的 + * + * @param source 解析源 + * @return 解析源是否为自定义的 + */ public static boolean isCustom(String source) { return source != null && source.contains(Custom); } diff --git a/library/src/main/java/com/qiniu/android/http/dns/HappyDns.java b/library/src/main/java/com/qiniu/android/http/dns/HappyDns.java index ae1d72953..af30455ed 100644 --- a/library/src/main/java/com/qiniu/android/http/dns/HappyDns.java +++ b/library/src/main/java/com/qiniu/android/http/dns/HappyDns.java @@ -9,6 +9,8 @@ /** * Created by yangsen on 2020/6/8 + * + * @hidden */ @Deprecated public class HappyDns implements Dns { @@ -18,13 +20,16 @@ public class HappyDns implements Dns { private DnsQueryErrorHandler errorHandler; - public HappyDns(){ + /** + * 构造函数 + */ + public HappyDns() { int dnsTimeout = GlobalConfiguration.getInstance().dnsResolveTimeout; systemDns = new SystemDns(dnsTimeout); customDns = GlobalConfiguration.getInstance().dns; } - void setQueryErrorHandler(DnsQueryErrorHandler handler){ + void setQueryErrorHandler(DnsQueryErrorHandler handler) { errorHandler = handler; } diff --git a/library/src/main/java/com/qiniu/android/http/dns/HttpDns.java b/library/src/main/java/com/qiniu/android/http/dns/HttpDns.java index a16de94ff..5279e09fa 100644 --- a/library/src/main/java/com/qiniu/android/http/dns/HttpDns.java +++ b/library/src/main/java/com/qiniu/android/http/dns/HttpDns.java @@ -15,11 +15,21 @@ import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; +/** + * Http Dns + * + * @hidden + */ public class HttpDns extends BaseDns implements Dns { private IResolver httpIpv4Resolver; private IResolver httpIpv6Resolver; + /** + * 构造函数 + * + * @param timeout 解析超时时间 + */ public HttpDns(int timeout) { String[] dohIpv4Servers = GlobalConfiguration.getInstance().getDohIpv4Servers(); if (dohIpv4Servers != null && dohIpv4Servers.length > 0) { @@ -32,6 +42,13 @@ public HttpDns(int timeout) { } } + /** + * Dns 解析函数 + * + * @param hostname host 域名 + * @return 解析结果 + * @throws UnknownHostException 异常 + */ @Override public List lookup(String hostname) throws UnknownHostException { if (!GlobalConfiguration.getInstance().dohEnable) { diff --git a/library/src/main/java/com/qiniu/android/http/dns/IDnsNetworkAddress.java b/library/src/main/java/com/qiniu/android/http/dns/IDnsNetworkAddress.java index a0a44909e..a22c20939 100644 --- a/library/src/main/java/com/qiniu/android/http/dns/IDnsNetworkAddress.java +++ b/library/src/main/java/com/qiniu/android/http/dns/IDnsNetworkAddress.java @@ -1,19 +1,45 @@ package com.qiniu.android.http.dns; +/** + * Dns 预解析信息 + * + * @hidden + */ public interface IDnsNetworkAddress { - /// 域名 + + /** + * 预解析的域名 + * + * @return 预解析的域名 + */ String getHostValue(); - /// 地址IP信息 + /** + * 预解析域名的 IP 信息 + * + * @return 预解析域名的 IP 信息 + */ String getIpValue(); - /// ip有效时间 单位:秒 + /** + * 预解析域名的 IP 有效时间 单位:秒 + * + * @return 预解析域名的 IP 有效时间 + */ Long getTtlValue(); - /// ip预取来源, 自定义dns返回 "customized" + /** + * 预解析的源,自定义dns返回 "customized" + * + * @return 预解析的源 + */ String getSourceValue(); - /// 解析到host时的时间戳 单位:秒 + /** + * 解析到 host 时的时间戳,单位:秒 + * + * @return 解析到 host 时的时间戳 + */ Long getTimestampValue(); } diff --git a/library/src/main/java/com/qiniu/android/http/dns/SystemDns.java b/library/src/main/java/com/qiniu/android/http/dns/SystemDns.java index a89d0b292..7440fad64 100644 --- a/library/src/main/java/com/qiniu/android/http/dns/SystemDns.java +++ b/library/src/main/java/com/qiniu/android/http/dns/SystemDns.java @@ -18,16 +18,33 @@ /** * Created by yangsen on 2020/5/28 + * + * @hidden */ public class SystemDns extends BaseDns implements Dns { + /** + * 构造函数 + */ public SystemDns() { } + /** + * 构造函数 + * + * @param timeout DNS 解析超时时间 + */ public SystemDns(int timeout) { this.timeout = timeout; } + /** + * DNS 解析域名 + * + * @param hostname 域名 + * @return 解析结果 + * @throws UnknownHostException 异常 + */ public List lookupInetAddress(final String hostname) throws UnknownHostException { if (hostname == null) { throw new UnknownHostException("hostname is null"); @@ -49,6 +66,13 @@ public List call() throws Exception { } } + /** + * DNS 解析域名 + * + * @param hostname 域名 + * @return 解析结果 + * @throws UnknownHostException 异常 + */ @Override public List lookup(String hostname) throws UnknownHostException { long timestamp = new Date().getTime() / 1000; diff --git a/library/src/main/java/com/qiniu/android/http/dns/UdpDns.java b/library/src/main/java/com/qiniu/android/http/dns/UdpDns.java index 48d7ca0e8..a7fb30522 100644 --- a/library/src/main/java/com/qiniu/android/http/dns/UdpDns.java +++ b/library/src/main/java/com/qiniu/android/http/dns/UdpDns.java @@ -15,10 +15,20 @@ import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; +/** + * udp dns + * + * @hidden + */ public class UdpDns extends BaseDns implements Dns { private IResolver udpIpv4Resolver; private IResolver udpIpv6Resolver; + /** + * 构造函数 + * + * @param timeout 超时时间,单位:秒 + */ public UdpDns(int timeout) { String[] udpIpv4Servers = GlobalConfiguration.getInstance().getUdpDnsIpv4Servers(); if (udpIpv4Servers != null && udpIpv4Servers.length > 0) { @@ -31,6 +41,13 @@ public UdpDns(int timeout) { } } + /** + * 解析域名 + * + * @param hostname host 域名 + * @return 解析结果 + * @throws UnknownHostException 异常 + */ @Override public List lookup(String hostname) throws UnknownHostException { if (!GlobalConfiguration.getInstance().udpDnsEnable) { diff --git a/library/src/main/java/com/qiniu/android/http/metrics/UploadMetrics.java b/library/src/main/java/com/qiniu/android/http/metrics/UploadMetrics.java index ecfd51da2..5b138a59c 100644 --- a/library/src/main/java/com/qiniu/android/http/metrics/UploadMetrics.java +++ b/library/src/main/java/com/qiniu/android/http/metrics/UploadMetrics.java @@ -4,24 +4,58 @@ import java.util.Date; +/** + * 上传指标 + * + * @hidden + */ public class UploadMetrics { + /** + * 开始时间 + */ protected Date startDate = null; + + /** + * 结束时间 + */ protected Date endDate = null; + /** + * 构造函数 + */ + protected UploadMetrics() { + } + + /** + * 开始 + */ public void start() { startDate = new Date(); } + /** + * 结束 + */ public void end() { endDate = new Date(); } + /** + * 获取开始时间 + * + * @return 开始时间 + */ public Date getStartDate() { return startDate; } - public long totalElapsedTime(){ + /** + * 获取总耗时 + * + * @return 总耗时 + */ + public long totalElapsedTime() { if (startDate == null || endDate == null) { return 0; } diff --git a/library/src/main/java/com/qiniu/android/http/metrics/UploadRegionRequestMetrics.java b/library/src/main/java/com/qiniu/android/http/metrics/UploadRegionRequestMetrics.java index 1d7b2b1e0..43e41c43d 100644 --- a/library/src/main/java/com/qiniu/android/http/metrics/UploadRegionRequestMetrics.java +++ b/library/src/main/java/com/qiniu/android/http/metrics/UploadRegionRequestMetrics.java @@ -7,23 +7,46 @@ import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; +/** + * 区域上传事务 + * + * @hidden + */ public class UploadRegionRequestMetrics extends UploadMetrics { + /** + * 上传区域 + */ public final IUploadRegion region; private List metricsList = new CopyOnWriteArrayList<>(); + /** + * 构造函数 + * + * @param region 上传区域 + */ public UploadRegionRequestMetrics(IUploadRegion region) { this.region = region; } + /** + * 请求的次数 + * + * @return 请求的次数 + */ public Integer requestCount() { return metricsList.size(); } + /** + * 发送数据的大小 + * + * @return 发送数据的大小 + */ public Long bytesSend() { - if (metricsList.size() == 0) { - return 0l; + if (metricsList.isEmpty()) { + return 0L; } long bytes = 0; for (UploadSingleRequestMetrics metrics : metricsList) { @@ -34,11 +57,21 @@ public Long bytesSend() { return bytes; } + /** + * 获取最后一个请求指标 + * + * @return 最后一个请求指标 + */ public UploadSingleRequestMetrics lastMetrics() { int size = metricsList.size(); return size < 1 ? null : metricsList.get(size - 1); } + /** + * 添加新的上传请求指标 + * + * @param metricsList 新的上传请求指标 + */ public void addMetricsList(List metricsList) { if (metricsList == null || metricsList.size() == 0) { return; @@ -50,6 +83,11 @@ public void addMetricsList(List metricsList) { } } + /** + * 添加新的上传请求指标 + * + * @param metrics 新的上传请求指标 + */ public void addMetrics(UploadRegionRequestMetrics metrics) { if (metrics == null || metrics.region == null || metrics.region.getZoneInfo() == null || metrics.region.getZoneInfo().regionId == null diff --git a/library/src/main/java/com/qiniu/android/http/metrics/UploadSingleRequestMetrics.java b/library/src/main/java/com/qiniu/android/http/metrics/UploadSingleRequestMetrics.java index 2534733e8..df4bde63e 100644 --- a/library/src/main/java/com/qiniu/android/http/metrics/UploadSingleRequestMetrics.java +++ b/library/src/main/java/com/qiniu/android/http/metrics/UploadSingleRequestMetrics.java @@ -8,17 +8,46 @@ import java.util.Date; +/** + * 单请求的指标 + * + * @hidden + */ public class UploadSingleRequestMetrics extends UploadMetrics { + + /** + * 请求被劫持标识 + */ public static final String RequestHijacked = "forsure"; + + /** + * 请求可能被劫持标识 + */ public static final String RequestMaybeHijacked = "maybe"; // 请求是否劫持【内部使用】 private String hijacked; + /** + * 构造函数 + */ + public UploadSingleRequestMetrics() { + } + + /** + * 请求是否劫持 + * + * @return hijacked + */ public String getHijacked() { return hijacked; } + /** + * 设置 hijacked + * + * @param hijacked hijacked + */ public void setHijacked(String hijacked) { this.hijacked = hijacked; } @@ -26,10 +55,20 @@ public void setHijacked(String hijacked) { // 同步 Dns 解析源【内部使用】 private String syncDnsSource; + /** + * 获取同步安全 DNS 解析的源 + * + * @return 安全 DNS 解析的源 + */ public String getSyncDnsSource() { return syncDnsSource; } + /** + * 设置同步安全 DNS 解析的源 + * + * @param syncDnsSource 安全 DNS 解析的源 + */ public void setSyncDnsSource(String syncDnsSource) { this.syncDnsSource = syncDnsSource; } @@ -37,10 +76,20 @@ public void setSyncDnsSource(String syncDnsSource) { // 同步 Dns 解析错误信息【内部使用】 private String syncDnsError; + /** + * 获取同步 DNS 解析错误信息 + * + * @return 同步 DNS 解析错误信息 + */ public String getSyncDnsError() { return syncDnsError; } + /** + * 设置同步 DNS 解析错误信息 + * + * @param syncDnsError 同步 DNS 解析错误信息 + */ public void setSyncDnsError(String syncDnsError) { this.syncDnsError = syncDnsError; } @@ -48,10 +97,20 @@ public void setSyncDnsError(String syncDnsError) { // 网络检测信息,只有进行网络检测才会有 connectCheckMetrics 【内部使用】 private UploadSingleRequestMetrics connectCheckMetrics; + /** + * 获取网络检测指标 + * + * @return 网络检测指标 + */ public UploadSingleRequestMetrics getConnectCheckMetrics() { return connectCheckMetrics; } + /** + * 设置网络检测指标 + * + * @param connectCheckMetrics 网络检测指标 + */ public void setConnectCheckMetrics(UploadSingleRequestMetrics connectCheckMetrics) { this.connectCheckMetrics = connectCheckMetrics; } @@ -59,10 +118,20 @@ public void setConnectCheckMetrics(UploadSingleRequestMetrics connectCheckMetric // 请求对象【自定义对象,请保证对象的此属性不为空】 private Request request; + /** + * 获取请求 + * + * @return 请求 + */ public Request getRequest() { return request; } + /** + * 设置请求 + * + * @param request 请求 + */ public void setRequest(Request request) { if (request != null) { this.request = request.copyWithoutBody(); @@ -81,10 +150,20 @@ public void setRequest(Request request) { // 请求的响应对象【自定义对象,请保证对象的此属性不为空】 private ResponseInfo response; + /** + * 获取请求响应 + * + * @return 请求响应 + */ public ResponseInfo getResponse() { return response; } + /** + * 设置请求响应 + * + * @param response 设置请求响应 + */ public void setResponse(ResponseInfo response) { this.response = response; } @@ -92,10 +171,20 @@ public void setResponse(ResponseInfo response) { // 实际请求使用的 httpVersion【自定义对象,请保证对象的此属性不为空】 private String httpVersion; + /** + * 获取请求 HTTP 版本 + * + * @return 请求 HTTP 版本 + */ public String getHttpVersion() { return httpVersion; } + /** + * 设置请求 HTTP 版本 + * + * @param httpVersion 请求 HTTP 版本 + */ public void setHttpVersion(String httpVersion) { this.httpVersion = httpVersion; } @@ -103,10 +192,20 @@ public void setHttpVersion(String httpVersion) { // 请求使用的 Client 名称 private String clientName = "customized"; + /** + * 获取 client 名 + * + * @return client 名 + */ public String getClientName() { return clientName; } + /** + * 设置 client 名 + * + * @param clientName client 名 + */ public void setClientName(String clientName) { this.clientName = clientName; } @@ -114,10 +213,20 @@ public void setClientName(String clientName) { // 请求使用的 Client 的版本信息 private String clientVersion = "unknown"; + /** + * 获取 client 版本 + * + * @return client 版本 + */ public String getClientVersion() { return clientVersion; } + /** + * 设置 client 版本 + * + * @param clientVersion client 版本 + */ public void setClientVersion(String clientVersion) { this.clientVersion = clientVersion; } @@ -125,10 +234,20 @@ public void setClientVersion(String clientVersion) { // dns 解析开始时间 【自定义对象,请保证对象的此属性不为空】 private Date domainLookupStartDate; + /** + * 获取 dns 解析开始时间 + * + * @return dns 解析开始时间 + */ public Date getDomainLookupStartDate() { return domainLookupStartDate; } + /** + * 配置 dns 解析开始时间 + * + * @param domainLookupStartDate dns 解析开始时间 + */ public void setDomainLookupStartDate(Date domainLookupStartDate) { this.domainLookupStartDate = domainLookupStartDate; } @@ -136,10 +255,20 @@ public void setDomainLookupStartDate(Date domainLookupStartDate) { // dns 解析结束时间 【自定义对象,请保证对象的此属性不为空】 private Date domainLookupEndDate; + /** + * 获取 dns 解析结束时间 + * + * @return dns 解析结束时间 + */ public Date getDomainLookupEndDate() { return domainLookupEndDate; } + /** + * 设置 dns 解析结束时间 + * + * @param domainLookupEndDate dns 解析结束时间 + */ public void setDomainLookupEndDate(Date domainLookupEndDate) { this.domainLookupEndDate = domainLookupEndDate; } @@ -147,10 +276,20 @@ public void setDomainLookupEndDate(Date domainLookupEndDate) { // connect 开始时间 【自定义对象,请保证对象的此属性不为空】 private Date connectStartDate; + /** + * 获取链接建立开始时间 + * + * @return 链接建立开始时间 + */ public Date getConnectStartDate() { return connectStartDate; } + /** + * 设置链接建立开始时间 + * + * @param connectStartDate 链接建立开始时间 + */ public void setConnectStartDate(Date connectStartDate) { this.connectStartDate = connectStartDate; } @@ -158,10 +297,20 @@ public void setConnectStartDate(Date connectStartDate) { // connect 结束时间 【自定义对象,请保证对象的此属性不为空】 private Date connectEndDate; + /** + * 获取链接建立结束时间 + * + * @return 链接建立结束时间 + */ public Date getConnectEndDate() { return connectEndDate; } + /** + * 设置链接建立结束时间 + * + * @param connectEndDate 链接建立结束时间 + */ public void setConnectEndDate(Date connectEndDate) { this.connectEndDate = connectEndDate; } @@ -169,10 +318,20 @@ public void setConnectEndDate(Date connectEndDate) { // secure connect 开始时间 【自定义对象,请保证对象的此属性不为空】 private Date secureConnectionStartDate; + /** + * 获取 tls 建立开始时间 + * + * @return tls 建立开始时间 + */ public Date getSecureConnectionStartDate() { return secureConnectionStartDate; } + /** + * 设置 tls 建立开始时间 + * + * @param secureConnectionStartDate tls 建立开始时间 + */ public void setSecureConnectionStartDate(Date secureConnectionStartDate) { this.secureConnectionStartDate = secureConnectionStartDate; } @@ -180,10 +339,20 @@ public void setSecureConnectionStartDate(Date secureConnectionStartDate) { // secure connect 结束时间 【自定义对象,请保证对象的此属性不为空】 private Date secureConnectionEndDate; + /** + * 获取 tls 建立结束时间 + * + * @return tls 建立结束时间 + */ public Date getSecureConnectionEndDate() { return secureConnectionEndDate; } + /** + * 设置 tls 建立结束时间 + * + * @param secureConnectionEndDate tls 建立结束时间 + */ public void setSecureConnectionEndDate(Date secureConnectionEndDate) { this.secureConnectionEndDate = secureConnectionEndDate; } @@ -191,10 +360,20 @@ public void setSecureConnectionEndDate(Date secureConnectionEndDate) { // http 请求头发送开始时间 【自定义对象,请保证对象的此属性不为空】 private Date requestStartDate; + /** + * 获取请求开始时间 + * + * @return 请求开始时间 + */ public Date getRequestStartDate() { return requestStartDate; } + /** + * 设置请求开始时间 + * + * @param requestStartDate 请求开始时间 + */ public void setRequestStartDate(Date requestStartDate) { this.requestStartDate = requestStartDate; } @@ -202,10 +381,20 @@ public void setRequestStartDate(Date requestStartDate) { // http 请求体发送结束时间 【自定义对象,请保证对象的此属性不为空】 private Date requestEndDate; + /** + * 获取请求结束时间 + * + * @return 请求结束时间 + */ public Date getRequestEndDate() { return requestEndDate; } + /** + * 设置请求结束时间 + * + * @param requestEndDate 请求结束时间 + */ public void setRequestEndDate(Date requestEndDate) { this.requestEndDate = requestEndDate; } @@ -213,10 +402,20 @@ public void setRequestEndDate(Date requestEndDate) { // http 收到响应的时间 【自定义对象,请保证对象的此属性不为空】 private Date responseStartDate; + /** + * 获取响应开始时间 + * + * @return 响应开始时间 + */ public Date getResponseStartDate() { return responseStartDate; } + /** + * 设置响应开始时间 + * + * @param responseStartDate 响应开始时间 + */ public void setResponseStartDate(Date responseStartDate) { this.responseStartDate = responseStartDate; } @@ -224,10 +423,20 @@ public void setResponseStartDate(Date responseStartDate) { // http 响应的结束时间 【自定义对象,请保证对象的此属性不为空】 private Date responseEndDate; + /** + * 获取响应结束时间 + * + * @return 响应结束时间 + */ public Date getResponseEndDate() { return responseEndDate; } + /** + * 设置响应结束时间 + * + * @param responseEndDate 响应结束时间 + */ public void setResponseEndDate(Date responseEndDate) { this.responseEndDate = responseEndDate; } @@ -235,10 +444,20 @@ public void setResponseEndDate(Date responseEndDate) { // http 请求头大小【自定义对象,请保证对象的此属性不为空】 private long countOfRequestHeaderBytesSent = 0; + /** + * 获取请求头发送的大小 + * + * @return 请求头发送的大小 + */ public long getCountOfRequestHeaderBytesSent() { return countOfRequestHeaderBytesSent; } + /** + * 设置请求头发送的大小 + * + * @param countOfRequestHeaderBytesSent 请求头发送的大小 + */ public void setCountOfRequestHeaderBytesSent(long countOfRequestHeaderBytesSent) { this.countOfRequestHeaderBytesSent = countOfRequestHeaderBytesSent; } @@ -246,10 +465,20 @@ public void setCountOfRequestHeaderBytesSent(long countOfRequestHeaderBytesSent) // http 请求头体【自定义对象,请保证对象的此属性不为空】 private long countOfRequestBodyBytesSent = 0; + /** + * 获取请求体发送的大小 + * + * @return 请求体发送的大小 + */ public long getCountOfRequestBodyBytesSent() { return countOfRequestBodyBytesSent; } + /** + * 设置请求体发送的大小 + * + * @param countOfRequestBodyBytesSent 请求体发送的大小 + */ public void setCountOfRequestBodyBytesSent(long countOfRequestBodyBytesSent) { this.countOfRequestBodyBytesSent = countOfRequestBodyBytesSent; } @@ -257,10 +486,20 @@ public void setCountOfRequestBodyBytesSent(long countOfRequestBodyBytesSent) { // http 响应头大小【自定义对象,请保证对象的此属性不为空】 private long countOfResponseHeaderBytesReceived = 0; + /** + * 获取响应头大小 + * + * @return 响应头大小 + */ public long getCountOfResponseHeaderBytesReceived() { return countOfResponseHeaderBytesReceived; } + /** + * 设置响应头大小 + * + * @param countOfResponseHeaderBytesReceived 响应头大小 + */ public void setCountOfResponseHeaderBytesReceived(long countOfResponseHeaderBytesReceived) { this.countOfResponseHeaderBytesReceived = countOfResponseHeaderBytesReceived; } @@ -268,10 +507,20 @@ public void setCountOfResponseHeaderBytesReceived(long countOfResponseHeaderByte // http 响应体大小【自定义对象,请保证对象的此属性不为空】 private long countOfResponseBodyBytesReceived = 0; + /** + * 获取响应体接收的大小 + * + * @return 响应体接收的大小 + */ public long getCountOfResponseBodyBytesReceived() { return countOfResponseBodyBytesReceived; } + /** + * 设置响应体接收的大小 + * + * @param countOfResponseBodyBytesReceived 响应体接收的大小 + */ public void setCountOfResponseBodyBytesReceived(long countOfResponseBodyBytesReceived) { this.countOfResponseBodyBytesReceived = countOfResponseBodyBytesReceived; } @@ -279,10 +528,20 @@ public void setCountOfResponseBodyBytesReceived(long countOfResponseBodyBytesRec // http 请求本地 IP【自定义对象,请保证对象的此属性不为空】 private String localAddress; + /** + * 获取 localAddress + * + * @return localAddress + */ public String getLocalAddress() { return localAddress; } + /** + * 设置 localAddress + * + * @param localAddress localAddress + */ public void setLocalAddress(String localAddress) { this.localAddress = localAddress; } @@ -290,10 +549,20 @@ public void setLocalAddress(String localAddress) { // http 请求本地端口【自定义对象,请保证对象的此属性不为空】 private Integer localPort; + /** + * 获取 local port + * + * @return local port + */ public Integer getLocalPort() { return localPort; } + /** + * 设置 local port + * + * @param localPort local port + */ public void setLocalPort(Integer localPort) { this.localPort = localPort; } @@ -301,10 +570,20 @@ public void setLocalPort(Integer localPort) { // http 请求远程 IP【自定义对象,请保证对象的此属性不为空】 private String remoteAddress; + /** + * 获取 server address + * + * @return server address + */ public String getRemoteAddress() { return remoteAddress; } + /** + * 设置 server address + * + * @param remoteAddress server address + */ public void setRemoteAddress(String remoteAddress) { this.remoteAddress = remoteAddress; } @@ -312,44 +591,94 @@ public void setRemoteAddress(String remoteAddress) { // http 请求远程端口【自定义对象,请保证对象的此属性不为空】 private Integer remotePort; + /** + * 获取 server port + * + * @return server port + */ public Integer getRemotePort() { return remotePort; } + /** + * 设置 server port + * + * @param remotePort server port + */ public void setRemotePort(Integer remotePort) { this.remotePort = remotePort; } private long totalBytes = 0; + /** + * 获取 dns 耗时时间 + * + * @return dns 耗时时间 + */ public long totalDnsTime() { return time(domainLookupStartDate, domainLookupEndDate); } + /** + * 获取 建立连接耗时时间 + * + * @return 建立连接耗时时间 + */ public long totalConnectTime() { return time(connectStartDate, connectEndDate); } + /** + * 获取 tls 耗时时间 + * + * @return tls 耗时时间 + */ public long totalSecureConnectTime() { return time(secureConnectionStartDate, secureConnectionEndDate); } + /** + * 获取请求耗时时间 + * + * @return 请求耗时时间 + */ public long totalRequestTime() { return time(requestStartDate, requestEndDate); } + /** + * 获取请求等待耗时时间 + * + * @return 请求等待耗时时间 + */ public long totalWaitTime() { return time(requestEndDate, responseStartDate); } + /** + * 获取响应耗时时间 + * + * @return 响应耗时时间 + */ public long totalResponseTime() { return time(responseStartDate, responseEndDate); } + /** + * 获取请求总大小 + * + * @return 请求总大小 + */ public long totalBytes() { return totalBytes; } + /** + * 获取请求发送数据大小 + * + * @return 请求发送数据大小 + */ public Long bytesSend() { long totalBytes = totalBytes(); long bytesSend = countOfRequestHeaderBytesSent + countOfRequestBodyBytesSent; @@ -359,6 +688,11 @@ public Long bytesSend() { return bytesSend; } + /** + * 获取请求接收数据大小 + * + * @return 请求接收数据大小 + */ public Long bytesReceived() { long bytesReceived = countOfResponseHeaderBytesReceived + countOfResponseBodyBytesReceived; if (bytesReceived < 0) { @@ -367,14 +701,29 @@ public Long bytesReceived() { return bytesReceived; } + /** + * 获取请求速度 + * + * @return 请求速度 + */ public Long perceptiveSpeed() { return Utils.calculateSpeed(bytesSend() + bytesReceived(), totalElapsedTime()); } + /** + * 获取请求是否被劫持 + * + * @return 请求是否被劫持 + */ public boolean isForsureHijacked() { return hijacked != null && hijacked.contains(RequestHijacked); } + /** + * 获取请求是否可能被劫持 + * + * @return 请求是否可能被劫持 + */ public boolean isMaybeHijacked() { return hijacked != null && hijacked.contains(RequestMaybeHijacked); } diff --git a/library/src/main/java/com/qiniu/android/http/metrics/UploadTaskMetrics.java b/library/src/main/java/com/qiniu/android/http/metrics/UploadTaskMetrics.java index 11ab395b8..e2107e9d5 100644 --- a/library/src/main/java/com/qiniu/android/http/metrics/UploadTaskMetrics.java +++ b/library/src/main/java/com/qiniu/android/http/metrics/UploadTaskMetrics.java @@ -10,8 +10,16 @@ import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArrayList; +/** + * upload task metrics + * + * @hidden + */ public class UploadTaskMetrics extends UploadMetrics { + /** + * 上传的 regions + */ public ArrayList regions; private String upType; @@ -19,45 +27,70 @@ public class UploadTaskMetrics extends UploadMetrics { private List metricsKeys = new CopyOnWriteArrayList<>(); private Map metricsInfo = new ConcurrentHashMap<>(); + /** + * 构造函数 + * + * @param upType 上传类型 + */ public UploadTaskMetrics(String upType) { this.upType = upType; } - public Long requestCount(){ + /** + * 获取请求次数 + * + * @return 请求次数 + */ + public Long requestCount() { long count = 0; - for (String key : metricsInfo.keySet()){ + for (String key : metricsInfo.keySet()) { UploadRegionRequestMetrics metrics = metricsInfo.get(key); - if (metrics != null){ + if (metrics != null) { count += metrics.requestCount(); } } return count; } - public Long bytesSend(){ + /** + * 获取发送数据大小 + * + * @return 发送数据大小 + */ + public Long bytesSend() { long bytesSend = 0; - for (String key : metricsInfo.keySet()){ + for (String key : metricsInfo.keySet()) { UploadRegionRequestMetrics metrics = metricsInfo.get(key); - if (metrics != null){ + if (metrics != null) { bytesSend += metrics.bytesSend(); } } return bytesSend; } - public Long regionCount(){ + /** + * 获取上传使用区域个数 + * + * @return 上传使用区域个数 + */ + public Long regionCount() { long count = 0; - for (String key : metricsInfo.keySet()){ + for (String key : metricsInfo.keySet()) { UploadRegionRequestMetrics metrics = metricsInfo.get(key); - if (metrics !=null + if (metrics != null && metrics.region != null && metrics.region.getZoneInfo() != null - && !metrics.region.getZoneInfo().regionId.equals(ZoneInfo.EmptyRegionId)){ + && !metrics.region.getZoneInfo().regionId.equals(ZoneInfo.EmptyRegionId)) { count += 1; } } return count; } + /** + * 获取最后一个区域请求指标 + * + * @return 最后一个区域请求指标 + */ public UploadRegionRequestMetrics lastMetrics() { int size = metricsKeys.size(); if (size < 1) { @@ -68,14 +101,19 @@ public UploadRegionRequestMetrics lastMetrics() { return metricsInfo.get(key); } - public void addMetrics(UploadRegionRequestMetrics metrics){ + /** + * 添加区域请求指标 + * + * @param metrics 区域请求指标 + */ + public void addMetrics(UploadRegionRequestMetrics metrics) { if (metrics == null || metrics.region == null || metrics.region.getZoneInfo() == null - || metrics.region.getZoneInfo().regionId == null){ + || metrics.region.getZoneInfo().regionId == null) { return; } String regionId = metrics.region.getZoneInfo().regionId; UploadRegionRequestMetrics metricsOld = metricsInfo.get(regionId); - if (metricsOld != null){ + if (metricsOld != null) { metricsOld.addMetrics(metrics); } else { metricsKeys.add(regionId); @@ -83,14 +121,29 @@ public void addMetrics(UploadRegionRequestMetrics metrics){ } } + /** + * 获取上传类型 + * + * @return 上传类型 + */ public String getUpType() { return upType; } + /** + * 获取 uc query 请求指标 + * + * @return uc query 请求指标 + */ public UploadRegionRequestMetrics getUcQueryMetrics() { return ucQueryMetrics; } + /** + * 设置 uc query 请求指标 + * + * @param ucQueryMetrics uc query 请求指标 + */ public void setUcQueryMetrics(UploadRegionRequestMetrics ucQueryMetrics) { this.ucQueryMetrics = ucQueryMetrics; addMetrics(ucQueryMetrics); diff --git a/library/src/main/java/com/qiniu/android/http/networkStatus/NetworkStatusManager.java b/library/src/main/java/com/qiniu/android/http/networkStatus/NetworkStatusManager.java index 9ec112f15..c6cadd751 100644 --- a/library/src/main/java/com/qiniu/android/http/networkStatus/NetworkStatusManager.java +++ b/library/src/main/java/com/qiniu/android/http/networkStatus/NetworkStatusManager.java @@ -6,6 +6,11 @@ import org.json.JSONObject; +/** + * 网络状态管理器 + * + * @hidden + */ public class NetworkStatusManager { private static final NetworkStatusManager networkStatusManager = new NetworkStatusManager(); @@ -15,19 +20,48 @@ public class NetworkStatusManager { .setFlushCount(10) .builder(); + /** + * 获取单例 + * + * @return NetworkStatusManager 单例 + */ public static NetworkStatusManager getInstance() { return networkStatusManager; } + private NetworkStatusManager() { + } + + /** + * 获取网络状态唯一标识 + * + * @param host host + * @param ip ip + * @return 唯一标识 + */ @Deprecated public static String getNetworkStatusType(String host, String ip) { return Utils.getIpType(ip, host); } + /** + * 获取网络状态唯一标识 + * + * @param httpVersion httpVersion + * @param host host + * @param ip ip + * @return 唯一标识 + */ public static String getNetworkStatusType(String httpVersion, String host, String ip) { return Utils.getIpType(httpVersion, ip, host); } + /** + * 获取网络状态 + * + * @param type 网络状态唯一标识 + * @return 网络状态 + */ public NetworkStatus getNetworkStatus(String type) { if (type == null || type.isEmpty()) { return null; @@ -41,6 +75,12 @@ public NetworkStatus getNetworkStatus(String type) { } } + /** + * 更新网络状态 + * + * @param type 网络状态唯一标识 + * @param speed 网速 + */ public void updateNetworkStatus(String type, int speed) { if (type == null || type.isEmpty()) { return; @@ -51,16 +91,34 @@ public void updateNetworkStatus(String type, int speed) { this.cache.cache(type, status, false); } + /** + * default speed + */ protected static final int DefaultSpeed = 600; + /** + * 网络状态 + * + * @hidden + */ public static class NetworkStatus implements Cache.Object { private int speed = DefaultSpeed; + /** + * 获取速度 + * + * @return 速度 + */ public int getSpeed() { return speed; } + /** + * 设置速度 + * + * @param speed speed + */ public void setSpeed(int speed) { this.speed = speed; } @@ -68,6 +126,11 @@ public void setSpeed(int speed) { private NetworkStatus() { } + /** + * 构造函数 + * + * @param jsonObject 网络状态 json 数据 + */ public NetworkStatus(JSONObject jsonObject) { if (jsonObject == null) { return; @@ -79,6 +142,11 @@ public NetworkStatus(JSONObject jsonObject) { } } + /** + * 获取 json 数据 + * + * @return json 数据 + */ @Override public JSONObject toJson() { JSONObject jsonObject = new JSONObject(); diff --git a/library/src/main/java/com/qiniu/android/http/networkStatus/UploadServerNetworkStatus.java b/library/src/main/java/com/qiniu/android/http/networkStatus/UploadServerNetworkStatus.java index 589ed8b78..1e78af4ae 100644 --- a/library/src/main/java/com/qiniu/android/http/networkStatus/UploadServerNetworkStatus.java +++ b/library/src/main/java/com/qiniu/android/http/networkStatus/UploadServerNetworkStatus.java @@ -2,13 +2,35 @@ import com.qiniu.android.http.request.IUploadServer; +/** + * UploadServerNetworkStatus + * + * @hidden + */ public class UploadServerNetworkStatus { + private UploadServerNetworkStatus() { + } + + /** + * 获取网络状态较好的 server + * + * @param serverA serverA + * @param serverB serverB + * @return 网络状态较好的 server + */ public static IUploadServer getBetterNetworkServer(IUploadServer serverA, IUploadServer serverB) { return isServerNetworkBetter(serverA, serverB) ? serverA : serverB; } - // 如果两个 Server 网速相同且类别相同优先使用 serverA,类别不同优先使用 Http3 + /** + * serverA 网络状态是否较 serverB 好 + * 如果两个 Server 网速相同且类别相同优先使用 serverA,类别不同 HTTP/3 较好 + * + * @param serverA serverA + * @param serverB serverB + * @return 是否较好 + */ public static boolean isServerNetworkBetter(IUploadServer serverA, IUploadServer serverB) { if (serverA == null) { return false; diff --git a/library/src/main/java/com/qiniu/android/http/request/IRequestClient.java b/library/src/main/java/com/qiniu/android/http/request/IRequestClient.java index a640501ce..ad1f6e8d7 100644 --- a/library/src/main/java/com/qiniu/android/http/request/IRequestClient.java +++ b/library/src/main/java/com/qiniu/android/http/request/IRequestClient.java @@ -6,33 +6,100 @@ import org.json.JSONObject; - +/** + * 请求 Client 抽象 + */ public abstract class IRequestClient { + /** + * 请求进度协议 + */ public interface Progress { + + /** + * 请求进度回调 + * + * @param totalBytesWritten totalBytesWritten + * @param totalBytesExpectedToWrite totalBytesExpectedToWrite + */ void progress(long totalBytesWritten, long totalBytesExpectedToWrite); } + /** + * 请求完成回调 + */ public interface CompleteHandler { + + /** + * 请求完成回调 + * + * @param responseInfo 请求响应信息 + * @param metrics 请求指标 + * @param response 请求响应信息 + */ void complete(ResponseInfo responseInfo, UploadSingleRequestMetrics metrics, JSONObject response); } + /** + * 构造函数 + */ + protected IRequestClient() { + } + + /** + * 触发请求 + * + * @param request 请求信息 + * @param options 可选信息 + * @param progress 进度回调 + * @param complete 完成回调 + */ public abstract void request(Request request, Options options, Progress progress, CompleteHandler complete); + /** + * 取消 + */ public abstract void cancel(); + /** + * 获取 ClientId + * + * @return ClientId + */ public String getClientId() { return "customized"; } + /** + * 可选信息 + */ public static class Options { + + /** + * 上传请求的 Server + */ public final IUploadServer server; + + /** + * 是否使用异步 + */ public final boolean isAsync; + + /** + * 请求的代理 + */ public final ProxyConfiguration connectionProxy; + /** + * 构造函数 + * + * @param server 上传请求的 Server + * @param isAsync 是否使用异步 + * @param connectionProxy 请求的代理 + */ public Options(IUploadServer server, boolean isAsync, ProxyConfiguration connectionProxy) { this.server = server; this.isAsync = isAsync; diff --git a/library/src/main/java/com/qiniu/android/http/request/IUploadRegion.java b/library/src/main/java/com/qiniu/android/http/request/IUploadRegion.java index f9f595928..cdd11b126 100644 --- a/library/src/main/java/com/qiniu/android/http/request/IUploadRegion.java +++ b/library/src/main/java/com/qiniu/android/http/request/IUploadRegion.java @@ -3,17 +3,56 @@ import com.qiniu.android.common.ZoneInfo; import com.qiniu.android.http.ResponseInfo; +/** + * 上传区域 + * + * @hidden + */ public interface IUploadRegion { + /** + * 是否有效 + * + * @return 是否有效 + */ boolean isValid(); + /** + * 是否和另一个 region 相等 + * + * @param region 另一个 region + * @return 是否和另一个 region 相等 + */ boolean isEqual(IUploadRegion region); + /** + * 获取 ZoneInfo + * + * @return ZoneInfo + */ ZoneInfo getZoneInfo(); + /** + * 配置 ZoneInfo + * + * @param zoneInfo ZoneInfo + */ void setupRegionData(ZoneInfo zoneInfo); + /** + * 获取下一个上传的 Server 信息 + * + * @param requestState 请求状态 + * @param responseInfo 请求响应信息 + * @param freezeServer 冻结的 Server 信息 + * @return 下一个上传的 Server 信息 + */ IUploadServer getNextServer(UploadRequestState requestState, ResponseInfo responseInfo, IUploadServer freezeServer); + /** + * 更新 host 的 IP 缓存信息 + * + * @param host host + */ void updateIpListFormHost(String host); } diff --git a/library/src/main/java/com/qiniu/android/http/request/IUploadServer.java b/library/src/main/java/com/qiniu/android/http/request/IUploadServer.java index f712a705c..c35989397 100644 --- a/library/src/main/java/com/qiniu/android/http/request/IUploadServer.java +++ b/library/src/main/java/com/qiniu/android/http/request/IUploadServer.java @@ -3,11 +3,39 @@ import java.net.InetAddress; +/** + * upload server 信息 + * + * @hidden + */ public abstract class IUploadServer { + + /** + * HTTP/1.1 + */ public static String HttpVersion1 = "http_version_1"; + + /** + * HTTP/2 + */ public static String HttpVersion2 = "http_version_2"; + + /** + * HTTP/3 + */ public static String HttpVersion3 = "http_version_3"; + /** + * 构造函数 + */ + protected IUploadServer() { + } + + /** + * 是否使用 HTTP/3 + * + * @return 是否使用 HTTP/3 + */ public boolean isHttp3() { String httpVersion = getHttpVersion(); if (httpVersion == null) { @@ -16,6 +44,11 @@ public boolean isHttp3() { return httpVersion.equals(IUploadServer.HttpVersion3); } + /** + * 是否使用 HTTP/2 + * + * @return 是否使用 HTTP/2 + */ public boolean isHttp2() { String httpVersion = getHttpVersion(); if (httpVersion == null) { @@ -24,19 +57,54 @@ public boolean isHttp2() { return httpVersion.equals(IUploadServer.HttpVersion2); } + /** + * 获取 ServerId + * + * @return ServerId + */ public abstract String getServerId(); + /** + * 获取 HttpVersion + * + * @return HttpVersion + */ public abstract String getHttpVersion(); + /** + * 获取 Host + * + * @return Host + */ public abstract String getHost(); + /** + * 获取 IP + * + * @return IP + */ public abstract String getIp(); + /** + * 获取 DNS 解析 Source + * + * @return DNS 解析 Source + */ public abstract String getSource(); + /** + * 获取 DNS 解析时间戳 + * + * @return DNS 解析时间戳 + */ public abstract Long getIpPrefetchedTime(); - public InetAddress getInetAddress(){ + /** + * 获取 DNS 解析信息 + * + * @return DNS 解析信息 + */ + public InetAddress getInetAddress() { String ip = getIp(); String host = getHost(); if (getHost() == null || ip == null || ip.length() == 0) { diff --git a/library/src/main/java/com/qiniu/android/http/request/Request.java b/library/src/main/java/com/qiniu/android/http/request/Request.java index 0519daae6..d73cd2497 100644 --- a/library/src/main/java/com/qiniu/android/http/request/Request.java +++ b/library/src/main/java/com/qiniu/android/http/request/Request.java @@ -3,24 +3,84 @@ import java.util.HashMap; import java.util.Map; +/** + * request + * + * @hidden + */ public class Request { + /** + * 请求方式:HEAD + */ public static final String HttpMethodHEAD = "HEAD"; + + /** + * 请求方式:GET + */ public static final String HttpMethodGet = "GET"; + + /** + * 请求方式:POST + */ public static final String HttpMethodPOST = "POST"; + + /** + * 请求方式:PUT + */ public static final String HttpMethodPUT = "PUT"; + /** + * 请求 Url + */ public final String urlString; + + /** + * 请求方式 + */ public final String httpMethod; + + /** + * 请求 header + */ public final Map allHeaders; + + /** + * 请求超时时间 + */ public final int timeout; + + /** + * 请求建立连接超时时间 + */ public final int connectTimeout; + + /** + * 请求读超时时间 + */ public final int readTimeout; + + /** + * 请求写超时时间 + */ public final int writeTimeout; + + /** + * 请求 body + */ public byte[] httpBody; private String host; + /** + * 构造函数 + * + * @param urlString 请求 url + * @param httpMethod 请求方式 + * @param allHeaders 请求头 + * @param httpBody 请求体 + * @param timeout 请求超时时间 + */ public Request(String urlString, String httpMethod, Map allHeaders, @@ -31,6 +91,17 @@ public Request(String urlString, (timeout - 10) >> 1); } + /** + * 构造函数 + * + * @param urlString 请求 url + * @param httpMethod 请求方式 + * @param allHeaders 请求头 + * @param httpBody 请求体 + * @param connectTimeout 请求建立连接超时时间 + * @param readTimeout 请求读超时时间 + * @param writeTimeout 请求写超时时间 + */ public Request(String urlString, String httpMethod, Map allHeaders, @@ -62,14 +133,29 @@ void setHost(String host) { this.host = host; } + /** + * 获取 host + * + * @return host + */ public String getHost() { return host; } + /** + * 请求是否有效 + * + * @return 是否有效 + */ protected boolean isValid() { return this.urlString == null || httpMethod == null; } + /** + * copy 请求,但是不 copy body + * + * @return 新的请求对象 + */ public Request copyWithoutBody() { Request request = new Request(urlString, httpMethod, allHeaders, null, connectTimeout, readTimeout, writeTimeout); diff --git a/library/src/main/java/com/qiniu/android/http/request/RequestTransaction.java b/library/src/main/java/com/qiniu/android/http/request/RequestTransaction.java index 1dce75c9f..8356d50d1 100644 --- a/library/src/main/java/com/qiniu/android/http/request/RequestTransaction.java +++ b/library/src/main/java/com/qiniu/android/http/request/RequestTransaction.java @@ -26,6 +26,11 @@ import java.util.Map; import java.util.Set; +/** + * 请求事务 + * + * @hidden + */ public class RequestTransaction { private final Configuration config; @@ -39,17 +44,40 @@ public class RequestTransaction { private HttpRegionRequest regionRequest; + /** + * 构造函数 + * + * @param hosts hosts + * @param token token + */ public RequestTransaction(List hosts, UpToken token) { this(new Configuration.Builder().build(), UploadOptions.defaultOptions(), hosts, null, null, token); } + /** + * 构造函数 + * + * @param hosts hosts + * @param regionId 区域 ID + * @param token 上传 Token + */ public RequestTransaction(List hosts, String regionId, UpToken token) { this(new Configuration.Builder().build(), UploadOptions.defaultOptions(), hosts, regionId, null, token); } + /** + * 构造函数 + * + * @param config 配置信息 + * @param uploadOption 上传选项 + * @param hosts hosts + * @param regionId 区域 ID + * @param key 上传保存的 key + * @param token 上传的 Token + */ public RequestTransaction(Configuration config, UploadOptions uploadOption, List hosts, @@ -62,6 +90,16 @@ public RequestTransaction(Configuration config, this.initData(region, region); } + /** + * 构造函数 + * + * @param config 请求事务配置 + * @param uploadOption 请求选项 + * @param targetRegion 请求的区域 + * @param currentRegion 当前的区域 + * @param key 保存的 key + * @param token 上传的 token + */ public RequestTransaction(Configuration config, UploadOptions uploadOption, IUploadRegion targetRegion, @@ -101,6 +139,12 @@ private void initData(IUploadRegion targetRegion, } + /** + * 查询上传域名 + * + * @param isAsync 是否为同步请求 + * @param completeHandler 请求结束回调 + */ public void queryUploadHosts(boolean isAsync, final RequestCompleteHandler completeHandler) { requestInfo.requestType = UploadRequestInfo.RequestTypeUCQuery; @@ -123,6 +167,15 @@ public void complete(ResponseInfo responseInfo, UploadRegionRequestMetrics reque }); } + /** + * 上传表单接口 + * + * @param data 上传数据 + * @param fileName 文件名 + * @param isAsync 是否为同步 + * @param progressHandler 进度回调 + * @param completeHandler 结束回调 + */ public void uploadFormData(byte[] data, String fileName, boolean isAsync, @@ -194,6 +247,16 @@ public void complete(ResponseInfo responseInfo, UploadRegionRequestMetrics reque }); } + /** + * make block api + * + * @param blockOffset block offset + * @param blockSize block 大小 + * @param firstChunkData 第一块数据 + * @param isAsync 是否为异步 + * @param progressHandler 进度回调 + * @param completeHandler 结束回调 + */ public void makeBlock(long blockOffset, long blockSize, byte[] firstChunkData, @@ -239,6 +302,17 @@ public void complete(ResponseInfo responseInfo, UploadRegionRequestMetrics reque }); } + /** + * upload chunk api + * + * @param blockContext block ctx + * @param blockOffset block offset + * @param chunkData chunk data + * @param chunkOffset chunk offset + * @param isAsync 是佛为异步 + * @param progressHandler 进度回调 + * @param completeHandler 结束回调 + */ public void uploadChunk(String blockContext, long blockOffset, byte[] chunkData, @@ -286,6 +360,15 @@ public void complete(ResponseInfo responseInfo, UploadRegionRequestMetrics reque }); } + /** + * make file api + * + * @param fileSize 文件大小 + * @param fileName 文件名 + * @param blockContexts block ctxs + * @param isAsync 是否为异步 + * @param completeHandler 结束回调 + */ public void makeFile(long fileSize, String fileName, String[] blockContexts, @@ -355,6 +438,12 @@ public void complete(ResponseInfo responseInfo, UploadRegionRequestMetrics reque } + /** + * init part api + * + * @param isAsync 是否为异步 + * @param completeHandler 结束回调 + */ public void initPart(boolean isAsync, final RequestCompleteHandler completeHandler) { requestInfo.requestType = UploadRequestInfo.RequestTypeInitParts; @@ -385,6 +474,16 @@ public void complete(ResponseInfo responseInfo, UploadRegionRequestMetrics reque } + /** + * upload part api + * + * @param isAsync 是否为异步 + * @param uploadId 上传 ID + * @param partIndex part index + * @param partData part data + * @param progressHandler 进度回调 + * @param completeHandler 完成回调 + */ public void uploadPart(boolean isAsync, String uploadId, int partIndex, @@ -437,6 +536,15 @@ public void complete(ResponseInfo responseInfo, UploadRegionRequestMetrics reque }); } + /** + * complete part api + * + * @param isAsync 是否为同步 + * @param fileName 文件名 + * @param uploadId 上传 ID + * @param partInfoArray part info + * @param completeHandler 结束回调 + */ public void completeParts(boolean isAsync, String fileName, String uploadId, @@ -501,6 +609,14 @@ public void complete(ResponseInfo responseInfo, UploadRegionRequestMetrics reque }); } + /** + * report log api + * + * @param logData 日志数据 + * @param logClientId 日志 client id + * @param isAsync 是否为同步 + * @param completeHandler 结束回调 + */ public void reportLog(byte[] logData, String logClientId, boolean isAsync, @@ -533,6 +649,12 @@ public void complete(ResponseInfo responseInfo, UploadRegionRequestMetrics reque }); } + /** + * server config + * + * @param isAsync 是否为异步 + * @param completeHandler 结束回调 + */ public void serverConfig(boolean isAsync, final RequestCompleteHandler completeHandler) { requestInfo.requestType = UploadRequestInfo.RequestTypeServerConfig; @@ -556,6 +678,12 @@ public void complete(ResponseInfo responseInfo, UploadRegionRequestMetrics reque }); } + /** + * server user config + * + * @param isAsync 是否为异步 + * @param completeHandler 完成回调 + */ public void serverUserConfig(boolean isAsync, final RequestCompleteHandler completeHandler) { requestInfo.requestType = UploadRequestInfo.RequestTypeServerUserConfig; @@ -604,7 +732,20 @@ private void completeAction(ResponseInfo responseInfo, } } + /** + * 请求结束回调 + * + * @hidden + */ public interface RequestCompleteHandler { + + /** + * 请求结束回调 + * + * @param responseInfo 请求响应信息 + * @param requestMetrics 请求指标 + * @param response 请求响应 + */ void complete(ResponseInfo responseInfo, UploadRegionRequestMetrics requestMetrics, JSONObject response); diff --git a/library/src/main/java/com/qiniu/android/http/request/UploadRequestState.java b/library/src/main/java/com/qiniu/android/http/request/UploadRequestState.java index 811e610d3..0612038d1 100644 --- a/library/src/main/java/com/qiniu/android/http/request/UploadRequestState.java +++ b/library/src/main/java/com/qiniu/android/http/request/UploadRequestState.java @@ -1,12 +1,28 @@ package com.qiniu.android.http.request; +/** + * 上传状态 + * + * @hidden + */ public class UploadRequestState { private boolean couldUseHttp3; private boolean isUseOldServer; private boolean isUserCancel; - public boolean couldUseHttp3(){ + /** + * 构造函数 + */ + public UploadRequestState() { + } + + /** + * 是否可以使用 HTTP/3 + * + * @return 是否可以使用 HTTP/3 + */ + public boolean couldUseHttp3() { return couldUseHttp3; } @@ -14,7 +30,7 @@ void setCouldUseHttp3(boolean couldUseHttp3) { this.couldUseHttp3 = couldUseHttp3; } - boolean isUserCancel(){ + boolean isUserCancel() { return isUserCancel; } @@ -22,14 +38,29 @@ void setUserCancel(boolean isUserCancel) { this.isUserCancel = isUserCancel; } + /** + * 是否使用支持 sni 的域名 + * + * @return 是否使用支持 sni 的域名 + */ public boolean isUseOldServer() { return isUseOldServer; } + /** + * 设置是否使用支持 sni 的域名 + * + * @param useOldServer 是否使用支持 sni 的域名 + */ public void setUseOldServer(boolean useOldServer) { isUseOldServer = useOldServer; } + /** + * clone + * + * @return clone 后的对象 + */ protected UploadRequestState clone() { UploadRequestState state = new UploadRequestState(); state.isUseOldServer = isUseOldServer; diff --git a/library/src/main/java/com/qiniu/android/http/request/handler/CheckCancelHandler.java b/library/src/main/java/com/qiniu/android/http/request/handler/CheckCancelHandler.java index cabda10d7..6742cdd48 100644 --- a/library/src/main/java/com/qiniu/android/http/request/handler/CheckCancelHandler.java +++ b/library/src/main/java/com/qiniu/android/http/request/handler/CheckCancelHandler.java @@ -1,5 +1,16 @@ package com.qiniu.android.http.request.handler; +/** + * CheckCancelHandler + * + * @hidden + */ public interface CheckCancelHandler { + + /** + * 查看是否取消 + * + * @return 是否取消 + */ boolean checkCancel(); } diff --git a/library/src/main/java/com/qiniu/android/http/request/handler/RequestProgressHandler.java b/library/src/main/java/com/qiniu/android/http/request/handler/RequestProgressHandler.java index ca5765aab..6be42c0f3 100644 --- a/library/src/main/java/com/qiniu/android/http/request/handler/RequestProgressHandler.java +++ b/library/src/main/java/com/qiniu/android/http/request/handler/RequestProgressHandler.java @@ -1,5 +1,17 @@ package com.qiniu.android.http.request.handler; +/** + * 请求进度回调 + * + * @hidden + */ public interface RequestProgressHandler { + + /** + * 请求进度回调 + * + * @param totalBytesWritten 已发送数据大小 + * @param totalBytesExpectedToWrite 总数据大小 + */ void progress(long totalBytesWritten, long totalBytesExpectedToWrite); } diff --git a/library/src/main/java/com/qiniu/android/http/request/handler/RequestShouldRetryHandler.java b/library/src/main/java/com/qiniu/android/http/request/handler/RequestShouldRetryHandler.java index 39efcbe8e..c8a3c69df 100644 --- a/library/src/main/java/com/qiniu/android/http/request/handler/RequestShouldRetryHandler.java +++ b/library/src/main/java/com/qiniu/android/http/request/handler/RequestShouldRetryHandler.java @@ -4,6 +4,19 @@ import org.json.JSONObject; +/** + * 请求重试回调 + * + * @hidden + */ public interface RequestShouldRetryHandler { + + /** + * 请求重试回调 + * + * @param responseInfo 上次请求的响应信息 + * @param response 上次请求的响应信息 + * @return 是否可以重试 + */ boolean shouldRetry(ResponseInfo responseInfo, JSONObject response); } diff --git a/library/src/main/java/com/qiniu/android/http/request/httpclient/ByteBody.java b/library/src/main/java/com/qiniu/android/http/request/httpclient/ByteBody.java index 4e9a7de3f..4b89d8e26 100644 --- a/library/src/main/java/com/qiniu/android/http/request/httpclient/ByteBody.java +++ b/library/src/main/java/com/qiniu/android/http/request/httpclient/ByteBody.java @@ -9,16 +9,23 @@ /** * Created by yangsen on 2020/6/10 + * + * @hidden */ public class ByteBody extends RequestBody { - private static final int SEGMENT_SIZE = 1024*16; // okio.Segment.SIZE + private static final int SEGMENT_SIZE = 1024 * 16; // okio.Segment.SIZE private final MediaType mediaType; private final byte[] body; - public ByteBody(MediaType mediaType, - byte[] body){ + /** + * 请求体 + * + * @param mediaType mediaType + * @param body 请求体 byte 数组 + */ + public ByteBody(MediaType mediaType, byte[] body) { this.mediaType = mediaType; this.body = body; @@ -39,7 +46,7 @@ public void writeTo(BufferedSink bufferedSink) throws IOException { int byteOffset = 0; int byteSize = SEGMENT_SIZE; - while (byteOffset < body.length){ + while (byteOffset < body.length) { byteSize = Math.min(byteSize, body.length - byteOffset); RequestBody requestBody = getRequestBodyWithRange(byteOffset, byteSize); requestBody.writeTo(bufferedSink); @@ -50,7 +57,7 @@ public void writeTo(BufferedSink bufferedSink) throws IOException { } - private RequestBody getRequestBodyWithRange(int location, int size){ + private RequestBody getRequestBodyWithRange(int location, int size) { byte[] data = Arrays.copyOfRange(body, location, location + size); return RequestBody.create(contentType(), data); } diff --git a/library/src/main/java/com/qiniu/android/http/request/httpclient/CountingRequestBody.java b/library/src/main/java/com/qiniu/android/http/request/httpclient/CountingRequestBody.java index e7e546ee1..18914d2c9 100644 --- a/library/src/main/java/com/qiniu/android/http/request/httpclient/CountingRequestBody.java +++ b/library/src/main/java/com/qiniu/android/http/request/httpclient/CountingRequestBody.java @@ -16,6 +16,8 @@ /** * Created by bailong on 16/1/8. + * + * @hidden */ public final class CountingRequestBody extends RequestBody { private static final int SEGMENT_SIZE = 2048; // okio.Segment.SIZE @@ -26,6 +28,14 @@ public final class CountingRequestBody extends RequestBody { private final long totalSize; private final CancellationHandler cancellationHandler; + /** + * CountingRequestBody 构造函数 + * + * @param body 请求体 + * @param progress 请求进度回调 + * @param totalSize 请求体总大小 + * @param cancellationHandler 取消函数 + */ public CountingRequestBody(RequestBody body, ProgressHandler progress, long totalSize, CancellationHandler cancellationHandler) { this.body = body; @@ -34,16 +44,33 @@ public CountingRequestBody(RequestBody body, ProgressHandler progress, long tota this.cancellationHandler = cancellationHandler; } + /** + * 获取请求体大小 + * + * @return 请求体大小 + * @throws IOException 异常 + */ @Override public long contentLength() throws IOException { return body.contentLength(); } + /** + * 获取请求 ContentType + * + * @return 请求 ContentType + */ @Override public MediaType contentType() { return body.contentType(); } + /** + * 写入数据 + * + * @param sink BufferedSink + * @throws IOException 异常 + */ @Override public void writeTo(BufferedSink sink) throws IOException { BufferedSink bufferedSink; @@ -56,14 +83,31 @@ public void writeTo(BufferedSink sink) throws IOException { bufferedSink.flush(); } + /** + * 请求进度 Sink + * + * @hidden + */ protected final class CountingSink extends ForwardingSink { private int bytesWritten = 0; + /** + * 构造方法 + * + * @param delegate Sink + */ public CountingSink(Sink delegate) { super(delegate); } + /** + * 写入数据 + * + * @param source Buffer + * @param byteCount byteCount + * @throws IOException 异常 + */ @Override public void write(Buffer source, long byteCount) throws IOException { if (cancellationHandler == null && progress == null) { diff --git a/library/src/main/java/com/qiniu/android/http/request/httpclient/MultipartBody.java b/library/src/main/java/com/qiniu/android/http/request/httpclient/MultipartBody.java index 8cdcb3f17..5742cbb6d 100644 --- a/library/src/main/java/com/qiniu/android/http/request/httpclient/MultipartBody.java +++ b/library/src/main/java/com/qiniu/android/http/request/httpclient/MultipartBody.java @@ -34,7 +34,11 @@ import okio.BufferedSink; import okio.ByteString; -/** An RFC 2387-compliant request body. */ +/** + * An RFC 2387-compliant request body. + * + * @hidden + */ public final class MultipartBody extends RequestBody { /** * The "mixed" subtype of "multipart" is intended for use when the body parts are independent and @@ -120,28 +124,55 @@ static StringBuilder appendQuotedString(StringBuilder target, String key) { return target; } + /** + * 获取 type + * + * @return MediaType + */ public MediaType type() { return originalType; } + /** + * 获取 boundary + * + * @return boundary + */ public String boundary() { return boundary.utf8(); } - /** The number of parts in this multipart body. */ + /** + * The number of parts in this multipart body. + * + * @return size + */ public int size() { return parts.size(); } + /** + * 获取 parts + * + * @return parts + */ public List parts() { return parts; } + /** + * 构造函数 + * + * @param index index + * @return Part + */ public Part part(int index) { return parts.get(index); } - /** A combination of {@link #type()} and {@link #boundary()}. */ + /** + * A combination of {@link #type()} and {@link #boundary()}. + */ @Override public MediaType contentType() { return contentType; @@ -233,6 +264,11 @@ private long writeOrCountBytes(BufferedSink sink, boolean countBytes) throws IOE return byteCount; } + /** + * Part + * + * @hidden + */ public static final class Part { final Headers headers; final RequestBody body; @@ -242,10 +278,23 @@ private Part(Headers headers, RequestBody body) { this.body = body; } + /** + * 构造函数 + * + * @param body body + * @return Part + */ public static Part create(RequestBody body) { return create(null, body); } + /** + * 构造函数 + * + * @param headers headers + * @param body body + * @return Part + */ public static Part create(Headers headers, RequestBody body) { if (body == null) { throw new NullPointerException("body == null"); @@ -259,10 +308,25 @@ public static Part create(Headers headers, RequestBody body) { return new Part(headers, body); } + /** + * 构造函数 + * + * @param name name + * @param value value + * @return Part + */ public static Part createFormData(String name, String value) { return createFormData(name, null, RequestBody.create(null, value)); } + /** + * 构造函数 + * + * @param name name + * @param filename filename + * @param body body + * @return Part + */ public static Part createFormData(String name, String filename, RequestBody body) { if (name == null) { throw new NullPointerException("name == null"); @@ -278,24 +342,47 @@ public static Part createFormData(String name, String filename, RequestBody body return create(Headers.of("Content-Disposition", disposition.toString()), body); } + /** + * header + * + * @return header + */ public Headers headers() { return headers; } + /** + * body + * + * @return body + */ public RequestBody body() { return body; } } + /** + * Builder + * + * @hidden + */ public static final class Builder { private final ByteString boundary; private final List parts = new ArrayList<>(); private MediaType type = MIXED; + /** + * 构造方法 + */ public Builder() { this(UUID.randomUUID().toString()); } + /** + * 构造方法 + * + * @param boundary boundary + */ public Builder(String boundary) { this.boundary = ByteString.encodeUtf8(boundary); } @@ -303,6 +390,9 @@ public Builder(String boundary) { /** * Set the MIME type. Expected values for {@code type} are {@link #MIXED} (the default), {@link * #ALTERNATIVE}, {@link #DIGEST}, {@link #PARALLEL} and {@link #FORM}. + * + * @param type MediaType + * @return Builder */ public Builder setType(MediaType type) { if (type == null) { @@ -315,34 +405,67 @@ public Builder setType(MediaType type) { return this; } - /** Add a part to the body. */ + /** + * Add a part to the body. + * + * @param body body + * @return Builder + */ public Builder addPart(RequestBody body) { return addPart(Part.create(body)); } - /** Add a part to the body. */ + /** + * Add a part to the body. + * + * @param headers headers + * @param body body + * @return Builder + */ public Builder addPart(Headers headers, RequestBody body) { return addPart(Part.create(headers, body)); } - /** Add a form data part to the body. */ + /** + * Add a form data part to the body. + * + * @param name name + * @param value value + * @return Builder + */ public Builder addFormDataPart(String name, String value) { return addPart(Part.createFormData(name, value)); } - /** Add a form data part to the body. */ + /** + * Add a form data part to the body. + * + * @param name name + * @param filename filename + * @param body body + * @return Builder + */ public Builder addFormDataPart(String name, String filename, RequestBody body) { return addPart(Part.createFormData(name, filename, body)); } - /** Add a part to the body. */ + /** + * Add a part to the body. + * + * @param part part + * @return Builder + */ public Builder addPart(Part part) { if (part == null) throw new NullPointerException("part == null"); parts.add(part); return this; } - /** Assemble the specified parts into a request body. */ + /** + * Assemble the specified parts into a request body. + * + * @return MultipartBody + */ public MultipartBody build() { if (parts.isEmpty()) { throw new IllegalStateException("Multipart body must have at least one part."); diff --git a/library/src/main/java/com/qiniu/android/http/request/httpclient/SystemHttpClient.java b/library/src/main/java/com/qiniu/android/http/request/httpclient/SystemHttpClient.java index a01eb13d7..4ae5b74a2 100644 --- a/library/src/main/java/com/qiniu/android/http/request/httpclient/SystemHttpClient.java +++ b/library/src/main/java/com/qiniu/android/http/request/httpclient/SystemHttpClient.java @@ -50,11 +50,31 @@ import static com.qiniu.android.http.ResponseInfo.NetworkError; +/** + * system client + * + * @hidden + */ public class SystemHttpClient extends IRequestClient { + /** + * 请求头 key:Content-Type + */ public static final String ContentTypeHeader = "Content-Type"; + + /** + * 默认请求的 Content-Type + */ public static final String DefaultMime = "application/octet-stream"; + + /** + * 请求体为 Json 的 Content-Type + */ public static final String JsonMime = "application/json"; + + /** + * 表单请求的 Content-Type + */ public static final String FormMime = "application/x-www-form-urlencoded"; private boolean hasHandleComplete = false; @@ -68,6 +88,22 @@ public class SystemHttpClient extends IRequestClient { private Progress requestProgress; private CompleteHandler completeHandler; + /** + * 构造函数 + * 内部使用,禁止外部调用 + */ + public SystemHttpClient() { + } + + /** + * 构造函数 + * + * @param request 请求 + * @param isAsync 是否异步 + * @param connectionProxy 代理 + * @param progress 进度回调 + * @param complete 完成回调 + */ public void request(Request request, boolean isAsync, ProxyConfiguration connectionProxy, @@ -76,6 +112,14 @@ public void request(Request request, request(request, new Options(null, isAsync, connectionProxy), progress, complete); } + /** + * 构造函数 + * + * @param request 请求信息 + * @param options 可选信息 + * @param progress 进度回调 + * @param complete 完成回调 + */ @Override public void request(Request request, Options options, @@ -156,6 +200,9 @@ public void run() { } } + /** + * 取消请求 + */ @Override public synchronized void cancel() { if (call != null && !call.isCanceled()) { @@ -163,6 +210,11 @@ public synchronized void cancel() { } } + /** + * client id + * + * @return client id + */ @Override public String getClientId() { return "okhttp"; diff --git a/library/src/main/java/com/qiniu/android/http/serverRegion/HttpServerManager.java b/library/src/main/java/com/qiniu/android/http/serverRegion/HttpServerManager.java index 2bf54a65b..ae3b30b8a 100644 --- a/library/src/main/java/com/qiniu/android/http/serverRegion/HttpServerManager.java +++ b/library/src/main/java/com/qiniu/android/http/serverRegion/HttpServerManager.java @@ -5,19 +5,34 @@ import java.util.Locale; import java.util.concurrent.ConcurrentHashMap; +/** + * HttpServerManager + * + * @hidden + */ public class HttpServerManager { private ConcurrentHashMap serversInfo = new ConcurrentHashMap<>(); private final static HttpServerManager manager = new HttpServerManager(); + private HttpServerManager() { + } + + /** + * 单例对象 + * + * @return 单例对象 + */ public static HttpServerManager getInstance() { return manager; } /** * 添加支持 http3 的 Host/ip 组合 - * @param host 支持 http3 的 Host - * @param ip 支持 http3 Host 对应的 ip + * + * @param host 支持 http3 的 Host + * @param ip 支持 http3 Host 对应的 ip * @param liveDuration 有效时间 单位: 秒 + * @return 是否添加 */ public boolean addHttp3Server(String host, String ip, int liveDuration) { if (host == null || host.length() == 0 || ip == null || ip.length() == 0 || liveDuration < 0) { @@ -32,8 +47,10 @@ public boolean addHttp3Server(String host, String ip, int liveDuration) { /** * Host/ip 组合是否支持 http3 + * * @param host host - * @param ip ip + * @param ip ip + * @return 是否支持 http3 */ public boolean isServerSupportHttp3(String host, String ip) { if (host == null || host.length() == 0 || ip == null || ip.length() == 0) { diff --git a/library/src/main/java/com/qiniu/android/http/serverRegion/UploadDomainRegion.java b/library/src/main/java/com/qiniu/android/http/serverRegion/UploadDomainRegion.java index 8b31a7dd1..177a0fed9 100644 --- a/library/src/main/java/com/qiniu/android/http/serverRegion/UploadDomainRegion.java +++ b/library/src/main/java/com/qiniu/android/http/serverRegion/UploadDomainRegion.java @@ -17,7 +17,11 @@ import java.util.HashMap; import java.util.List; - +/** + * region domain 管理对象 + * + * @hidden + */ public class UploadDomainRegion implements IUploadRegion { private final static int Http3FrozenTime = 3600 * 24; @@ -39,6 +43,18 @@ public class UploadDomainRegion implements IUploadRegion { private HashMap oldDomainHashMap; private ZoneInfo zoneInfo; + /** + * 构造函数 + */ + public UploadDomainRegion() { + } + + /** + * 是否和另一个 region 相同 + * + * @param region 另一个 region + * @return 是否相同 + */ @Override public boolean isEqual(IUploadRegion region) { if (region == null) { @@ -68,16 +84,31 @@ public boolean isEqual(IUploadRegion region) { } } + /** + * 是否有效 + * + * @return 是否有效 + */ @Override public boolean isValid() { return !isAllFrozen && (domainHostList.size() > 0 || oldDomainHostList.size() > 0); } + /** + * 获取 zone info + * + * @return zone info + */ @Override public ZoneInfo getZoneInfo() { return zoneInfo; } + /** + * 设置 zone info + * + * @param zoneInfo ZoneInfo + */ @Override public void setupRegionData(ZoneInfo zoneInfo) { if (zoneInfo == null) { @@ -118,6 +149,14 @@ private HashMap createDomainDictionary(List return domainHashMap; } + /** + * 获取下一个可重试的 Server + * + * @param requestState 请求状态 + * @param responseInfo 请求响应信息 + * @param freezeServer 冻结的 Server 信息 + * @return 下一个可重试的 Server + */ @Override public IUploadServer getNextServer(UploadRequestState requestState, ResponseInfo responseInfo, IUploadServer freezeServer) { if (isAllFrozen || requestState == null) { @@ -241,6 +280,11 @@ public boolean condition(String host, UploadServer serverP, UploadServer filterS return server; } + /** + * 更新 host 的 ip 列表 + * + * @param host host + */ @Override public void updateIpListFormHost(String host) { if (host == null) { diff --git a/library/src/main/java/com/qiniu/android/http/serverRegion/UploadServer.java b/library/src/main/java/com/qiniu/android/http/serverRegion/UploadServer.java index dabb9cd89..82199433d 100644 --- a/library/src/main/java/com/qiniu/android/http/serverRegion/UploadServer.java +++ b/library/src/main/java/com/qiniu/android/http/serverRegion/UploadServer.java @@ -2,6 +2,11 @@ import com.qiniu.android.http.request.IUploadServer; +/** + * 上传服务 + * + * @hidden + */ public class UploadServer extends IUploadServer { private final String serverId; @@ -11,6 +16,15 @@ public class UploadServer extends IUploadServer { private final Long ipPrefetchedTime; private String httpVersion; + /** + * 构造函数 + * + * @param serverId server id + * @param host host + * @param ip ip + * @param source dns 解析源 + * @param ipPrefetchedTime dns 解析时间 + */ public UploadServer(String serverId, String host, String ip, @@ -23,35 +37,70 @@ public UploadServer(String serverId, this.ipPrefetchedTime = ipPrefetchedTime; } + /** + * 获取 server id + * + * @return server id + */ @Override public String getServerId() { return this.serverId; } + /** + * 获取 HTTP version + * + * @return HTTP version + */ @Override public String getHttpVersion() { return httpVersion; } + /** + * 配置 HTTP version + * + * @param httpVersion HTTP version + */ public void setHttpVersion(String httpVersion) { this.httpVersion = httpVersion; } + /** + * 获取 IP + * + * @return IP + */ @Override public String getIp() { return ip; } + /** + * 获取 dns 解析源 + * + * @return dns 解析源 + */ @Override public String getSource() { return source; } + /** + * 获取 dns 解析时间 + * + * @return dns 解析时间 + */ @Override public Long getIpPrefetchedTime() { return ipPrefetchedTime; } + /** + * 获取服务域名 + * + * @return 服务域名 + */ @Override public String getHost() { return host; diff --git a/library/src/main/java/com/qiniu/android/http/serverRegion/UploadServerFreezeManager.java b/library/src/main/java/com/qiniu/android/http/serverRegion/UploadServerFreezeManager.java index c21bdb1f2..23b7edfd6 100644 --- a/library/src/main/java/com/qiniu/android/http/serverRegion/UploadServerFreezeManager.java +++ b/library/src/main/java/com/qiniu/android/http/serverRegion/UploadServerFreezeManager.java @@ -7,19 +7,35 @@ /** * Created by yangsen on 2020/6/3 + * + * @hidden */ public class UploadServerFreezeManager { private ConcurrentHashMap frozenInfo = new ConcurrentHashMap<>(); private final static UploadServerFreezeManager manager = new UploadServerFreezeManager(); + /** + * 构造函数 + */ public UploadServerFreezeManager() { } + /** + * 获取单例 + * + * @return 单例 + */ public static UploadServerFreezeManager getInstance() { return manager; } + /** + * 查看 type 是否冻结 + * + * @param type type + * @return 是否冻结 + */ public boolean isTypeFrozen(String type) { if (type == null || type.length() == 0) { return true; @@ -32,6 +48,12 @@ public boolean isTypeFrozen(String type) { return isFrozen; } + /** + * 冻结 type + * + * @param type type + * @param frozenTime 冻结时间 + */ public void freezeType(String type, int frozenTime) { if (type == null || type.length() == 0) { return; @@ -44,6 +66,11 @@ public void freezeType(String type, int frozenTime) { item.freeze(frozenTime); } + /** + * 解冻 type + * + * @param type type + */ public void unfreezeType(String type) { if (type == null || type.length() == 0) { return; diff --git a/library/src/main/java/com/qiniu/android/http/serverRegion/UploadServerFreezeUtil.java b/library/src/main/java/com/qiniu/android/http/serverRegion/UploadServerFreezeUtil.java index 96cb93103..733cab938 100644 --- a/library/src/main/java/com/qiniu/android/http/serverRegion/UploadServerFreezeUtil.java +++ b/library/src/main/java/com/qiniu/android/http/serverRegion/UploadServerFreezeUtil.java @@ -2,17 +2,44 @@ import com.qiniu.android.utils.Utils; +/** + * UploadServerFreezeUtil + * + * @hidden + */ public class UploadServerFreezeUtil { private final static UploadServerFreezeManager globalHttp3Freezer = new UploadServerFreezeManager(); + + private UploadServerFreezeUtil() { + } + + /** + * 获取 HTTP/3 冻结管理单例 + * + * @return 单例 + */ public static UploadServerFreezeManager globalHttp3Freezer() { return globalHttp3Freezer; } private final static UploadServerFreezeManager globalHttp2Freezer = new UploadServerFreezeManager(); + + /** + * 获取 HTTP/2 冻结管理单例 + * + * @return 单例 + */ public static UploadServerFreezeManager globalHttp2Freezer() { return globalHttp2Freezer; } + /** + * 查看 type 是否被冻结管理者冻结 + * + * @param type type + * @param freezeManagerList 结管理者 + * @return 是否冻结 + */ public static boolean isTypeFrozenByFreezeManagers(String type, UploadServerFreezeManager[] freezeManagerList) { if (type == null || type.length() == 0) { return true; @@ -31,6 +58,13 @@ public static boolean isTypeFrozenByFreezeManagers(String type, UploadServerFree return isFrozen; } + /** + * 获取 type + * + * @param host host + * @param ip ip + * @return type + */ public static String getFrozenType(String host, String ip) { String ipType = Utils.getIpType(ip, host); return String.format("%s-%s", host, ipType); diff --git a/library/src/main/java/com/qiniu/android/storage/Configuration.java b/library/src/main/java/com/qiniu/android/storage/Configuration.java index cd4aa651b..5b12eb8c4 100644 --- a/library/src/main/java/com/qiniu/android/storage/Configuration.java +++ b/library/src/main/java/com/qiniu/android/storage/Configuration.java @@ -8,6 +8,9 @@ import java.io.File; +/** + * 上传配置信息 + */ public final class Configuration { /** @@ -179,6 +182,9 @@ public String gen(String key, String sourceId) { return keyGen; } + /** + * Configuration Builder + */ public static class Builder { private IRequestClient requestClient = null; private Zone zone = null; @@ -190,7 +196,7 @@ public static class Builder { private int chunkSize = 2 * 1024 * 1024; private int putThreshold = 4 * 1024 * 1024; private int connectTimeout = 10; - private int writeTimeout = 30; + private int writeTimeout = 30; private int responseTimeout = 10; private int retryMax = 1; private int retryInterval = 500; @@ -200,97 +206,218 @@ public static class Builder { private int resumeUploadVersion = RESUME_UPLOAD_VERSION_V1; private int concurrentTaskCount = 3; + /** + * 构造函数 + */ + public Builder() { + } + + /** + * Builder 构造方法 + * + * @param requestClient 请求的客户端 + * @return Builder + */ public Builder requestClient(IRequestClient requestClient) { this.requestClient = requestClient; return this; } + /** + * 配置请求的 Zone + * + * @param zone 请求的 Zone + * @return Builder + */ public Builder zone(Zone zone) { this.zone = zone; return this; } + /** + * 配置上传的 Recorder,Recorder 可以记录上传的进度,使上传支持断点续传 + * + * @param recorder 请求的 Recorder + * @return Builder + */ public Builder recorder(Recorder recorder) { this.recorder = recorder; return this; } + /** + * 配置上传的 Recorder,Recorder 可以记录上传的进度,使上传支持断点续传 + * + * @param recorder 请求的 Recorder + * @param keyGen 上传记录 key 的生成器 + * @return Builder + */ public Builder recorder(Recorder recorder, KeyGenerator keyGen) { this.recorder = recorder; this.keyGen = keyGen; return this; } + /** + * 配置请求的 ProxyConfiguration + * + * @param proxy 请求的代理配置 + * @return Builder + */ public Builder proxy(ProxyConfiguration proxy) { this.proxy = proxy; return this; } + /** + * 配置分片上传时的分片大小 + * + * @param size 分片大小,单位:B + * @return Builder + */ public Builder chunkSize(int size) { this.chunkSize = size; return this; } + /** + * 配置分片上传的阈值,大于此值会使用分片上传,小于等于此值会使用表单上传 + * + * @param size 阈值,单位:B + * @return Builder + */ public Builder putThreshold(int size) { this.putThreshold = size; return this; } + /** + * 配置请求建立连接的超时时间 + * + * @param timeout 超时时间,单位:秒 + * @return Builder + */ public Builder connectTimeout(int timeout) { this.connectTimeout = timeout; return this; } + /** + * 配置请求发送数据的超时时间 + * + * @param timeout 超时时间,单位:秒 + * @return Builder + */ public Builder writeTimeout(int timeout) { this.writeTimeout = timeout; return this; } + /** + * 配置请求接收数据的超时时间 + * + * @param timeout 超时时间,单位:秒 + * @return Builder + */ public Builder responseTimeout(int timeout) { this.responseTimeout = timeout; return this; } + /** + * 配置请求单个域名最大的重试次数,一个上传请求可能会有多个主备域名 + * + * @param times 请求单个域名最大的重试次数 + * @return Builder + */ public Builder retryMax(int times) { this.retryMax = times; return this; } + /** + * 配置请求重试时间间隔 + * + * @param retryInterval 请求重试时间间隔,单位:秒 + * @return Builder + */ public Builder retryInterval(int retryInterval) { this.retryInterval = retryInterval; return this; } + /** + * 配置是否允许使用备用域名,如果不允许则仅会使用一个域名进行上传 + * 注:如果配置为 false 可能会影响上传的成功率 + * + * @param isAllow 是否允许使用备用域名 + * @return Builder + */ public Builder allowBackupHost(boolean isAllow) { this.allowBackupHost = isAllow; return this; } + /** + * 配置请求 Url 的拦截器 + * + * @param converter 请求 Url 的拦截器 + * @return Builder + */ public Builder urlConverter(UrlConverter converter) { this.urlConverter = converter; return this; } + /** + * 配置上传是否允许使用并发分片方式 + * + * @param useConcurrentResumeUpload 上传是否允许使用并发分片方式 + * @return Builder + */ public Builder useConcurrentResumeUpload(boolean useConcurrentResumeUpload) { this.useConcurrentResumeUpload = useConcurrentResumeUpload; return this; } + /** + * 配置分片上传的版本 + * + * @param resumeUploadVersion 分片上传的版本 + * @return Builder + */ public Builder resumeUploadVersion(int resumeUploadVersion) { this.resumeUploadVersion = resumeUploadVersion; return this; } + /** + * 配置分片上传的并发度 + * + * @param concurrentTaskCount 分片上传的并发度 + * @return Builder + */ public Builder concurrentTaskCount(int concurrentTaskCount) { this.concurrentTaskCount = concurrentTaskCount; return this; } + /** + * 配置是否使用 HTTP 请求 + * + * @param useHttps 是否使用 HTTP 请求 + * @return Builder + */ public Builder useHttps(boolean useHttps) { this.useHttps = useHttps; return this; } + /** + * 生成 Configuration + * + * @return Configuration + */ public Configuration build() { return new Configuration(this); } diff --git a/library/src/main/java/com/qiniu/android/storage/FileRecorder.java b/library/src/main/java/com/qiniu/android/storage/FileRecorder.java index 0566e998b..1abb03c0c 100644 --- a/library/src/main/java/com/qiniu/android/storage/FileRecorder.java +++ b/library/src/main/java/com/qiniu/android/storage/FileRecorder.java @@ -18,8 +18,17 @@ */ public final class FileRecorder implements Recorder { + /** + * 记录路径 + */ public String directory; + /** + * 构造方法 + * + * @param directory 记录路径 + * @throws IOException 异常 + */ public FileRecorder(String directory) throws IOException { this.directory = directory; File f = new File(directory); @@ -129,6 +138,9 @@ public void del(String key) { f.delete(); } + /** + * 删除所有路径 + */ public void deleteAll() { try { File folder = new File(directory); @@ -157,6 +169,11 @@ private void deleteDirectoryLegacyIO(File file) { file.delete(); } + /** + * 获取文件名 + * + * @return 文件名 + */ @Override public String getFileName() { return null; diff --git a/library/src/main/java/com/qiniu/android/storage/GlobalConfiguration.java b/library/src/main/java/com/qiniu/android/storage/GlobalConfiguration.java index 8154e83b2..aa7d01c2a 100644 --- a/library/src/main/java/com/qiniu/android/storage/GlobalConfiguration.java +++ b/library/src/main/java/com/qiniu/android/storage/GlobalConfiguration.java @@ -10,6 +10,9 @@ import org.json.JSONException; import org.json.JSONObject; +/** + * 上传全局配置 + */ public class GlobalConfiguration { /** @@ -170,10 +173,20 @@ public class GlobalConfiguration { private GlobalConfiguration() { } + /** + * 获取全局配置单例 + * + * @return 单例 + */ public static GlobalConfiguration getInstance() { return configuration; } + /** + * 获取 UDP dns ipv4 server 列表 + * + * @return server 列表 + */ public String[] getUdpDnsIpv4Servers() { if (udpDnsIpv4Servers != null) { return udpDnsIpv4Servers; @@ -182,6 +195,11 @@ public String[] getUdpDnsIpv4Servers() { } } + /** + * 获取 UDP dns ipv6 server 列表 + * + * @return server 列表 + */ public String[] getUdpDnsIpv6Servers() { if (udpDnsIpv6Servers != null) { return udpDnsIpv6Servers; @@ -190,6 +208,11 @@ public String[] getUdpDnsIpv6Servers() { } } + /** + * 获取 Doh ipv4 server 列表 + * + * @return server 列表 + */ public String[] getDohIpv4Servers() { if (dohIpv4Servers != null) { return dohIpv4Servers; @@ -198,6 +221,11 @@ public String[] getDohIpv4Servers() { } } + /** + * 获取 Doh 方式进行 Dns 预解析使用的 IPv6 Server + * + * @return Server 列表 + */ public String[] getDohIpv6Servers() { if (dohIpv6Servers != null) { return dohIpv6Servers; @@ -206,6 +234,11 @@ public String[] getDohIpv6Servers() { } } + /** + * 获取网络状态检测使用的 Url + * + * @return Url 列表 + */ public String[] getConnectCheckUrls() { if (connectCheckURLStrings != null) { return connectCheckURLStrings; @@ -214,6 +247,12 @@ public String[] getConnectCheckUrls() { } } + /** + * 解析 Base64 数据为字符串数组 + * + * @param data base64 data + * @return 字符串数组 + */ public static String[] parseBase64Array(String data) { try { byte[] jsonBytes = UrlSafeBase64.decode(data); diff --git a/library/src/main/java/com/qiniu/android/storage/NetReadyHandler.java b/library/src/main/java/com/qiniu/android/storage/NetReadyHandler.java index cbb550e6c..86033c6f8 100644 --- a/library/src/main/java/com/qiniu/android/storage/NetReadyHandler.java +++ b/library/src/main/java/com/qiniu/android/storage/NetReadyHandler.java @@ -2,7 +2,13 @@ /** * Created by bailong on 16/9/7. + * + * @hidden */ public interface NetReadyHandler { + + /** + * 等待网络正常连接 + */ void waitReady(); } diff --git a/library/src/main/java/com/qiniu/android/storage/PartsUploadPerformerV1.java b/library/src/main/java/com/qiniu/android/storage/PartsUploadPerformerV1.java index 908655677..ffc9b9aa0 100644 --- a/library/src/main/java/com/qiniu/android/storage/PartsUploadPerformerV1.java +++ b/library/src/main/java/com/qiniu/android/storage/PartsUploadPerformerV1.java @@ -49,7 +49,7 @@ void uploadNextData(final PartsUploadPerformerDataCompleteHandler completeHandle UploadBlock block = null; UploadData chunk = null; - synchronized (this) { + synchronized (uploadSource) { try { block = info.nextUploadBlock(); chunk = info.nextUploadData(block); @@ -108,13 +108,17 @@ public void complete(ResponseInfo responseInfo, UploadRegionRequestMetrics reque } } if (responseInfo.isOK() && ctx != null && expiredAt != null) { - uploadBlock.ctx = ctx; - uploadBlock.expireAt = expiredAt; - uploadChunk.updateState(UploadData.State.Complete); + synchronized (uploadSource) { + uploadBlock.ctx = ctx; + uploadBlock.expireAt = expiredAt; + uploadChunk.updateState(UploadData.State.Complete); + } recordUploadInfo(); notifyProgress(false); } else { - uploadChunk.updateState(UploadData.State.WaitToUpload); + synchronized (uploadSource) { + uploadChunk.updateState(UploadData.State.WaitToUpload); + } } completeHandler.complete(false, responseInfo, requestMetrics, response); } diff --git a/library/src/main/java/com/qiniu/android/storage/PartsUploadPerformerV2.java b/library/src/main/java/com/qiniu/android/storage/PartsUploadPerformerV2.java index d968a4e2b..f5031ae69 100644 --- a/library/src/main/java/com/qiniu/android/storage/PartsUploadPerformerV2.java +++ b/library/src/main/java/com/qiniu/android/storage/PartsUploadPerformerV2.java @@ -79,7 +79,7 @@ void uploadNextData(final PartsUploadPerformerDataCompleteHandler completeHandle final UploadInfoV2 info = (UploadInfoV2) uploadInfo; UploadData data = null; - synchronized (this) { + synchronized (uploadSource) { try { data = info.nextUploadData(); if (data != null) { @@ -134,12 +134,16 @@ public void complete(ResponseInfo responseInfo, UploadRegionRequestMetrics reque } } if (responseInfo.isOK() && etag != null && md5 != null) { - uploadData.etag = etag; - uploadData.updateState(UploadData.State.Complete); + synchronized (uploadSource) { + uploadData.etag = etag; + uploadData.updateState(UploadData.State.Complete); + } recordUploadInfo(); notifyProgress(false); } else { - uploadData.updateState(UploadData.State.WaitToUpload); + synchronized (uploadSource) { + uploadData.updateState(UploadData.State.WaitToUpload); + } } completeHandler.complete(false, responseInfo, requestMetrics, response); } diff --git a/library/src/main/java/com/qiniu/android/storage/Recorder.java b/library/src/main/java/com/qiniu/android/storage/Recorder.java index 9bd218cb2..4620d3117 100644 --- a/library/src/main/java/com/qiniu/android/storage/Recorder.java +++ b/library/src/main/java/com/qiniu/android/storage/Recorder.java @@ -28,5 +28,10 @@ public interface Recorder { */ void del(String key); + /** + * 获取记录的文件名 + * + * @return 记录的文件名 + */ String getFileName(); } diff --git a/library/src/main/java/com/qiniu/android/storage/UpProgressBytesHandler.java b/library/src/main/java/com/qiniu/android/storage/UpProgressBytesHandler.java index 35b2ef445..9ad23e726 100644 --- a/library/src/main/java/com/qiniu/android/storage/UpProgressBytesHandler.java +++ b/library/src/main/java/com/qiniu/android/storage/UpProgressBytesHandler.java @@ -1,6 +1,10 @@ package com.qiniu.android.storage; +/** + * UpProgressBytesHandler + */ public interface UpProgressBytesHandler extends UpProgressHandler { + /** * 用户自定义进度处理类必须实现的方法 * 注: diff --git a/library/src/main/java/com/qiniu/android/storage/UpToken.java b/library/src/main/java/com/qiniu/android/storage/UpToken.java index 5e23de4e1..5ad38e3e3 100644 --- a/library/src/main/java/com/qiniu/android/storage/UpToken.java +++ b/library/src/main/java/com/qiniu/android/storage/UpToken.java @@ -11,8 +11,19 @@ */ public final class UpToken { + /** + * token + */ public final String token; + + /** + * accessKey + */ public final String accessKey; + + /** + * bucket + */ public final String bucket; private long deadline = -1; @@ -25,6 +36,12 @@ private UpToken(String returnUrl, String token, String accessKey, String bucket) this.bucket = bucket; } + /** + * 构造函数 + * + * @param token token + * @return UpToken + */ public static UpToken parse(String token) { if (token == null) { return null; @@ -70,28 +87,59 @@ public static UpToken parse(String token) { return upToken; } + /** + * 获取无效 Token + * + * @return UpToken + */ public static UpToken getInvalidToken() { UpToken token = new UpToken("", "", "", ""); token.deadline = -1; return token; } + /** + * 判断 Token 是否有效 + * + * @param token Token + * @return 是否有效 + */ public static boolean isInvalid(UpToken token) { return token == null || !token.isValid(); } + /** + * 判断当前 Token 是否有效 + * + * @return 是否有效 + */ public boolean isValid() { return accessKey != null && !accessKey.isEmpty() && bucket != null && !bucket.isEmpty(); } + /** + * 获取 Token 字符串 + * + * @return Token 字符串 + */ public String toString() { return token; } + /** + * 判断 Token 中是否有 return url + * + * @return Token 中是否有 return url + */ public boolean hasReturnUrl() { return !returnUrl.equals(""); } + /** + * Token 标识 + * + * @return Token 标识 + */ public String index() { String index = ""; if (accessKey != null) { @@ -103,14 +151,31 @@ public String index() { return index; } + /** + * 获取 Token 有效期 + * + * @return Token 有效期 + */ public long getDeadline() { return deadline; } + /** + * 在未来时间段中,Token 是否有效 + * + * @param duration 未来时间段 + * @return Token 是否有效 + */ public boolean isValidForDuration(long duration) { return isValidBeforeTimestamp((new Date().getTime() / 1000) + duration); } + /** + * 在时间之前,Token 是否有效 + * + * @param date 时间 + * @return 是否有效 + */ public boolean isValidBeforeDate(Date date) { if (date == null) { return false; diff --git a/library/src/main/java/com/qiniu/android/storage/UploadManager.java b/library/src/main/java/com/qiniu/android/storage/UploadManager.java index 4bfd91af9..45ec5aa65 100644 --- a/library/src/main/java/com/qiniu/android/storage/UploadManager.java +++ b/library/src/main/java/com/qiniu/android/storage/UploadManager.java @@ -26,29 +26,44 @@ import java.io.InputStream; import java.util.ArrayList; - +/** + * 上传类 + */ public class UploadManager { private final Configuration config; - + /** + * 构造函数 + * + * @param recorder 文件上传进度记录,可实现断点续传 + */ public UploadManager(Recorder recorder) { this(recorder, null); } + /** + * 构造函数 + * + * @param recorder 文件上传进度记录,可实现断点续传 + * @param keyGen 上传文件上传进度对应记录缓存的 key 生成器 + */ public UploadManager(Recorder recorder, KeyGenerator keyGen) { this(new Configuration.Builder().recorder(recorder, keyGen).build()); } /** - * default 1 Threads + * 构造函数 + * 默认为串行 */ public UploadManager() { this(new Configuration.Builder().build()); } /** - * @param config Configuration, default 1 Thread + * 构造函数 + * + * @param config Configuration, 默认为串行 */ public UploadManager(Configuration config) { this.config = config != null ? config : new Configuration.Builder().build(); @@ -174,7 +189,7 @@ public void put(final InputStream inputStream, } /** - * 同步上传文件。使用 form 表单方式上传,建议只在数据较小情况下使用此方式,如 file.size() < 1024 * 1024。 + * 同步上传文件。使用 form 表单方式上传,建议只在数据较小情况下使用此方式,如 file.size() 小于 1024 * 1024。 * 注:切勿在主线程调用 * * @param data 上传的数据 @@ -215,7 +230,7 @@ public void complete(String key, ResponseInfo info, JSONObject response) { } /** - * 同步上传文件。使用 form 表单方式上传,建议只在文件较小情况下使用此方式,如 file.size() < 1024 * 1024。 + * 同步上传文件。使用 form 表单方式上传,建议只在文件较小情况下使用此方式,如 file.size() 小于 1024 * 1024。 * 注:切勿在主线程调用 * * @param file 上传的文件绝对路径 @@ -229,7 +244,7 @@ public ResponseInfo syncPut(String file, String key, String token, UploadOptions } /** - * 同步上传文件。使用 form 表单方式上传,建议只在文件较小情况下使用此方式,如 file.size() < 1024 * 1024。 + * 同步上传文件。使用 form 表单方式上传,建议只在文件较小情况下使用此方式,如 file.size() 小于 1024 * 1024。 * 注:切勿在主线程调用 * * @param file 上传的文件对象 @@ -243,7 +258,7 @@ public ResponseInfo syncPut(File file, String key, String token, UploadOptions o } /** - * 同步上传文件。使用 form 表单方式上传,建议只在文件较小情况下使用此方式,如 file.size() < 1024 * 1024。 + * 同步上传文件。使用 form 表单方式上传,建议只在文件较小情况下使用此方式,如 file.size() 小于 1024 * 1024。 * 注:切勿在主线程调用 * * @param uri 上传的文件对象 Uri @@ -265,7 +280,7 @@ public ResponseInfo syncPut(Uri uri, } /** - * 同步上传文件。使用 form 表单方式上传,建议只在文件较小情况下使用此方式,如 file.size() < 1024 * 1024。 + * 同步上传文件。使用 form 表单方式上传,建议只在文件较小情况下使用此方式,如 file.size() 小于 1024 * 1024。 * 注:切勿在主线程调用 * * @param inputStream 上传的资源流 @@ -522,7 +537,7 @@ private void reportQuality(String key, } else if (source instanceof byte[]) { fileSize = ((byte[]) source).length; } - item.setReport((Long)fileSize, ReportItem.QualityKeyFileSize); + item.setReport((Long) fileSize, ReportItem.QualityKeyFileSize); // 统计当前文件上传速度,也即用户感知速度: 总文件大小 / 总耗时 if (source != null && responseInfo.isOK() && taskMetrics.totalElapsedTime() > 0) { diff --git a/library/src/main/java/com/qiniu/android/storage/UploadOptions.java b/library/src/main/java/com/qiniu/android/storage/UploadOptions.java index 47e6b8c79..0093699d5 100644 --- a/library/src/main/java/com/qiniu/android/storage/UploadOptions.java +++ b/library/src/main/java/com/qiniu/android/storage/UploadOptions.java @@ -48,6 +48,15 @@ public final class UploadOptions { */ public final NetReadyHandler netReadyHandler; + /** + * 构造函数 + * + * @param params 参数 + * @param mimeType mime type + * @param checkCrc 是否验证文件上传前后的一致性 + * @param progressHandler 进度回调 + * @param cancellationSignal 取消函数 + */ public UploadOptions(Map params, String mimeType, boolean checkCrc, @@ -56,15 +65,36 @@ public UploadOptions(Map params, this(params, mimeType, checkCrc, progressHandler, cancellationSignal, null); } + /** + * 构造函数 + * + * @param params 参数 + * @param mimeType mime type + * @param checkCrc 是否验证文件上传前后的一致性 + * @param progressHandler 进度回调 + * @param cancellationSignal 取消函数 + * @param netReadyHandler 网络准备回调 + */ public UploadOptions(final Map params, String mimeType, boolean checkCrc, UpProgressHandler progressHandler, UpCancellationSignal cancellationSignal, NetReadyHandler netReadyHandler) { - this(params, null, mimeType, checkCrc, progressHandler, cancellationSignal, netReadyHandler); + this(params, null, mimeType, checkCrc, progressHandler, cancellationSignal, netReadyHandler); } + /** + * 构造函数 + * + * @param params 参数 + * @param metaDataParam meta data + * @param mimeType mime type + * @param checkCrc 是否验证文件上传前后的一致性 + * @param progressHandler 进度回调 + * @param cancellationSignal 取消函数 + * @param netReadyHandler 网络准备回调 + */ public UploadOptions(final Map params, final Map metaDataParam, String mimeType, @@ -79,7 +109,8 @@ public UploadOptions(final Map params, if (netCheckTime != null) { netReadyCheckTime = Integer.parseInt(netCheckTime); } - } catch (Exception e) {} + } catch (Exception e) { + } this.params = filterParam(params); this.metaDataParam = filterMetaDataParam(metaDataParam); this.mimeType = mime(mimeType); @@ -157,7 +188,11 @@ private static Map filterMetaDataParam(Map param return ret; } - + /** + * 默认可选属性 + * + * @return UploadOptions + */ public static UploadOptions defaultOptions() { return new UploadOptions(null, null, false, null, null); } diff --git a/library/src/main/java/com/qiniu/android/storage/serverConfig/ServerConfig.java b/library/src/main/java/com/qiniu/android/storage/serverConfig/ServerConfig.java index eb5ab073d..55699de68 100644 --- a/library/src/main/java/com/qiniu/android/storage/serverConfig/ServerConfig.java +++ b/library/src/main/java/com/qiniu/android/storage/serverConfig/ServerConfig.java @@ -10,6 +10,11 @@ import java.util.ArrayList; import java.util.List; +/** + * server config + * + * @hidden + */ public class ServerConfig implements Cache.Object { private long timestamp; @@ -19,6 +24,11 @@ public class ServerConfig implements Cache.Object { private DnsConfig dnsConfig; private ConnectCheckConfig connectCheckConfig; + /** + * 构造函数 + * + * @param info json info + */ public ServerConfig(JSONObject info) { if (info == null) { return; @@ -48,31 +58,66 @@ public ServerConfig(JSONObject info) { } } + /** + * 获取 json 数据 + * + * @return JSONObject + */ @Override public JSONObject toJson() { return info; } + /** + * 获取 json 数据 + * + * @return JSONObject + */ public JSONObject getInfo() { return toJson(); } + /** + * 获取区域配置 + * + * @return 区域配置 + */ public RegionConfig getRegionConfig() { return regionConfig; } + /** + * 获取 DNS 配置 + * + * @return DNS 配置 + */ public DnsConfig getDnsConfig() { return dnsConfig; } + /** + * 获取网络连接检测配置 + * + * @return 网络连接检测配置 + */ public ConnectCheckConfig getConnectCheckConfig() { return connectCheckConfig; } + /** + * 配置信息是否有效 + * + * @return 配置信息是否有效 + */ public boolean isValid() { return Utils.currentSecondTimestamp() < (this.timestamp + this.ttl); } + /** + * 区域配置 + * + * @hidden + */ public static class RegionConfig { private long clearId; private boolean clearCache; @@ -86,15 +131,30 @@ public static class RegionConfig { this.clearCache = info.optBoolean("clear_cache", false); } + /** + * 获取 clearId + * + * @return clearId + */ public long getClearId() { return clearId; } + /** + * 获取 clearCache + * + * @return clearCache + */ public boolean getClearCache() { return clearCache; } } + /** + * DNS 配置 + * + * @hidden + */ public static class DnsConfig { private Boolean enable; private long clearId; @@ -116,27 +176,57 @@ public static class DnsConfig { this.dohDnsConfig = new DohDnsConfig(info.optJSONObject("doh")); } + /** + * DNS 是否生效 + * + * @return DNS 是否生效 + */ public Boolean getEnable() { return enable; } + /** + * 获取 clearId + * + * @return clearId + */ public long getClearId() { return clearId; } + /** + * 获取 clearCache + * + * @return clearCache + */ public boolean getClearCache() { return clearCache; } + /** + * 获取 udp dns 配置信息 + * + * @return udp dns 配置信息 + */ public UdpDnsConfig getUdpDnsConfig() { return udpDnsConfig; } + /** + * 获取 doh 配置信息 + * + * @return doh 配置信息 + */ public DohDnsConfig getDohDnsConfig() { return dohDnsConfig; } } + /** + * dns server + * + * @hidden + */ public static class DnsServer { private boolean isOverride; private String[] servers; @@ -165,15 +255,30 @@ public static class DnsServer { this.servers = servers.toArray(new String[0]); } + /** + * 是否覆盖配置 + * + * @return 是否覆盖配置 + */ public boolean getIsOverride() { return isOverride; } + /** + * 获取 servers + * + * @return servers + */ public String[] getServers() { return servers; } } + /** + * udp dns 配置 + * + * @hidden + */ public static class UdpDnsConfig { private Boolean enable; private DnsServer ipv4Server; @@ -192,19 +297,39 @@ public static class UdpDnsConfig { this.ipv6Server = new DnsServer(info.optJSONObject("ipv6")); } + /** + * 配置是否生效 + * + * @return 配置是否生效 + */ public Boolean getEnable() { return enable; } + /** + * 获取 ipv4 server + * + * @return ipv4 server + */ public DnsServer getIpv4Server() { return ipv4Server; } + /** + * 获取 ipv6 server + * + * @return ipv6 server + */ public DnsServer getIpv6Server() { return ipv6Server; } } + /** + * doh 配置 + * + * @hidden + */ public static class DohDnsConfig { private Boolean enable; private DnsServer ipv4Server; @@ -223,19 +348,39 @@ public static class DohDnsConfig { this.ipv6Server = new DnsServer(info.optJSONObject("ipv6")); } + /** + * 配置是否生效 + * + * @return 配置是否生效 + */ public Boolean getEnable() { return enable; } + /** + * 获取 ipv4 server + * + * @return ipv4 server + */ public DnsServer getIpv4Server() { return ipv4Server; } + /** + * 获取 ipv6 server + * + * @return ipv6 server + */ public DnsServer getIpv6Server() { return ipv6Server; } } + /** + * connect check config + * + * @hidden + */ public static class ConnectCheckConfig { private Boolean isOverride; private Boolean enable; @@ -273,18 +418,38 @@ public static class ConnectCheckConfig { } } + /** + * 是否覆盖配置 + * + * @return 是否覆盖配置 + */ public Boolean getOverride() { return isOverride; } + /** + * 配置是否生效 + * + * @return 配置是否生效 + */ public Boolean getEnable() { return enable; } + /** + * 获取超时时间 + * + * @return 超时时间 + */ public Integer getTimeoutMs() { return timeoutMs; } + /** + * 获取网络检测的 url 列表 + * + * @return 网络检测的 url 列表 + */ public String[] getUrls() { return urls; } diff --git a/library/src/main/java/com/qiniu/android/storage/serverConfig/ServerConfigMonitor.java b/library/src/main/java/com/qiniu/android/storage/serverConfig/ServerConfigMonitor.java index 68ded4152..fe27da9fc 100644 --- a/library/src/main/java/com/qiniu/android/storage/serverConfig/ServerConfigMonitor.java +++ b/library/src/main/java/com/qiniu/android/storage/serverConfig/ServerConfigMonitor.java @@ -8,6 +8,9 @@ import java.util.List; import java.util.Random; +/** + * 服务控制监控 + */ public class ServerConfigMonitor { private static final String TransactionKey = "ServerConfig"; @@ -15,23 +18,46 @@ public class ServerConfigMonitor { private final ServerConfigCache cache = new ServerConfigCache(); private static final ServerConfigMonitor configMonitor = new ServerConfigMonitor(); + private ServerConfigMonitor() { + } + + /** + * 是否开启 + * + * @param enable 是否开启 + */ public static void setEnable(boolean enable) { configMonitor.enable = enable; } + /** + * 配置上传 Token,SDK 会在上传文件时自动配置 + * + * @param token 上传 Token + */ public static void setToken(String token) { ServerConfigSynchronizer.setToken(token); } + /** + * 配置 server hosts + * + * @param hosts hosts + */ public static void setServerHosts(String[] hosts) { ServerConfigSynchronizer.setHosts(hosts); } + /** + * 清理配置缓存 + */ public static void removeConfigCache() { configMonitor.cache.removeConfigCache(); } - // 开始监控 + /** + * 开始监控 + */ public synchronized static void startMonitor() { if (!configMonitor.enable) { return; @@ -54,7 +80,9 @@ public void run() { transactionManager.addTransaction(transaction); } - // 停止监控 + /** + * 停止监控 + */ public synchronized static void endMonitor() { TransactionManager transactionManager = TransactionManager.getInstance(); List transactions = transactionManager.transactionsForName(TransactionKey); diff --git a/library/src/main/java/com/qiniu/android/storage/serverConfig/ServerUserConfig.java b/library/src/main/java/com/qiniu/android/storage/serverConfig/ServerUserConfig.java index 27c113e8a..ef023e658 100644 --- a/library/src/main/java/com/qiniu/android/storage/serverConfig/ServerUserConfig.java +++ b/library/src/main/java/com/qiniu/android/storage/serverConfig/ServerUserConfig.java @@ -6,6 +6,11 @@ import org.json.JSONException; import org.json.JSONObject; +/** + * server user config + * + * @hidden + */ public class ServerUserConfig implements Cache.Object { private long timestamp; @@ -15,6 +20,11 @@ public class ServerUserConfig implements Cache.Object { private JSONObject info; + /** + * 构造函数 + * + * @param info json 数据 + */ public ServerUserConfig(JSONObject info) { if (info == null) { return; @@ -46,23 +56,48 @@ public ServerUserConfig(JSONObject info) { } } + /** + * 获取 json 数据 + * + * @return json 数据 + */ @Override public JSONObject toJson() { return info; } + /** + * HTTP/3 是否开启 + * + * @return HTTP/3 是否开启 + */ public Boolean getHttp3Enable() { return http3Enable; } + /** + * 网络检测是否开启 + * + * @return 网络检测是否开启 + */ public Boolean getNetworkCheckEnable() { return networkCheckEnable; } + /** + * 获取 json 信息 + * + * @return json 信息 + */ public JSONObject getInfo() { return toJson(); } + /** + * 配置是否有效 + * + * @return 配置是否有效 + */ public boolean isValid() { return Utils.currentSecondTimestamp() < (this.timestamp + this.ttl); } diff --git a/library/src/main/java/com/qiniu/android/transaction/TransactionManager.java b/library/src/main/java/com/qiniu/android/transaction/TransactionManager.java index 10a721e9d..74ccf85f3 100644 --- a/library/src/main/java/com/qiniu/android/transaction/TransactionManager.java +++ b/library/src/main/java/com/qiniu/android/transaction/TransactionManager.java @@ -9,14 +9,24 @@ /** * Created by yangsen on 2020/6/9 + * + * @hidden */ public class TransactionManager { - /// 事务链表 + /** + * 事务链表 + */ protected final ConcurrentLinkedQueue transactionList = new ConcurrentLinkedQueue<>(); - /// 事务定时器 + + /** + * 事务定时器 + */ private Timer timer; + /** + * action 数量 + */ protected long actionCount = 0; private static final TransactionManager transactionManager = new TransactionManager(); @@ -24,11 +34,21 @@ public class TransactionManager { private TransactionManager() { } + /** + * 获取事务管理器单例 + * + * @return 事务管理器单例 + */ public static TransactionManager getInstance() { return transactionManager; } - /// 根据name查找事务 + /** + * 根据 name 查找事务 + * + * @param name name + * @return 事务列表 + */ public ArrayList transactionsForName(String name) { ArrayList arrayList = new ArrayList<>(); for (Transaction transaction : transactionList) { @@ -39,7 +59,12 @@ public ArrayList transactionsForName(String name) { return arrayList; } - /// 是否存在某个名称的事务 + /** + * 是否存在某个名称的事务 + * + * @param name 事务名称 + * @return 是否存在 + */ public boolean existTransactionsForName(String name) { boolean isExist = false; for (Transaction transaction : transactionList) { @@ -51,7 +76,11 @@ public boolean existTransactionsForName(String name) { return isExist; } - /// 添加一个事务 + /** + * 添加一个事务 + * + * @param transaction 事务 + */ public void addTransaction(Transaction transaction) { if (transaction == null) { return; @@ -60,7 +89,11 @@ public void addTransaction(Transaction transaction) { createTimer(); } - /// 移除一个事务 + /** + * 移除一个事务 + * + * @param transaction 事务 + */ public void removeTransaction(Transaction transaction) { if (transaction == null) { return; @@ -68,7 +101,11 @@ public void removeTransaction(Transaction transaction) { transactionList.remove(transaction); } - /// 在下一次循环执行事务, 该事务如果未被添加到事务列表,会自动添加 + /** + * 在下一次循环执行事务, 该事务如果未被添加到事务列表,会自动添加 + * + * @param transaction 事务 + */ public synchronized void performTransaction(Transaction transaction) { if (transaction == null) { return; @@ -80,7 +117,9 @@ public synchronized void performTransaction(Transaction transaction) { transaction.nextExecutionTime = Utils.currentSecondTimestamp(); } - /// 销毁资源 清空事务链表 销毁常驻线程 + /** + * 销毁资源 清空事务链表 销毁常驻线程 + */ public synchronized void destroyResource() { invalidateTimer(); transactionList.clear(); @@ -124,16 +163,27 @@ private void timerAction() { handleAllTransaction(); } - + /** + * Transaction + * + * @hidden + */ public static class Transaction { - // 事务名称 + /** + * 事务名称 + */ public final String name; - // 事务延迟执行时间 单位:秒 + + /** + * 事务延迟执行时间 单位:秒 + */ public final int after; - // 事务内容 - public final Runnable actionHandler; + /** + * 事务内容 + */ + public final Runnable actionHandler; // 普通类型事务,事务体仅会执行一次 private static final int TransactionTypeNormal = 0; @@ -145,14 +195,25 @@ public static class Transaction { private final int interval; // 创建时间 private long createTime; - // 下一次需要执行的时间 + + /** + * 下一次需要执行的时间 + */ protected long nextExecutionTime; - // 已执行次数 + /** + * 已执行次数 + */ protected long executedCount = 0; private boolean isExecuting = false; - + /** + * 构造函数 + * + * @param name 名称 + * @param after 执行延迟时间 + * @param actionHandler 执行体 + */ public Transaction(String name, int after, Runnable actionHandler) { @@ -166,7 +227,14 @@ public Transaction(String name, this.nextExecutionTime = this.createTime + after; } - + /** + * 构造函数 + * + * @param name 名称 + * @param after 执行延迟时间 + * @param interval 周期执行时间间隔 + * @param actionHandler 执行体 + */ public Transaction(String name, int after, int interval, @@ -181,6 +249,11 @@ public Transaction(String name, this.nextExecutionTime = this.createTime + after; } + /** + * 是否需要执行 + * + * @return 是否需要执行 + */ protected boolean shouldAction() { long currentTime = Utils.currentSecondTimestamp(); if (this.type == TransactionTypeNormal) { @@ -192,6 +265,11 @@ protected boolean shouldAction() { } } + /** + * 是否已经结束 + * + * @return 是否已经结束 + */ protected boolean maybeCompleted() { if (this.type == TransactionTypeNormal) { return executedCount > 0; @@ -220,6 +298,11 @@ private synchronized void handleAction() { } } + /** + * 是否正在执行 + * + * @return 是否正在执行 + */ public boolean isExecuting() { return isExecuting; } diff --git a/library/src/main/java/com/qiniu/android/utils/AndroidNetwork.java b/library/src/main/java/com/qiniu/android/utils/AndroidNetwork.java index 6d8390794..a46ed3df5 100644 --- a/library/src/main/java/com/qiniu/android/utils/AndroidNetwork.java +++ b/library/src/main/java/com/qiniu/android/utils/AndroidNetwork.java @@ -1,6 +1,7 @@ package com.qiniu.android.utils; import android.Manifest; +import android.annotation.SuppressLint; import android.content.Context; import android.content.pm.PackageManager; import android.net.ConnectivityManager; @@ -26,8 +27,19 @@ /** * Created by bailong on 16/9/7. + * + * @hidden */ public final class AndroidNetwork { + + private AndroidNetwork() { + } + + /** + * 网络是否正常连接 + * + * @return 网络是否连接 + */ public static boolean isNetWorkReady() { Context c = ContextGetter.applicationContext(); if (c == null) { @@ -48,7 +60,7 @@ public static boolean isNetWorkReady() { * 使用DNS解析某地址时,可能会同时返回IPv4和IPv6的地址。 * 如果同时拥有IPv4和IPv6的地址,是会默认优先上报IPv6的地址 * - * @return + * @return IP */ public static String getHostIP() { String hostIp = null; @@ -77,6 +89,18 @@ public static String getHostIP() { return hostIp; } + /** + * 网络类型 + * {@link Constants#NETWORK_CLASS_UNKNOWN} + * {@link Constants#NETWORK_WIFI} + * {@link Constants#NETWORK_CLASS_2_G} + * {@link Constants#NETWORK_CLASS_3_G} + * {@link Constants#NETWORK_CLASS_4_G} + * ... + * + * @param context context + * @return 网络类型 + */ public static String networkType(Context context) { try { return networkTypeWithException(context); @@ -87,7 +111,7 @@ public static String networkType(Context context) { } private static String networkTypeWithException(Context context) throws Exception { - if (context == null){ + if (context == null) { return Constants.NETWORK_CLASS_UNKNOWN; } @@ -116,7 +140,7 @@ private static String getNetWorkClass(Context context) { } TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); - if (telephonyManager == null){ + if (telephonyManager == null) { return Constants.NETWORK_CLASS_UNKNOWN; } @@ -142,6 +166,10 @@ private static String getNetWorkClass(Context context) { case TelephonyManager.NETWORK_TYPE_LTE: return Constants.NETWORK_CLASS_4_G; + + case TelephonyManager.NETWORK_TYPE_NR: + return Constants.NETWORK_CLASS_5_G; + default: return Constants.NETWORK_CLASS_UNKNOWN; } diff --git a/library/src/main/java/com/qiniu/android/utils/AsyncRun.java b/library/src/main/java/com/qiniu/android/utils/AsyncRun.java index a55e868f1..600e0647c 100644 --- a/library/src/main/java/com/qiniu/android/utils/AsyncRun.java +++ b/library/src/main/java/com/qiniu/android/utils/AsyncRun.java @@ -14,6 +14,8 @@ /** * Created by bailong on 14/10/22. + * + * @hidden */ public final class AsyncRun { @@ -25,8 +27,16 @@ public final class AsyncRun { 1000L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue()); + private AsyncRun() { + } + + /** + * 主线程执行任务 + * + * @param r 执行体 + */ public static void runInMain(Runnable r) { - if (Looper.getMainLooper() == Looper.myLooper()){ + if (Looper.getMainLooper() == Looper.myLooper()) { r.run(); } else { mainThreadHandler.post(r); @@ -34,10 +44,12 @@ public static void runInMain(Runnable r) { } /** - * delay: delay in milliseconds before task is to be executed. + * 延迟执行任务 + * + * @param delay 延迟执行时间,单位:ms + * @param r 执行体 */ - public static void runInMain(int delay, - final Runnable r){ + public static void runInMain(int delay, final Runnable r) { delayTimerTask(delay, new TimerTask() { @Override @@ -48,15 +60,22 @@ public void run() { }); } + /** + * 后台执行任务 + * + * @param r 执行体 + */ public static void runInBack(Runnable r) { executorService.submit(r); } /** - * delay: delay in milliseconds before task is to be executed. + * 延迟执行任务 + * + * @param delay 延迟执行时间,单位:ms + * @param r 执行体 */ - public static void runInBack(int delay, - final Runnable r) { + public static void runInBack(int delay, final Runnable r) { delayTimerTask(delay, new TimerTask() { @Override @@ -67,7 +86,7 @@ public void run() { }); } - private static void delayTimerTask(int delay, TimerTask timerTask){ + private static void delayTimerTask(int delay, TimerTask timerTask) { Timer timer = new Timer(); timer.schedule(timerTask, delay); } diff --git a/library/src/main/java/com/qiniu/android/utils/BytesUtils.java b/library/src/main/java/com/qiniu/android/utils/BytesUtils.java index 20fbc3496..1a1683a27 100644 --- a/library/src/main/java/com/qiniu/android/utils/BytesUtils.java +++ b/library/src/main/java/com/qiniu/android/utils/BytesUtils.java @@ -2,7 +2,25 @@ import java.io.IOException; +/** + * Bytes 工具 + * + * @hidden + */ public class BytesUtils { + + private BytesUtils() { + } + + /** + * 获取 byte 数组的子数组 + * + * @param source 源 byte 数组 + * @param from 子数组开始位置 + * @param length 子数组长度 + * @return 子数组 + * @throws IOException 异常 + */ public static byte[] subBytes(byte[] source, int from, int length) throws IOException { if (length + from > source.length) { throw new IOException("copy bytes out of range"); diff --git a/library/src/main/java/com/qiniu/android/utils/Cache.java b/library/src/main/java/com/qiniu/android/utils/Cache.java index d8ece7dd3..6d680f936 100644 --- a/library/src/main/java/com/qiniu/android/utils/Cache.java +++ b/library/src/main/java/com/qiniu/android/utils/Cache.java @@ -10,6 +10,11 @@ import java.util.Map; import java.util.concurrent.ConcurrentHashMap; +/** + * 缓存对象 + * + * @hidden + */ public class Cache { // 当 cache 修改数量到达这个值时,就会 flush,默认是 1 @@ -63,7 +68,7 @@ private void load() { try { JSONObject jsonObject = cacheJson.getJSONObject(key); Constructor constructor = (Constructor) objectClass.getConstructor(JSONObject.class); - Object object = (Object)constructor.newInstance(jsonObject); + Object object = (Object) constructor.newInstance(jsonObject); this.memCache.put(key, object); } catch (Exception e) { e.printStackTrace(); @@ -75,14 +80,38 @@ private void load() { } } + /** + * 缓存的 Object 协议定义 + * + * @hidden + */ public interface Object { + + /** + * 转 json + * + * @return JSONObject + */ JSONObject toJson(); } + /** + * 根据缓存的 key 获取缓存对象 + * + * @param cacheKey 缓存的 key + * @return 缓存对象 + */ public Object cacheForKey(String cacheKey) { return this.memCache.get(cacheKey); } + /** + * 缓存对象方法 + * + * @param cacheKey 缓存的 key + * @param object 缓存对象 + * @param atomically 是否同步缓存 + */ public void cache(String cacheKey, Object object, boolean atomically) { if (StringUtils.isNullOrEmpty(cacheKey) || object == null) { return; @@ -98,10 +127,20 @@ public void cache(String cacheKey, Object object, boolean atomically) { } } + /** + * 获取所有的内存缓存 + * + * @return 所有的内存缓存 + */ public Map allMemoryCache() { return new HashMap<>(this.memCache); } + /** + * 内存缓存写入硬盘 + * + * @param atomically 是否同步写入 + */ public void flush(boolean atomically) { synchronized (this) { if (this.isFlushing) { @@ -159,15 +198,25 @@ private void flushCache(Map flushCache) { } } + /** + * 清理内存缓存 + */ public void clearMemoryCache() { this.memCache.clear(); } + /** + * 清理磁盘缓存 + */ public void clearDiskCache() { this.diskCache.deleteAll(); } - + /** + * Cache Builder + * + * @hidden + */ public static class Builder { // 当 cache 修改数量到达这个值时,就会 flush,默认是 1 private int flushCount = 1; @@ -178,20 +227,42 @@ public static class Builder { // 存储对象的类型 private final Class objectClass; + /** + * Builder 构造方法 + * + * @param objectClass 缓存对象的 class 类型 + */ public Builder(Class objectClass) { this.objectClass = objectClass; } + /** + * 设置当内存改变多少次后进行内存刷入磁盘操作 + * + * @param flushCount 次数 + * @return Builder + */ public Builder setFlushCount(int flushCount) { this.flushCount = flushCount; return this; } + /** + * 设置缓存版本信息 + * + * @param version 版本信息 + * @return Builder + */ public Builder setVersion(String version) { this.version = version; return this; } + /** + * 构造 Cache + * + * @return Cache + */ public Cache builder() { return new Cache(this.objectClass, this.flushCount, this.version); } diff --git a/library/src/main/java/com/qiniu/android/utils/Constants.java b/library/src/main/java/com/qiniu/android/utils/Constants.java index 01be0179b..40468b2bc 100644 --- a/library/src/main/java/com/qiniu/android/utils/Constants.java +++ b/library/src/main/java/com/qiniu/android/utils/Constants.java @@ -1,6 +1,10 @@ package com.qiniu.android.utils; +/** + * 常量定义 + */ public class Constants { + /** * Unknown network class */ @@ -26,5 +30,11 @@ public class Constants { */ public static final String NETWORK_CLASS_4_G = "4g"; + /** + * "5G" networks + */ + public static final String NETWORK_CLASS_5_G = "5g"; + private Constants() { + } } diff --git a/library/src/main/java/com/qiniu/android/utils/ContextGetter.java b/library/src/main/java/com/qiniu/android/utils/ContextGetter.java index 11d065d8e..0c9e22799 100644 --- a/library/src/main/java/com/qiniu/android/utils/ContextGetter.java +++ b/library/src/main/java/com/qiniu/android/utils/ContextGetter.java @@ -7,10 +7,20 @@ /** * Created by bailong on 16/9/7. + * + * @hidden */ public final class ContextGetter { private static Context context = applicationContext(); + private ContextGetter() { + } + + /** + * application Context + * + * @return Context + */ public static Context applicationContext() { if (context != null) { return context; diff --git a/library/src/main/java/com/qiniu/android/utils/Crc32.java b/library/src/main/java/com/qiniu/android/utils/Crc32.java index 52fbd84ba..32f12776c 100644 --- a/library/src/main/java/com/qiniu/android/utils/Crc32.java +++ b/library/src/main/java/com/qiniu/android/utils/Crc32.java @@ -7,9 +7,14 @@ /** * 计算文件或二进制数据的crc32校验码 + * + * @hidden */ public final class Crc32 { + private Crc32() { + } + /** * 计算二进制字节校验码 * diff --git a/library/src/main/java/com/qiniu/android/utils/Etag.java b/library/src/main/java/com/qiniu/android/utils/Etag.java index 38ceef761..5ae8eb0ed 100644 --- a/library/src/main/java/com/qiniu/android/utils/Etag.java +++ b/library/src/main/java/com/qiniu/android/utils/Etag.java @@ -13,9 +13,14 @@ /** * 计算文件内容或者二进制数据的etag, etag算法是七牛用来标志数据唯一性的算法。 * 文档:etag算法 + * + * @hidden */ public final class Etag { + private Etag() { + } + /** * 计算二进制数据的etag * diff --git a/library/src/main/java/com/qiniu/android/utils/FastDatePrinter.java b/library/src/main/java/com/qiniu/android/utils/FastDatePrinter.java index 1ba6c51e9..c6efd9815 100644 --- a/library/src/main/java/com/qiniu/android/utils/FastDatePrinter.java +++ b/library/src/main/java/com/qiniu/android/utils/FastDatePrinter.java @@ -32,41 +32,35 @@ /** *

FastDatePrinter is a fast and thread-safe version of * {@link java.text.SimpleDateFormat}.

- *

*

Since FastDatePrinter is thread safe, you can use a static member instance:

* * private static final DatePrinter DATE_PRINTER = FastDateFormat.getInstance("yyyy-MM-dd"); * - *

*

This class can be used as a direct replacement to * {@code SimpleDateFormat} in most formatting situations. * This class is especially useful in multi-threaded server environments. * {@code SimpleDateFormat} is not thread-safe in any JDK version, * nor will it be as Sun have closed the bug/RFE. *

- *

*

Only formatting is supported by this class, but all patterns are compatible with * SimpleDateFormat (except time zones and some year patterns - see below).

- *

*

Java 1.4 introduced a new pattern letter, {@code 'Z'}, to represent * time zones in RFC822 format (eg. {@code +0800} or {@code -1100}). * This pattern letter can be used here (on all JDK versions).

- *

*

In addition, the pattern {@code 'ZZ'} has been made to represent * ISO 8601 extended format time zones (eg. {@code +08:00} or {@code -11:00}). * This introduces a minor incompatibility with Java 1.4, but at a gain of * useful functionality.

- *

*

Starting with JDK7, ISO 8601 support was added using the pattern {@code 'X'}. * To maintain compatibility, {@code 'ZZ'} will continue to be supported, but using * one of the {@code 'X'} formats is recommended. - *

*

Javadoc cites for the year pattern: For formatting, if the number of * pattern letters is 2, the year is truncated to 2 digits; otherwise it is * interpreted as a number. Starting with Java 1.7 a pattern of 'Y' or * 'YYY' will be formatted as '2003', while it was '03' in former Java * versions. FastDatePrinter implements the behavior of Java 7.

* + * @hidden * @since 3.2 */ public final class FastDatePrinter { @@ -508,10 +502,12 @@ String format(final Object obj) { } } - /* (non-Javadoc) - * @see org.apache.commons.lang3.time.DatePrinter#format(java.util.Date) + /** + * format + * + * @param millis 时间戳 + * @return format 信息 */ - public String format(final long millis) { final Calendar c = newCalendar(); c.setTimeInMillis(millis); @@ -549,6 +545,12 @@ private Calendar newCalendar() { * @see org.apache.commons.lang3.time.DatePrinter#format(java.util.Date, java.lang.StringBuffer) */ + /** + * format + * + * @param date date + * @return String + */ public String format(final Date date) { final Calendar c = newCalendar(); c.setTime(date); @@ -559,6 +561,12 @@ public String format(final Date date) { * @see org.apache.commons.lang3.time.DatePrinter#format(java.util.Calendar, java.lang.StringBuffer) */ + /** + * format + * + * @param calendar calendar + * @return String + */ public String format(final Calendar calendar) { return format(calendar, new StringBuilder(mMaxLengthEstimate)).toString(); } @@ -567,6 +575,13 @@ public String format(final Calendar calendar) { * @see org.apache.commons.lang3.time.DatePrinter#format(long, java.lang.Appendable) */ + /** + * format + * + * @param millis millis + * @param buf buf + * @return StringBuffer + */ public StringBuffer format(final long millis, final StringBuffer buf) { final Calendar c = newCalendar(); c.setTimeInMillis(millis); @@ -577,6 +592,13 @@ public StringBuffer format(final long millis, final StringBuffer buf) { * @see org.apache.commons.lang3.time.DatePrinter#format(java.util.Date, java.lang.Appendable) */ + /** + * format + * + * @param date date + * @param buf buf + * @return StringBuffer + */ public StringBuffer format(final Date date, final StringBuffer buf) { final Calendar c = newCalendar(); c.setTime(date); @@ -587,23 +609,54 @@ public StringBuffer format(final Date date, final StringBuffer buf) { * @see org.apache.commons.lang3.time.DatePrinter#format(java.util.Calendar, java.lang.Appendable) */ + /** + * format + * + * @param calendar calendar + * @param buf buf + * @return StringBuffer + */ public StringBuffer format(final Calendar calendar, final StringBuffer buf) { // do not pass in calendar directly, this will cause TimeZone of FastDatePrinter to be ignored return format(calendar.getTime(), buf); } + /** + * format + * + * @param millis millis + * @param buf buf + * @param buf class + * @return Appendable + */ public B format(final long millis, final B buf) { final Calendar c = newCalendar(); c.setTimeInMillis(millis); return applyRules(c, buf); } + /** + * format + * + * @param date date + * @param buf buf + * @param buf class + * @return Appendable + */ public B format(final Date date, final B buf) { final Calendar c = newCalendar(); c.setTime(date); return applyRules(c, buf); } + /** + * format + * + * @param calendar calendar + * @param buf buf + * @param buf class + * @return Appendable + */ public B format(Calendar calendar, final B buf) { // do not pass in calendar directly, this will cause TimeZone of FastDatePrinter to be ignored if (!calendar.getTimeZone().equals(mTimeZone)) { @@ -656,6 +709,12 @@ private B applyRules(final Calendar calendar, final B buf /* (non-Javadoc) * @see org.apache.commons.lang3.time.DatePrinter#getPattern() */ + + /** + * getPattern + * + * @return Pattern + */ public String getPattern() { return mPattern; } @@ -666,10 +725,21 @@ public String getPattern() { /* (non-Javadoc) * @see org.apache.commons.lang3.time.DatePrinter#getTimeZone() */ + + /** + * get TimeZone + * + * @return TimeZone + */ public TimeZone getTimeZone() { return mTimeZone; } + /** + * get Locale + * + * @return Locale + */ public Locale getLocale() { return mLocale; } @@ -677,7 +747,6 @@ public Locale getLocale() { /** *

Gets an estimate for the maximum string length that the * formatter will produce.

- *

*

The actual formatted length will almost always be less than or * equal to this amount.

* @@ -696,7 +765,6 @@ public int getMaxLengthEstimate() { * @param obj the object to compare to * @return {@code true} if equal */ - public boolean equals(final Object obj) { if (obj instanceof FastDatePrinter == false) { return false; @@ -712,7 +780,6 @@ public boolean equals(final Object obj) { * * @return a hash code compatible with equals */ - public int hashCode() { return mPattern.hashCode() + 13 * (mTimeZone.hashCode() + 13 * mLocale.hashCode()); } @@ -722,7 +789,6 @@ public int hashCode() { * * @return a debugging string */ - public String toString() { return "FastDatePrinter[" + mPattern + "," + mLocale + "," + mTimeZone.getID() + "]"; } @@ -797,7 +863,6 @@ private static class CharacterLiteral implements Rule { /** * {@inheritDoc} */ - public int estimateLength() { return 1; } @@ -805,7 +870,6 @@ public int estimateLength() { /** * {@inheritDoc} */ - public void appendTo(final Appendable buffer, final Calendar calendar) throws IOException { buffer.append(mValue); } @@ -830,7 +894,6 @@ private static class StringLiteral implements Rule { /** * {@inheritDoc} */ - public int estimateLength() { return mValue.length(); } @@ -838,7 +901,6 @@ public int estimateLength() { /** * {@inheritDoc} */ - public void appendTo(final Appendable buffer, final Calendar calendar) throws IOException { buffer.append(mValue); } @@ -866,7 +928,6 @@ private static class TextField implements Rule { /** * {@inheritDoc} */ - public int estimateLength() { int max = 0; for (int i = mValues.length; --i >= 0; ) { @@ -881,7 +942,6 @@ public int estimateLength() { /** * {@inheritDoc} */ - public void appendTo(final Appendable buffer, final Calendar calendar) throws IOException { buffer.append(mValues[calendar.get(mField)]); } @@ -905,7 +965,6 @@ private static class UnpaddedNumberField implements NumberRule { /** * {@inheritDoc} */ - public int estimateLength() { return 4; } @@ -913,7 +972,6 @@ public int estimateLength() { /** * {@inheritDoc} */ - public void appendTo(final Appendable buffer, final Calendar calendar) throws IOException { appendTo(buffer, calendar.get(mField)); } @@ -921,7 +979,6 @@ public void appendTo(final Appendable buffer, final Calendar calendar) throws IO /** * {@inheritDoc} */ - public final void appendTo(final Appendable buffer, final int value) throws IOException { if (value < 10) { buffer.append((char) (value + '0')); @@ -949,7 +1006,6 @@ private static class UnpaddedMonthField implements NumberRule { /** * {@inheritDoc} */ - public int estimateLength() { return 2; } @@ -957,7 +1013,6 @@ public int estimateLength() { /** * {@inheritDoc} */ - public void appendTo(final Appendable buffer, final Calendar calendar) throws IOException { appendTo(buffer, calendar.get(Calendar.MONTH) + 1); } @@ -965,7 +1020,6 @@ public void appendTo(final Appendable buffer, final Calendar calendar) throws IO /** * {@inheritDoc} */ - public final void appendTo(final Appendable buffer, final int value) throws IOException { if (value < 10) { buffer.append((char) (value + '0')); @@ -1000,7 +1054,6 @@ private static class PaddedNumberField implements NumberRule { /** * {@inheritDoc} */ - public int estimateLength() { return mSize; } @@ -1008,7 +1061,6 @@ public int estimateLength() { /** * {@inheritDoc} */ - public void appendTo(final Appendable buffer, final Calendar calendar) throws IOException { appendTo(buffer, calendar.get(mField)); } @@ -1016,7 +1068,6 @@ public void appendTo(final Appendable buffer, final Calendar calendar) throws IO /** * {@inheritDoc} */ - public final void appendTo(final Appendable buffer, final int value) throws IOException { appendFullDigits(buffer, value, mSize); } @@ -1040,7 +1091,6 @@ private static class TwoDigitNumberField implements NumberRule { /** * {@inheritDoc} */ - public int estimateLength() { return 2; } @@ -1048,7 +1098,6 @@ public int estimateLength() { /** * {@inheritDoc} */ - public void appendTo(final Appendable buffer, final Calendar calendar) throws IOException { appendTo(buffer, calendar.get(mField)); } @@ -1056,7 +1105,6 @@ public void appendTo(final Appendable buffer, final Calendar calendar) throws IO /** * {@inheritDoc} */ - public final void appendTo(final Appendable buffer, final int value) throws IOException { if (value < 100) { appendDigits(buffer, value); @@ -1082,7 +1130,6 @@ private static class TwoDigitYearField implements NumberRule { /** * {@inheritDoc} */ - public int estimateLength() { return 2; } @@ -1090,7 +1137,6 @@ public int estimateLength() { /** * {@inheritDoc} */ - public void appendTo(final Appendable buffer, final Calendar calendar) throws IOException { appendTo(buffer, calendar.get(Calendar.YEAR) % 100); } @@ -1098,7 +1144,6 @@ public void appendTo(final Appendable buffer, final Calendar calendar) throws IO /** * {@inheritDoc} */ - public final void appendTo(final Appendable buffer, final int value) throws IOException { appendDigits(buffer, value); } @@ -1120,7 +1165,6 @@ private static class TwoDigitMonthField implements NumberRule { /** * {@inheritDoc} */ - public int estimateLength() { return 2; } @@ -1128,7 +1172,6 @@ public int estimateLength() { /** * {@inheritDoc} */ - public void appendTo(final Appendable buffer, final Calendar calendar) throws IOException { appendTo(buffer, calendar.get(Calendar.MONTH) + 1); } @@ -1136,7 +1179,6 @@ public void appendTo(final Appendable buffer, final Calendar calendar) throws IO /** * {@inheritDoc} */ - public final void appendTo(final Appendable buffer, final int value) throws IOException { appendDigits(buffer, value); } @@ -1161,7 +1203,6 @@ private static class TwelveHourField implements NumberRule { /** * {@inheritDoc} */ - public int estimateLength() { return mRule.estimateLength(); } @@ -1169,7 +1210,6 @@ public int estimateLength() { /** * {@inheritDoc} */ - public void appendTo(final Appendable buffer, final Calendar calendar) throws IOException { int value = calendar.get(Calendar.HOUR); if (value == 0) { @@ -1181,7 +1221,6 @@ public void appendTo(final Appendable buffer, final Calendar calendar) throws IO /** * {@inheritDoc} */ - public void appendTo(final Appendable buffer, final int value) throws IOException { mRule.appendTo(buffer, value); } @@ -1206,7 +1245,6 @@ private static class TwentyFourHourField implements NumberRule { /** * {@inheritDoc} */ - public int estimateLength() { return mRule.estimateLength(); } @@ -1214,7 +1252,6 @@ public int estimateLength() { /** * {@inheritDoc} */ - public void appendTo(final Appendable buffer, final Calendar calendar) throws IOException { int value = calendar.get(Calendar.HOUR_OF_DAY); if (value == 0) { @@ -1226,7 +1263,6 @@ public void appendTo(final Appendable buffer, final Calendar calendar) throws IO /** * {@inheritDoc} */ - public void appendTo(final Appendable buffer, final int value) throws IOException { mRule.appendTo(buffer, value); } @@ -1243,17 +1279,36 @@ private static class DayInWeekField implements NumberRule { } + /** + * estimateLength + * + * @return estimateLength + */ public int estimateLength() { return mRule.estimateLength(); } + /** + * append + * + * @param buffer the output buffer + * @param calendar calendar to be appended + * @throws IOException IOException + */ public void appendTo(final Appendable buffer, final Calendar calendar) throws IOException { final int value = calendar.get(Calendar.DAY_OF_WEEK); mRule.appendTo(buffer, value != Calendar.SUNDAY ? value - 1 : 7); } + /** + * appendTo + * + * @param buffer the output buffer + * @param value the value to be appended + * @throws IOException IOException + */ public void appendTo(final Appendable buffer, final int value) throws IOException { mRule.appendTo(buffer, value); } @@ -1357,7 +1412,6 @@ private static class TimeZoneNumberRule implements Rule { /** * {@inheritDoc} */ - public int estimateLength() { return 5; } @@ -1365,7 +1419,6 @@ public int estimateLength() { /** * {@inheritDoc} */ - public void appendTo(final Appendable buffer, final Calendar calendar) throws IOException { int offset = calendar.get(Calendar.ZONE_OFFSET) + calendar.get(Calendar.DST_OFFSET); @@ -1435,7 +1488,6 @@ static Iso8601_Rule getRule(final int tokenLen) { /** * {@inheritDoc} */ - public int estimateLength() { return length; } @@ -1443,7 +1495,6 @@ public int estimateLength() { /** * {@inheritDoc} */ - public void appendTo(final Appendable buffer, final Calendar calendar) throws IOException { int offset = calendar.get(Calendar.ZONE_OFFSET) + calendar.get(Calendar.DST_OFFSET); if (offset == 0) { diff --git a/library/src/main/java/com/qiniu/android/utils/GZipUtil.java b/library/src/main/java/com/qiniu/android/utils/GZipUtil.java index 01d2f2988..c050ceca8 100644 --- a/library/src/main/java/com/qiniu/android/utils/GZipUtil.java +++ b/library/src/main/java/com/qiniu/android/utils/GZipUtil.java @@ -6,20 +6,40 @@ import java.util.zip.GZIPInputStream; import java.util.zip.GZIPOutputStream; +/** + * GZip 工具 + * + * @hidden + */ public class GZipUtil { - public static byte[] gZip(String string){ - if (string == null){ + private GZipUtil() { + } + + /** + * 压缩字符串 + * + * @param string 带压缩数据 + * @return 压缩后的数据 + */ + public static byte[] gZip(String string) { + if (string == null) { return null; } return gZip(string.getBytes()); } - public static byte[] gZip(byte[] bytes){ - if (bytes == null){ + /** + * 压缩 byte 数组 + * + * @param bytes 带压缩数据 + * @return 压缩后的数据 + */ + public static byte[] gZip(byte[] bytes) { + if (bytes == null) { return null; } - if (bytes.length == 0){ + if (bytes.length == 0) { return bytes; } @@ -28,12 +48,12 @@ public static byte[] gZip(byte[] bytes){ try { gzip = new GZIPOutputStream(out); gzip.write(bytes); - } catch (IOException e){ + } catch (IOException e) { } finally { - if (gzip != null){ + if (gzip != null) { try { gzip.close(); - } catch (IOException e){ + } catch (IOException e) { } } } @@ -41,11 +61,17 @@ public static byte[] gZip(byte[] bytes){ return out.toByteArray(); } + /** + * 解压缩 byte 数组 + * + * @param bytes 待解压缩数据 + * @return 解压缩后的数据 + */ public static byte[] gUnzip(byte[] bytes) { - if (bytes == null){ + if (bytes == null) { return null; } - if (bytes.length == 0){ + if (bytes.length == 0) { return bytes; } diff --git a/library/src/main/java/com/qiniu/android/utils/GroupTaskThread.java b/library/src/main/java/com/qiniu/android/utils/GroupTaskThread.java index 5022ea5e1..c6279be6c 100644 --- a/library/src/main/java/com/qiniu/android/utils/GroupTaskThread.java +++ b/library/src/main/java/com/qiniu/android/utils/GroupTaskThread.java @@ -2,21 +2,37 @@ import java.util.ArrayList; +/** + * 组任务线程 + * + * @hidden + */ public class GroupTaskThread extends Thread { + /** + * 组任务执行完成回调 + */ public final GroupTaskCompleteHandler completeHandler; private ArrayList tasks = new ArrayList(); + /** + * 构造函数 + * + * @param completeHandler 组任务执行完成回调 + */ public GroupTaskThread(GroupTaskCompleteHandler completeHandler) { this.completeHandler = completeHandler; } + /** + * 组任务开始执行 + */ @Override public void run() { super.run(); - while (!isInterrupted()){ + while (!isInterrupted()) { boolean isAllTasksCompleted = false; synchronized (this) { isAllTasksCompleted = isAllTasksCompleted(); @@ -28,17 +44,23 @@ public void run() { } GroupTask task = getNextWaitingTask(); - if (task != null){ + if (task != null) { task.state = GroupTask.State.Running; task.run(task); } else { try { sleep(10); - } catch (InterruptedException e) {} + } catch (InterruptedException e) { + } } } } + /** + * 添加任务 + * + * @param task 任务 + */ public void addTask(GroupTask task) { synchronized (this) { if (!isAllTasksCompleted()) { @@ -47,66 +69,121 @@ public void addTask(GroupTask task) { } } - private GroupTask getNextWaitingTask(){ + private GroupTask getNextWaitingTask() { GroupTask task = null; for (int i = 0; i < tasks.size(); i++) { GroupTask taskP = tasks.get(i); - if (taskP.state == GroupTask.State.Waiting){ + if (taskP.state == GroupTask.State.Waiting) { task = taskP; break; } } return task; } - private boolean isAllTasksCompleted(){ - if (tasks.size() == 0){ + + private boolean isAllTasksCompleted() { + if (tasks.size() == 0) { return false; } boolean ret = true; for (int i = 0; i < tasks.size(); i++) { GroupTask task = tasks.get(i); - if (task.state != GroupTask.State.Complete){ + if (task.state != GroupTask.State.Complete) { ret = false; break; } } return ret; } - private void completeAction(){ - if (completeHandler != null){ + + private void completeAction() { + if (completeHandler != null) { completeHandler.complete(); } } + /** + * 组任务 + * + * @hidden + */ + public abstract static class GroupTask { - public abstract static class GroupTask{ - + /** + * task 状态 + * + * @hidden + */ protected enum State { + /** + * 等待执行 + */ Waiting, + + /** + * 执行中 + */ Running, + + /** + * 执行完成 + */ Complete - }; + } + /** + * task 状态 + */ protected State state = State.Waiting; + + /** + * 任务 ID + */ public final String id; + /** + * 构造函数 + */ public GroupTask() { this.id = null; } + + /** + * 构造函数 + * + * @param id 任务 ID + */ public GroupTask(String id) { this.id = id; } + /** + * 执行任务 + * + * @param task 任务 + */ public abstract void run(GroupTask task); - public void taskComplete(){ + + /** + * 任务执行结束 + */ + public void taskComplete() { state = State.Complete; } } - + /** + * 任务执行结束回调 + * + * @hidden + */ public interface GroupTaskCompleteHandler { + + /** + * 任务执行结束回调 + */ void complete(); } } diff --git a/library/src/main/java/com/qiniu/android/utils/IPAddressUtil.java b/library/src/main/java/com/qiniu/android/utils/IPAddressUtil.java index 4d3f46968..7bc3fb3dd 100644 --- a/library/src/main/java/com/qiniu/android/utils/IPAddressUtil.java +++ b/library/src/main/java/com/qiniu/android/utils/IPAddressUtil.java @@ -1,11 +1,19 @@ package com.qiniu.android.utils; +/** + * ip util + * + * @hidden + */ public class IPAddressUtil { private final static int INADDR4SZ = 4; private final static int INADDR16SZ = 16; private final static int INT16SZ = 2; - /* + private IPAddressUtil() { + } + + /** * Converts IPv4 address in its textual presentation form * into its numeric binary form. * @@ -13,8 +21,7 @@ public class IPAddressUtil { * @return a byte array representing the IPv4 numeric address */ @SuppressWarnings("fallthrough") - public static byte[] textToNumericFormatV4(String src) - { + public static byte[] textToNumericFormatV4(String src) { byte[] res = new byte[INADDR4SZ]; long tmpValue = 0; @@ -75,25 +82,23 @@ public static byte[] textToNumericFormatV4(String src) case 1: res[1] = (byte) ((tmpValue >> 16) & 0xff); case 2: - res[2] = (byte) ((tmpValue >> 8) & 0xff); + res[2] = (byte) ((tmpValue >> 8) & 0xff); case 3: - res[3] = (byte) ((tmpValue >> 0) & 0xff); + res[3] = (byte) ((tmpValue >> 0) & 0xff); } return res; } - /* + /** * Convert IPv6 presentation level address to network order binary form. * credit: - * Converted from C code from Solaris 8 (inet_pton) - * + * Converted from C code from Solaris 8 (inet_pton) * Any component of the string following a per-cent % is ignored. * * @param src a String representing an IPv6 address in textual format * @return a byte array representing the IPv6 numeric address */ - public static byte[] textToNumericFormatV6(String src) - { + public static byte[] textToNumericFormatV6(String src) { // Shortest valid string is "::", hence at least 2 chars if (src.length() < 2) { return null; @@ -107,8 +112,8 @@ public static byte[] textToNumericFormatV6(String src) byte[] dst = new byte[INADDR16SZ]; int srcb_length = srcb.length; - int pc = src.indexOf ("%"); - if (pc == srcb_length -1) { + int pc = src.indexOf("%"); + if (pc == srcb_length - 1) { return null; } @@ -157,10 +162,10 @@ public static byte[] textToNumericFormatV6(String src) if (ch == '.' && ((j + INADDR4SZ) <= INADDR16SZ)) { String ia4 = src.substring(curtok, srcb_length); /* check this IPv4 address has 3 dots, ie. A.B.C.D */ - int dot_count = 0, index=0; - while ((index = ia4.indexOf ('.', index)) != -1) { - dot_count ++; - index ++; + int dot_count = 0, index = 0; + while ((index = ia4.indexOf('.', index)) != -1) { + dot_count++; + index++; } if (dot_count != 3) { return null; @@ -206,6 +211,8 @@ public static byte[] textToNumericFormatV6(String src) } /** + * isIPv4LiteralAddress + * * @param src a String representing an IPv4 address in textual format * @return a boolean indicating whether src is an IPv4 literal address */ @@ -214,6 +221,8 @@ public static boolean isIPv4LiteralAddress(String src) { } /** + * isIPv6LiteralAddress + * * @param src a String representing an IPv6 address in textual format * @return a boolean indicating whether src is an IPv6 literal address */ @@ -221,11 +230,11 @@ public static boolean isIPv6LiteralAddress(String src) { return textToNumericFormatV6(src) != null; } - /* + /** * Convert IPv4-Mapped address to IPv4 address. Both input and * returned value are in network order binary form. * - * @param src a String representing an IPv4-Mapped address in textual format + * @param addr a String representing an IPv4-Mapped address in textual format * @return a byte array representing the IPv4 numeric address */ public static byte[] convertFromIPv4MappedAddress(byte[] addr) { @@ -253,8 +262,8 @@ private static boolean isIPv4MappedAddress(byte[] addr) { (addr[4] == 0x00) && (addr[5] == 0x00) && (addr[6] == 0x00) && (addr[7] == 0x00) && (addr[8] == 0x00) && (addr[9] == 0x00) && - (addr[10] == (byte)0xff) && - (addr[11] == (byte)0xff)) { + (addr[10] == (byte) 0xff) && + (addr[11] == (byte) 0xff)) { return true; } return false; diff --git a/library/src/main/java/com/qiniu/android/utils/Json.java b/library/src/main/java/com/qiniu/android/utils/Json.java index 8d0762b6e..d66698729 100644 --- a/library/src/main/java/com/qiniu/android/utils/Json.java +++ b/library/src/main/java/com/qiniu/android/utils/Json.java @@ -8,14 +8,31 @@ /** * Created by long on 2017/7/25. + * + * @hidden */ - public final class Json { + + private Json() { + } + + /** + * map 转 json + * + * @param map map + * @return json string + */ public static String encodeMap(Map map) { JSONObject obj = new JSONObject(map); return obj.toString(); } + /** + * Collection 转 json + * + * @param collection Collection + * @return json string + */ public static String encodeList(Collection collection) { JSONArray array = new JSONArray(collection); return array.toString(); diff --git a/library/src/main/java/com/qiniu/android/utils/ListVector.java b/library/src/main/java/com/qiniu/android/utils/ListVector.java index 5b203a651..ab5c16735 100644 --- a/library/src/main/java/com/qiniu/android/utils/ListVector.java +++ b/library/src/main/java/com/qiniu/android/utils/ListVector.java @@ -6,16 +6,36 @@ import java.util.Vector; import java.util.concurrent.CopyOnWriteArrayList; +/** + * ListVector + * + * @param 元素类型 + * @hidden + */ public class ListVector extends Vector { + /** + * 构造函数 + */ public ListVector() { super(); } + /** + * 构造函数 + * + * @param initialCapacity initialCapacity + * @param capacityIncrement capacityIncrement + */ public ListVector(int initialCapacity, int capacityIncrement) { super(initialCapacity, capacityIncrement); } + /** + * 对象遍历 + * + * @param handler handler + */ public synchronized void enumerateObjects(EnumeratorHandler handler) { if (handler == null) { return; @@ -30,6 +50,13 @@ public synchronized void enumerateObjects(EnumeratorHandler handler) } } + /** + * create subList + * + * @param fromIndex low endpoint (inclusive) of the subList + * @param toIndex high endpoint (exclusive) of the subList + * @return subList + */ @Override public synchronized ListVector subList(int fromIndex, int toIndex) { ListVector listVector = new ListVector(); @@ -44,7 +71,20 @@ public synchronized ListVector subList(int fromIndex, int toIndex) { return listVector; } + /** + * EnumeratorHandler + * + * @param enumerate 对象的类型 + * @hidden + */ public interface EnumeratorHandler { + + /** + * enumerate + * + * @param t T + * @return stop + */ boolean enumerate(T t); } } diff --git a/library/src/main/java/com/qiniu/android/utils/LogUtil.java b/library/src/main/java/com/qiniu/android/utils/LogUtil.java index 7331b9593..13665f9cb 100644 --- a/library/src/main/java/com/qiniu/android/utils/LogUtil.java +++ b/library/src/main/java/com/qiniu/android/utils/LogUtil.java @@ -15,22 +15,50 @@ public class LogUtil { private static boolean enableFile = true; private static boolean enableFunction = false; + private LogUtil() { + } + + /** + * 开启日志 + * + * @param enable 是否开启日志 + */ public static void enableLog(boolean enable) { enableLog = enable; } + /** + * 日志中是否包含 Date + * + * @param enable 是否包含 Date + */ public static void enableDate(boolean enable) { enableDate = enable; } + /** + * 日志中是否包含 File + * + * @param enable 是否包含 File + */ public static void enableFile(boolean enable) { enableFile = enable; } + /** + * 日志中是否包含 Function + * + * @param enable 是否包含 Function + */ public static void enableFunction(boolean enable) { enableFunction = enable; } + /** + * 设置日志等级 + * + * @param level 日志等级 + */ public static void setLogLevel(int level) { logLevel = level; } @@ -39,6 +67,7 @@ public static void setLogLevel(int level) { * Send a VERBOSE log message. * * @param msg The message you would like logged. + * @return int */ public static int v(String msg) { return println(Log.VERBOSE, null, msg, null); @@ -50,6 +79,7 @@ public static int v(String msg) { * @param tag Used to identify the source of a log message. It usually identifies * the class or activity where the log call occurs. * @param msg The message you would like logged. + * @return int */ public static int v(String tag, String msg) { return println(Log.VERBOSE, tag, msg, null); @@ -62,6 +92,7 @@ public static int v(String tag, String msg) { * the class or activity where the log call occurs. * @param msg The message you would like logged. * @param tr An exception to log + * @return int */ public static int v(String tag, String msg, Throwable tr) { return println(Log.VERBOSE, tag, msg, tr); @@ -71,6 +102,7 @@ public static int v(String tag, String msg, Throwable tr) { * Send a DEBUG log message. * * @param msg The message you would like logged. + * @return int */ public static int d(String msg) { return println(Log.DEBUG, null, msg, null); @@ -82,6 +114,7 @@ public static int d(String msg) { * @param tag Used to identify the source of a log message. It usually identifies * the class or activity where the log call occurs. * @param msg The message you would like logged. + * @return int */ public static int d(String tag, String msg) { return println(Log.DEBUG, tag, msg, null); @@ -94,6 +127,7 @@ public static int d(String tag, String msg) { * the class or activity where the log call occurs. * @param msg The message you would like logged. * @param tr An exception to log + * @return int */ public static int d(String tag, String msg, Throwable tr) { return println(Log.DEBUG, tag, msg, tr); @@ -103,6 +137,7 @@ public static int d(String tag, String msg, Throwable tr) { * Send an INFO log message. * * @param msg The message you would like logged. + * @return int */ public static int i(String msg) { return println(Log.INFO, null, msg, null); @@ -114,6 +149,7 @@ public static int i(String msg) { * @param tag Used to identify the source of a log message. It usually identifies * the class or activity where the log call occurs. * @param msg The message you would like logged. + * @return int */ public static int i(String tag, String msg) { return println(Log.INFO, tag, msg, null); @@ -126,6 +162,7 @@ public static int i(String tag, String msg) { * the class or activity where the log call occurs. * @param msg The message you would like logged. * @param tr An exception to log + * @return int */ public static int i(String tag, String msg, Throwable tr) { return println(Log.INFO, tag, msg, tr); @@ -135,6 +172,7 @@ public static int i(String tag, String msg, Throwable tr) { * Send a WARN log message. * * @param msg The message you would like logged. + * @return int */ public static int w(String msg) { return println(Log.WARN, null, msg, null); @@ -146,6 +184,7 @@ public static int w(String msg) { * @param tag Used to identify the source of a log message. It usually identifies * the class or activity where the log call occurs. * @param msg The message you would like logged. + * @return int */ public static int w(String tag, String msg) { return println(Log.WARN, tag, msg, null); @@ -158,16 +197,19 @@ public static int w(String tag, String msg) { * the class or activity where the log call occurs. * @param msg The message you would like logged. * @param tr An exception to log + * @return int */ public static int w(String tag, String msg, Throwable tr) { return println(Log.WARN, tag, msg, tr); } - /* + /** * Send a WARN log message and log the exception. + * * @param tag Used to identify the source of a log message. It usually identifies - * the class or activity where the log call occurs. - * @param tr An exception to log + * the class or activity where the log call occurs. + * @param tr An exception to log + * @return int */ public static int w(String tag, Throwable tr) { return println(Log.WARN, tag, null, tr); @@ -177,6 +219,7 @@ public static int w(String tag, Throwable tr) { * Send an ERROR log message. * * @param msg The message you would like logged. + * @return int */ public static int e(String msg) { return println(Log.ERROR, null, msg, null); @@ -188,6 +231,7 @@ public static int e(String msg) { * @param tag Used to identify the source of a log message. It usually identifies * the class or activity where the log call occurs. * @param msg The message you would like logged. + * @return int */ public static int e(String tag, String msg) { return println(Log.ERROR, tag, msg, null); @@ -200,6 +244,7 @@ public static int e(String tag, String msg) { * the class or activity where the log call occurs. * @param msg The message you would like logged. * @param tr An exception to log + * @return int */ public static int e(String tag, String msg, Throwable tr) { return println(Log.ERROR, tag, msg, tr); diff --git a/library/src/main/java/com/qiniu/android/utils/MD5.java b/library/src/main/java/com/qiniu/android/utils/MD5.java index f6ca47eb6..393fd4d7b 100644 --- a/library/src/main/java/com/qiniu/android/utils/MD5.java +++ b/library/src/main/java/com/qiniu/android/utils/MD5.java @@ -1,9 +1,25 @@ package com.qiniu.android.utils; + import java.security.MessageDigest; + import com.qiniu.android.dns.util.Hex; +/** + * MD5 util + * + * @hidden + */ public class MD5 { + private MD5() { + } + + /** + * MD5 加密 + * + * @param data 带加密数据 + * @return 已加密数据 + */ public static String encrypt(byte[] data) { try { MessageDigest digest = MessageDigest.getInstance("MD5"); diff --git a/library/src/main/java/com/qiniu/android/utils/SingleFlight.java b/library/src/main/java/com/qiniu/android/utils/SingleFlight.java index db6e5a632..e1836f223 100644 --- a/library/src/main/java/com/qiniu/android/utils/SingleFlight.java +++ b/library/src/main/java/com/qiniu/android/utils/SingleFlight.java @@ -5,16 +5,29 @@ import java.util.List; import java.util.Map; +/** + * single flight + * + * @param T + * @hidden + */ public class SingleFlight { private Map> callInfo = new HashMap<>(); + /** + * 构造函数 + */ + public SingleFlight() { + } + /** * 异步 SingleFlight 执行函数 * * @param key actionHandler 对应的 key,同一时刻同一个 key 最多只有一个对应的 actionHandler 在执行 * @param actionHandler 执行函数,注意:actionHandler 中,【完成回调】和【抛出异常】二者有且有一个,且只能出现一次 * @param completeHandler single flight 执行 actionHandler 后的完成回调 + * @throws Exception 异常 */ public void perform(String key, ActionHandler actionHandler, CompleteHandler completeHandler) throws Exception { if (actionHandler == null) { @@ -124,11 +137,36 @@ private static class SingleFlightCall { private Exception exception; } + /** + * 结束回调 + * + * @param T + * @hidden + */ public interface CompleteHandler { + + /** + * 结束回调 + * + * @param value value + */ void complete(T value); } + /** + * action 回调 + * + * @param T + * @hidden + */ public interface ActionHandler { + + /** + * action 回调 + * + * @param completeHandler 结束回调 + * @throws Exception 异常 + */ void action(CompleteHandler completeHandler) throws Exception; } } diff --git a/library/src/main/java/com/qiniu/android/utils/StringMap.java b/library/src/main/java/com/qiniu/android/utils/StringMap.java index e410f302c..b0a2f7b12 100644 --- a/library/src/main/java/com/qiniu/android/utils/StringMap.java +++ b/library/src/main/java/com/qiniu/android/utils/StringMap.java @@ -5,22 +5,47 @@ import java.util.HashMap; import java.util.Map; +/** + * string map + */ public final class StringMap { private Map map; + /** + * 构造函数 + */ public StringMap() { this(new HashMap()); } + /** + * 构造函数 + * + * @param map map + */ public StringMap(Map map) { this.map = map; } + /** + * 新增键值对 + * + * @param key 键 + * @param value 值 + * @return StringMap + */ public StringMap put(String key, Object value) { map.put(key, value); return this; } + /** + * 新增非空键值对 + * + * @param key 键 + * @param value 值 + * @return StringMap + */ public StringMap putNotEmpty(String key, String value) { if (!StringUtils.isNullOrEmpty(value)) { map.put(key, value); @@ -28,6 +53,13 @@ public StringMap putNotEmpty(String key, String value) { return this; } + /** + * 新增非空键值对 + * + * @param key 键 + * @param value 值 + * @return StringMap + */ public StringMap putNotNull(String key, Object value) { if (value != null) { map.put(key, value); @@ -36,6 +68,14 @@ public StringMap putNotNull(String key, Object value) { } + /** + * 新增键值对 + * + * @param key 键 + * @param val 值 + * @param when 条件 + * @return StringMap + */ public StringMap putWhen(String key, Object val, boolean when) { if (when) { map.put(key, val); @@ -43,39 +83,83 @@ public StringMap putWhen(String key, Object val, boolean when) { return this; } + /** + * 新增键值对 + * + * @param map map + * @return StringMap + */ public StringMap putAll(Map map) { this.map.putAll(map); return this; } + /** + * 新增键值对 + * + * @param map map + * @return StringMap + */ public StringMap putFileds(Map map) { this.map.putAll(map); return this; } + /** + * 新增键值对 + * + * @param map map + * @return StringMap + */ public StringMap putAll(StringMap map) { this.map.putAll(map.map); return this; } + /** + * 遍历 + * + * @param imp Consumer + */ public void forEach(Consumer imp) { for (Map.Entry i : map.entrySet()) { imp.accept(i.getKey(), i.getValue()); } } + /** + * 获取 map 大小 + * + * @return map 大小 + */ public int size() { return map.size(); } + /** + * 获取 map + * + * @return map + */ public Map map() { return this.map; } + /** + * 获取 value + * + * @param key key + * @return value + */ public Object get(String key) { return map.get(key); } + /** + * 获取 string + * + * @return string + */ public String formString() { final StringBuilder b = new StringBuilder(); forEach(new Consumer() { @@ -98,7 +182,17 @@ public void accept(String key, Object value) { return b.toString(); } + /** + * 遍历回调 + */ public interface Consumer { + + /** + * 遍历回调 + * + * @param key key + * @param value value + */ void accept(String key, Object value); } } diff --git a/library/src/main/java/com/qiniu/android/utils/StringUtils.java b/library/src/main/java/com/qiniu/android/utils/StringUtils.java index 9b349044c..d36c9b41a 100644 --- a/library/src/main/java/com/qiniu/android/utils/StringUtils.java +++ b/library/src/main/java/com/qiniu/android/utils/StringUtils.java @@ -12,12 +12,16 @@ /** * 字符串连接工具类 + * + * @hidden */ public final class StringUtils { + private StringUtils() { + } + /** * 以指定的分隔符来进行字符串元素连接 - *

* 例如有字符串数组array和连接符为逗号(,) * * String[] array = new String[] { "hello", "world", "qiniu", "cloud","storage" }; @@ -26,7 +30,6 @@ public final class StringUtils { * * hello,world,qiniu,cloud,storage * - *

* * @param array 需要连接的字符串数组 * @param sep 元素连接之间的分隔符 @@ -59,7 +62,6 @@ public static String join(String[] array, String sep) { /** * 以json元素的方式连接字符串中元素 - *

* 例如有字符串数组array * * String[] array = new String[] { "hello", "world", "qiniu", "cloud","storage" }; @@ -68,7 +70,6 @@ public static String join(String[] array, String sep) { * * "hello","world","qiniu","cloud","storage" * - *

* * @param array 需要连接的字符串数组 * @return 以json元素方式连接好的新字符串 @@ -92,11 +93,22 @@ public static String jsonJoin(String[] array) { return buf.toString(); } - + /** + * json join + * + * @param array Long 数组 + * @return json string + */ public static String jsonJoin(Long[] array) { return jsonJoin(longToString(array)); } + /** + * Long 数组转 String 数组 + * + * @param longArray Long 数组 + * @return String 数组 + */ public static String[] longToString(Long longArray[]) { String stringArray[] = new String[longArray.length]; for (int i = 0; i < stringArray.length; i++) { @@ -111,6 +123,12 @@ public static String[] longToString(Long longArray[]) { } + /** + * 获取 utf8 数据 + * + * @param data 原数据 + * @return utf8 数据 + */ public static byte[] utf8Bytes(String data) { try { return data.getBytes(Constants.UTF_8); @@ -119,18 +137,42 @@ public static byte[] utf8Bytes(String data) { } } + /** + * 判断字符串是否为空 + * + * @param s 字符串 + * @return 是否为空 + */ public static boolean isNullOrEmpty(String s) { return s == null || "".equals(s); } + /** + * 转换成非空字符串 + * + * @param s 待转对象 + * @return String + */ public static String toNonnullString(Object s) { return s == null ? "" : "" + s; } + /** + * 判断字符串是否为空或者仅包含空格 + * + * @param s 字符串 + * @return 判断结果 + */ public static boolean isBlank(String s) { return s == null || s.trim().equals(""); } + /** + * strip + * + * @param s 待处理字符串 + * @return strip 后的字符串 + */ public static String strip(String s) { StringBuilder b = new StringBuilder(); for (int i = 0, length = s.length(); i < length; i++) { @@ -145,8 +187,8 @@ public static String strip(String s) { /** * 对象转数组 * - * @param obj - * @return + * @param obj obj + * @return byte array */ public static byte[] toByteArray(Object obj) { byte[] bytes = null; @@ -173,8 +215,8 @@ public static byte[] toByteArray(Object obj) { /** * 数组转对象 * - * @param bytes - * @return + * @param bytes bytes + * @return Object */ public static Object toObject(byte[] bytes) { Object obj = null; @@ -195,6 +237,12 @@ public static Object toObject(byte[] bytes) { return obj; } + /** + * 获取 Token 中的 AK + Scope + * + * @param token 上传的 Token + * @return Token 中的 AK + Scope + */ public static String getAkAndScope(String token) { String[] strings = token.split(":"); String ak = strings[0]; @@ -211,6 +259,12 @@ public static String getAkAndScope(String token) { return null; } + /** + * 获取 Token 中的 Bucket + * + * @param token 上传 Token + * @return Bucket + */ public static String getBucket(String token) { String[] strings = token.split(":"); String policy = null; @@ -226,6 +280,12 @@ public static String getBucket(String token) { return ""; } + /** + * 转大写 + * + * @param str str + * @return 转之后的字符串 + */ public static String upperCase(String str) { if (str.length() <= 0 || str == null) { return ""; diff --git a/library/src/main/java/com/qiniu/android/utils/UrlSafeBase64.java b/library/src/main/java/com/qiniu/android/utils/UrlSafeBase64.java index 8aa455abd..365df704b 100644 --- a/library/src/main/java/com/qiniu/android/utils/UrlSafeBase64.java +++ b/library/src/main/java/com/qiniu/android/utils/UrlSafeBase64.java @@ -8,9 +8,14 @@ /** * URL安全的Base64编码和解码 + * + * @hidden */ public final class UrlSafeBase64 { + private UrlSafeBase64() { + } + /** * 编码字符串 * @@ -46,7 +51,7 @@ public static String encodeToString(byte[] data) { public static byte[] decode(String data) { try { return Base64.decode(data, Base64.URL_SAFE | Base64.NO_WRAP); - } catch (RuntimeException e){ + } catch (RuntimeException e) { return null; } } diff --git a/library/src/main/java/com/qiniu/android/utils/UrlUtils.java b/library/src/main/java/com/qiniu/android/utils/UrlUtils.java index ecd125390..3e92fdf4c 100644 --- a/library/src/main/java/com/qiniu/android/utils/UrlUtils.java +++ b/library/src/main/java/com/qiniu/android/utils/UrlUtils.java @@ -1,7 +1,21 @@ package com.qiniu.android.utils; +/** + * UrlUtils + * + * @hidden + */ public class UrlUtils { + private UrlUtils() { + } + + /** + * 移除 host 中的 scheme + * + * @param host host + * @return host + */ public static String removeHostScheme(String host) { if (host == null || StringUtils.isNullOrEmpty(host)) { return null; @@ -16,13 +30,17 @@ public static String removeHostScheme(String host) { /** * 如果 host 包含 scheme 则优先使用 host 中包含的 scheme * 如果 host 不包含 scheme 则按照 useHttps 增加 scheme + * + * @param host host + * @param useHttps 是否使用 https 请求 + * @return url */ public static String setHostScheme(String host, boolean useHttps) { if (StringUtils.isNullOrEmpty(host)) { return null; } - if (host.startsWith("http://") || host.startsWith("https://") ) { + if (host.startsWith("http://") || host.startsWith("https://")) { return host; } diff --git a/library/src/main/java/com/qiniu/android/utils/Utils.java b/library/src/main/java/com/qiniu/android/utils/Utils.java index e571a4fe4..6995260ab 100644 --- a/library/src/main/java/com/qiniu/android/utils/Utils.java +++ b/library/src/main/java/com/qiniu/android/utils/Utils.java @@ -11,9 +11,21 @@ import java.util.Date; import java.util.Locale; +/** + * utils + */ public class Utils { private static Boolean isDebug = null; + + private Utils() { + } + + /** + * 是否是 Debug + * + * @return 是否是 Debug + */ public static boolean isDebug() { if (isDebug != null) { return isDebug; @@ -33,23 +45,51 @@ public static boolean isDebug() { } } + /** + * SDK Version + * + * @return SDK Version + */ public static String sdkVerion() { return Constants.VERSION; } + /** + * SDK Language + * + * @return SDK Language + */ public static String sdkLanguage() { return "Android"; } + /** + * 获取 PID + * + * @return PID + * @hidden + */ public static Integer getCurrentProcessID() { return android.os.Process.myPid(); } + /** + * 获取 TID + * + * @return TID + * @hidden + */ public static Long getCurrentThreadID() { Thread thread = Thread.currentThread(); return thread.getId(); } + /** + * 获取系统名 + * + * @return 系统名 + * @hidden + */ public static String systemName() { try { String model = android.os.Build.MODEL != null ? android.os.Build.MODEL.trim() : ""; @@ -78,6 +118,12 @@ private static String deviceName(String manufacturer, String model) { return manufacturer; } + /** + * 获取系统版本 + * + * @return 系统版本 + * @hidden + */ public static String systemVersion() { try { String v = android.os.Build.VERSION.RELEASE; @@ -90,10 +136,23 @@ public static String systemVersion() { } } + /** + * 获取信号强度 + * + * @return 信号强度 + * @hidden + */ + @Deprecated public static Integer getCurrentSignalStrength() { return null; } + /** + * 获取网络类型 + * + * @return 网络类型 + * @hidden + */ public static String getCurrentNetworkType() { Context context = ContextGetter.applicationContext(); if (context == null) { @@ -102,19 +161,38 @@ public static String getCurrentNetworkType() { return AndroidNetwork.networkType(context); } - /// 单位:毫秒 + /** + * 获取当前时间戳 + * 单位:毫秒 + * + * @return 当前时间戳 + * @hidden + */ public static long currentTimestamp() { return new Date().getTime(); } - // 单位:秒 + /** + * 获取当前时间戳 + * 单位:秒 + * + * @return 当前时间戳 + * @hidden + */ public static long currentSecondTimestamp() { return currentTimestamp() / 1000; } - /// 两个时间的时间段 单位:毫秒 - public static long dateDuration(Date startDate, Date endDate){ - if (startDate != null && endDate != null){ + /** + * 两个时间的时间间隔 单位:毫秒 + * + * @param startDate 开始时间 + * @param endDate 结束时间 + * @return 时间间隔 + * @hidden + */ + public static long dateDuration(Date startDate, Date endDate) { + if (startDate != null && endDate != null) { return (endDate.getTime() - startDate.getTime()); } else { return 0l; @@ -123,17 +201,24 @@ public static long dateDuration(Date startDate, Date endDate){ /** * 计算 上传 或 下载 速度 单位:B/s - * @param bytes 单位: B - * @param totalTime 单位:ms + * + * @param bytes 单位: B + * @param totalTime 单位:ms * @return 速度 + * @hidden */ - public static Long calculateSpeed(Long bytes, Long totalTime){ + public static Long calculateSpeed(Long bytes, Long totalTime) { if (bytes == null || bytes < 0 || totalTime == null || totalTime == 0) { return null; } return bytes * 1000 / totalTime; } + /** + * SDK 路径 + * + * @return SDK 路径 + */ public static String sdkDirectory() { Context context = ContextGetter.applicationContext(); if (context == null) { @@ -143,6 +228,13 @@ public static String sdkDirectory() { return directory; } + /** + * Escape 字符串 + * + * @param string 字符串 + * @return Escape 后的字符串 + * @hidden + */ public static String formEscape(String string) { if (string == null) { return null; @@ -153,6 +245,14 @@ public static String formEscape(String string) { return ret; } + /** + * 获取 ip 类型 + * + * @param ip ip + * @param host host + * @return ip 类型 + * @hidden + */ @Deprecated public static String getIpType(String ip, String host) { String type = host; @@ -167,6 +267,15 @@ public static String getIpType(String ip, String host) { return type; } + /** + * 获取 ip 类型 + * + * @param httpVersion HTTP version + * @param ip ip + * @param host host + * @return ip 类型 + * @hidden + */ public static String getIpType(String httpVersion, String ip, String host) { if (httpVersion == null) { httpVersion = ""; @@ -184,6 +293,13 @@ public static String getIpType(String httpVersion, String ip, String host) { return httpVersion + "-" + type; } + /** + * 判断 IP 是否为 IPv6 + * + * @param ip ip + * @return 是否为 IPv6 + * @hidden + */ public static boolean isIpv6(String ip) { if (StringUtils.isNullOrEmpty(ip)) { return false; diff --git a/library/src/main/java/com/qiniu/android/utils/Wait.java b/library/src/main/java/com/qiniu/android/utils/Wait.java index 60c02b08b..98eaeef04 100644 --- a/library/src/main/java/com/qiniu/android/utils/Wait.java +++ b/library/src/main/java/com/qiniu/android/utils/Wait.java @@ -2,11 +2,25 @@ import java.util.concurrent.CountDownLatch; +/** + * wait + * + * @hidden + */ public class Wait { final CountDownLatch completeSingle = new CountDownLatch(1); - public void startWait(){ + /** + * 构造函数 + */ + public Wait() { + } + + /** + * 开始等待 + */ + public void startWait() { while (completeSingle.getCount() > 0) { try { completeSingle.await(); @@ -16,7 +30,10 @@ public void startWait(){ } } - public void stopWait(){ + /** + * 停止等待 + */ + public void stopWait() { completeSingle.countDown(); } diff --git a/mvn_push.gradle b/mvn_push.gradle index 5a3cf79b2..5cced192d 100644 --- a/mvn_push.gradle +++ b/mvn_push.gradle @@ -39,12 +39,18 @@ def getRepositoryPassword() { return hasProperty('NEXUS_PASSWORD') ? NEXUS_PASSWORD : "" } -task androidJavadocs(type: Javadoc) { +task androidJavadocs(type: Javadoc, dependsOn: 'assembleRelease') { failOnError = false - source = android.sourceSets.main.java.srcDirs options.encoding = "UTF-8" options.charSet = 'UTF-8' classpath += project.files(android.getBootClasspath().join(File.pathSeparator)) + android.libraryVariants.all { variant -> + if (variant.name == 'release') { + owner.classpath += variant.javaCompile.classpath + } + } + source = android.sourceSets.main.java.srcDirs + exclude '**/R.html', '**/R.*.html', '**/index.html' } task androidJavadocsJar(type: Jar, dependsOn: androidJavadocs) {