params) throws IOException, UpException {
29 |
30 | return super.process(params);
31 |
32 | }
33 |
34 |
35 | public class Params {
36 | /**
37 | * 请求参数
38 | *
39 | * bucket_name string 是 文件所在空间名称
40 | * notify_url string 是 回调通知地址
41 | * tasks string 是 处理任务信息,详见下
42 | * app_name string 是 任务所使用的云处理程序,压缩打包为 compress,解压为 depress
43 | */
44 | public final static String BUCKET_NAME = "bucket_name";
45 | public final static String NOTIFY_URL = "notify_url";
46 | public final static String TASKS = "tasks";
47 | public final static String APP_NAME = "app_name";
48 |
49 |
50 | /**
51 | * 回调通知参数
52 | *
53 | * task_id string 任务对应的 TaskId
54 | * status_code integer 处理结果状态码,200 表示成功处理
55 | * path string 输出文件保存路径
56 | * error string 处理错误信息描述,空字符串表示没有错误
57 | */
58 | public final static String TASK_ID = "task_id";
59 | public final static String STATUS_CODE = "status_code";
60 | public final static String PATH = "path";
61 | public final static String ERROR = "error";
62 |
63 | /**
64 | * 压缩
65 | *
66 | * save_as string 压缩文件保存路径(需要为 zip 压缩文件),如
67 | * sources array 需要被压缩打包的文件或目录路径(空间内相对路径)
68 | * home_dir string 压缩文件内的目录结构可不包含的父目录。默认包含从根开始的全部目录。可选参数
69 | */
70 | public final static String SAVE_AS = "save_as";
71 | public final static String SOURCES = "sources";
72 | public final static String HOME_DIR = "home_dir";
73 |
74 |
75 | /**
76 | * 解压缩
77 | *
78 | * save_as string 压缩文件保存路径(需要为目录),如
79 | * sources string 空间内压缩文件相对路径
80 | */
81 | // public final static String SAVE_AS = "save_as";
82 | // public final static String SOURCES = "sources";
83 |
84 | }
85 | }
86 |
--------------------------------------------------------------------------------
/src/main/java/com/upyun/ConvertHandler.java:
--------------------------------------------------------------------------------
1 | package com.upyun;
2 |
3 |
4 | import java.io.IOException;
5 | import java.util.Map;
6 |
7 | public class ConvertHandler extends AsyncProcessHandler {
8 |
9 |
10 | /**
11 | * 初始化异步文档转换
12 | *
13 | * @param bucketName 空间名称
14 | * @param userName 操作员名称
15 | * @param password 密码,不需要MD5加密
16 | */
17 | public ConvertHandler(String bucketName, String userName, String password) {
18 | super(bucketName, userName, password);
19 | }
20 |
21 | /**
22 | * 发起文档转换请求
23 | *
24 | * @param params 请求参数
25 | * @return 请求结果
26 | * @throws IOException
27 | */
28 | public Result process(Map params) throws IOException, UpException {
29 | return super.process(params);
30 | }
31 |
32 |
33 | public class Params {
34 | /**
35 | * 请求参数
36 | *
37 | * bucket_name string 是 文件所在空间名称
38 | * notify_url string 是 回调通知地址
39 | * tasks string 是 处理任务信息,详见下
40 | * app_name string 是 任务所使用的云处理程序,文件拉取为 spiderman
41 | */
42 | public final static String BUCKET_NAME = "bucket_name";
43 | public final static String NOTIFY_URL = "notify_url";
44 | public final static String TASKS = "tasks";
45 | public final static String APP_NAME = "app_name";
46 |
47 |
48 | /**
49 | * 回调通知参数
50 | *
51 | * task_id string 任务对应的 TaskId
52 | * bucket_name string 文件所在的空间名
53 | * status_code integer 处理结果状态码,200 表示成功处理
54 | * path string 文件保存路径
55 | * error string 处理错误信息描述,空字符串表示没有错误
56 | */
57 | public final static String TASK_ID = "task_id";
58 | // public final static String BUCKET_NAME = "bucket_name";
59 | public final static String STATUS_CODE = "status_code";
60 | public final static String PATH = "path";
61 | public final static String ERROR = "error";
62 |
63 | /**
64 | * 处理参数
65 | *
66 | * source string 是 文档存放的路径,最大支持 10M 文件大小
67 | * save_as string 是 图片保存路径。生成的图片会自动添加 -.png 后缀
68 | * density integer 否 图片的像素密度,范围 [2-200],默认为 100,越大图片越清晰
69 | * width integer 否 图片的宽度,图片大小随宽度等比例缩放,范围 [0-2048],默认自适应
70 | *
71 | */
72 | public final static String SOURCE = "source";
73 | public final static String SAVE_AS = "save_as";
74 | public final static String DENSITY = "density";
75 | public final static String overwrite = "width";
76 |
77 | }
78 | }
79 |
--------------------------------------------------------------------------------
/src/main/java/com/upyun/FormUploader.java:
--------------------------------------------------------------------------------
1 | package com.upyun;
2 |
3 | import java.io.*;
4 | import java.net.HttpURLConnection;
5 | import java.net.MalformedURLException;
6 | import java.net.URL;
7 | import java.security.InvalidKeyException;
8 | import java.security.NoSuchAlgorithmException;
9 | import java.security.SignatureException;
10 | import java.util.Map;
11 |
12 | public class FormUploader {
13 |
14 | // 默认的超时时间:30秒
15 | private int timeout = 30 * 1000;
16 |
17 | //默认过期时间
18 | private int expiration = 1800;
19 |
20 | //默认域名
21 | private String apiDomain = "http://v0.api.upyun.com";
22 | // 空间名
23 | protected String bucketName = null;
24 | // 操作员名
25 | protected String userName = null;
26 | // 操作员密码
27 | protected String password = null;
28 |
29 | public int getTimeout() {
30 | return timeout;
31 | }
32 |
33 | public String getBucketName() {
34 | return bucketName;
35 | }
36 |
37 | public int getExpiration() {
38 | return expiration;
39 | }
40 |
41 | public void setExpiration(int expiration) {
42 | this.expiration = expiration;
43 | }
44 |
45 | public void setBucketName(String bucketName) {
46 | this.bucketName = bucketName;
47 | }
48 |
49 | public void setTimeout(int timeout) {
50 | this.timeout = timeout;
51 | }
52 |
53 | public FormUploader(String bucketName, String userName, String password) {
54 | this.bucketName = bucketName;
55 | this.userName = userName;
56 | this.password = UpYunUtils.md5(password);
57 | }
58 |
59 | /**
60 | * 表单上传方法
61 | *
62 | * @param params 参数组见官网API文档
63 | * @param file 上传文件
64 | * @return 返回结果
65 | */
66 | public Result upload(Map params, File file) throws NoSuchAlgorithmException, SignatureException, InvalidKeyException {
67 |
68 | return upload(params, file, null);
69 | }
70 |
71 | /**
72 | * 表单上传方法
73 | *
74 | * @param params 参数组见官网API文档
75 | * @param datas 上传数组
76 | * @return 返回结果
77 | */
78 | public Result upload(Map params, byte[] datas) throws NoSuchAlgorithmException, SignatureException, InvalidKeyException {
79 |
80 | return upload(params, null, datas);
81 | }
82 |
83 | private Result upload(Map params, File file, byte[] datas) throws NoSuchAlgorithmException, SignatureException, InvalidKeyException {
84 | if (params.get(Params.BUCKET) == null) {
85 | params.put(Params.BUCKET, this.bucketName);
86 | }
87 |
88 | if (params.get(Params.EXPIRATION) == null) {
89 | params.put(Params.EXPIRATION, System.currentTimeMillis() / 1000 + expiration);
90 | }
91 |
92 | String policy = UpYunUtils.getPolicy(params);
93 |
94 | String signature = null;
95 |
96 |
97 | String date = (String) params.get(Params.DATE);
98 | String contentMd5 = (String) params.get(Params.CONTENT_MD5);
99 |
100 | StringBuilder sb = new StringBuilder();
101 | String sp = "&";
102 | sb.append("POST");
103 | sb.append(sp);
104 | sb.append("/" + bucketName);
105 |
106 | if (date != null) {
107 | sb.append(sp);
108 | sb.append(date);
109 | }
110 |
111 | sb.append(sp);
112 | sb.append(policy);
113 |
114 | if (contentMd5 != null) {
115 | sb.append(sp);
116 | sb.append(contentMd5);
117 | }
118 |
119 | String raw = sb.toString().trim();
120 |
121 | byte[] hmac;
122 |
123 | hmac = UpYunUtils.calculateRFC2104HMACRaw(password, raw);
124 |
125 | if (hmac != null) {
126 | signature = Base64Coder.encodeLines(hmac);
127 | }
128 |
129 | System.out.println("sign" + signature);
130 |
131 | URL url = null;
132 | try {
133 | url = new URL(getApiDomain() + "/" + this.bucketName);
134 | } catch (MalformedURLException e) {
135 | throw new RuntimeException("域名错误格式错误");
136 | }
137 |
138 | Result result;
139 | try {
140 | result = postData(file, datas, url, policy, signature.trim());
141 | } catch (IOException e) {
142 | result = new Result();
143 | result.setSucceed(false);
144 | result.setMsg(e.toString());
145 | }
146 |
147 | return result;
148 | }
149 |
150 | private Result postData(File file, byte[] datas, URL url, String policy, String signature) throws IOException {
151 |
152 | String BOUNDARY = "---------------------------12121upyun";
153 |
154 | InputStream is = null;
155 | OutputStream os;
156 | HttpURLConnection conn;
157 |
158 | conn = (HttpURLConnection) url.openConnection();
159 |
160 | // 设置必要参数
161 | conn.setConnectTimeout(timeout);
162 | conn.setRequestMethod("POST");
163 | conn.setUseCaches(false);
164 | conn.setDoOutput(true);
165 | conn.setRequestProperty("Connection", "Keep-Alive");
166 | conn.setRequestProperty("User-Agent", UpYunUtils.VERSION);
167 | conn.setRequestProperty("x-upyun-api-version", "2");
168 | conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
169 | conn.setChunkedStreamingMode(0);
170 |
171 | // 创建链接
172 | conn.connect();
173 |
174 | os = conn.getOutputStream();
175 | os.write(getBoundaryStr("policy", BOUNDARY, policy).getBytes());
176 | // os.write(getBoundaryStr("signature", BOUNDARY, signature).getBytes());
177 | os.write(getBoundaryStr("authorization", BOUNDARY, "UPYUN " + userName + ":" + signature).getBytes());
178 |
179 |
180 | String fileName = file != null ? file.getName() : "null";
181 | os.write(getBoundaryFileStr("file", BOUNDARY, fileName).getBytes());
182 |
183 | byte[] tempData = new byte[4096];
184 | int temp = 0;
185 | if (file != null) {
186 | // 上传文件内容
187 | is = new FileInputStream(file);
188 | while ((temp = is.read(tempData)) != -1) {
189 | os.write(tempData, 0, temp);
190 | }
191 | } else if (datas != null) {
192 | os.write(datas);
193 | }
194 |
195 | os.write("\r\n".getBytes());
196 | os.write(paramsEnd(BOUNDARY).getBytes());
197 |
198 | // 获取返回的信息
199 | Result result = getResult(conn);
200 |
201 | if (os != null) {
202 | os.close();
203 | }
204 | if (is != null) {
205 | is.close();
206 | }
207 | if (conn != null) {
208 | conn.disconnect();
209 | }
210 |
211 | return result;
212 | }
213 |
214 | private String getBoundaryStr(String key, String BOUNDARY, String value) {
215 | StringBuffer strBuf = new StringBuffer();
216 | strBuf.append("\r\n").append("--").append(BOUNDARY).append("\r\n");
217 | strBuf.append("Content-Disposition: form-data; name=\"" + key + "\"\r\n\r\n");
218 | strBuf.append(value);
219 | return strBuf.toString();
220 | }
221 |
222 | private String getBoundaryFileStr(String key, String BOUNDARY, String filename) {
223 | StringBuffer strBuf = new StringBuffer();
224 | strBuf.append("\r\n").append("--").append(BOUNDARY).append("\r\n");
225 | strBuf.append("Content-Disposition: form-data; name=\"file\"; filename=\"" + filename + "\"\r\n\r\n");
226 | // strBuf.append("Content-Type:" + filename + "\r\n\r\n");
227 | return strBuf.toString();
228 | }
229 |
230 | private Result getResult(HttpURLConnection conn) throws IOException {
231 | Result result = new Result();
232 | StringBuilder text = new StringBuilder();
233 |
234 | InputStream is = null;
235 | InputStreamReader sr = null;
236 | BufferedReader br = null;
237 |
238 | int code = conn.getResponseCode();
239 |
240 | result.setCode(code);
241 |
242 | try {
243 | // is = code >= 400 ? conn.getErrorStream() : conn.getInputStream();
244 | is = conn.getInputStream();
245 |
246 | sr = new InputStreamReader(is);
247 | br = new BufferedReader(sr);
248 |
249 | char[] chars = new char[4096];
250 | int length = 0;
251 |
252 | while ((length = br.read(chars)) != -1) {
253 | text.append(chars, 0, length);
254 | }
255 | } finally {
256 | if (br != null) {
257 | br.close();
258 | br = null;
259 | }
260 | if (sr != null) {
261 | sr.close();
262 | sr = null;
263 | }
264 | if (is != null) {
265 | is.close();
266 | is = null;
267 | }
268 | }
269 | if (code == HttpURLConnection.HTTP_OK) {
270 | result.setSucceed(true);
271 | } else {
272 | result.setSucceed(false);
273 | }
274 | result.setMsg(text.toString());
275 | return result;
276 |
277 | }
278 |
279 | //添加结尾数据
280 | private String paramsEnd(String boundary) {
281 | return "--" + boundary + "--" + "\r\n";
282 | }
283 |
284 | /**
285 | * 切换 API 接口的域名接入点
286 | *
287 | * 可选参数:
288 | * 1) UpYun.ED_AUTO(v0.api.upyun.com):默认,根据网络条件自动选择接入点
289 | * 2) UpYun.ED_TELECOM(v1.api.upyun.com):电信接入点
290 | * 3) UpYun.ED_CNC(v2.api.upyun.com):联通网通接入点
291 | * 4) UpYun.ED_CTT(v3.api.upyun.com):移动铁通接入点
292 | *
293 | * @param domain 域名接入点
294 | */
295 | public void setApiDomain(String domain) {
296 | this.apiDomain = domain;
297 | }
298 |
299 | /**
300 | * 查看当前的域名接入点
301 | *
302 | * @return
303 | */
304 | public String getApiDomain() {
305 | return apiDomain;
306 | }
307 | }
308 |
--------------------------------------------------------------------------------
/src/main/java/com/upyun/JigsawHandler.java:
--------------------------------------------------------------------------------
1 | package com.upyun;
2 |
3 |
4 | import java.io.IOException;
5 | import java.util.Map;
6 |
7 | public class JigsawHandler extends AsyncProcessHandler {
8 |
9 |
10 | /**
11 | * 初始化异步拼图
12 | *
13 | * @param bucketName 空间名称
14 | * @param userName 操作员名称
15 | * @param password 密码,不需要MD5加密
16 | */
17 | public JigsawHandler(String bucketName, String userName, String password) {
18 | super(bucketName, userName, password);
19 | }
20 |
21 | /**
22 | * 发起异步拼图请求
23 | *
24 | * @param params 请求参数
25 | * @return 请求结果
26 | * @throws IOException
27 | */
28 | public Result process(Map params) throws IOException, UpException {
29 | return super.process(params);
30 | }
31 |
32 |
33 | public class Params {
34 | /**
35 | * 请求参数
36 | *
37 | * bucket_name string 是 文件所在空间名称
38 | * notify_url string 是 回调通知地址
39 | * tasks string 是 处理任务信息,详见下
40 | * app_name string 是 任务所使用的云处理程序,文件拉取为 spiderman
41 | */
42 | public final static String BUCKET_NAME = "bucket_name";
43 | public final static String NOTIFY_URL = "notify_url";
44 | public final static String TASKS = "tasks";
45 | public final static String APP_NAME = "app_name";
46 |
47 |
48 | /**
49 | * 回调通知参数
50 | *
51 | * task_id string 任务对应的 TaskId
52 | * bucket_name string 文件所在的空间名
53 | * status_code integer 处理结果状态码,200 表示成功处理
54 | * path string 文件保存路径
55 | * error string 处理错误信息描述,空字符串表示没有错误
56 | */
57 | public final static String TASK_ID = "task_id";
58 | // public final static String BUCKET_NAME = "bucket_name";
59 | public final static String STATUS_CODE = "status_code";
60 | public final static String PATH = "path";
61 | public final static String ERROR = "error";
62 |
63 | /**
64 | * 处理参数
65 | *
66 | * image_matrix [][]string 是 需要拼接的图片路径和拼接方式
67 | * save_as string 是 拼接后图片的保存路径
68 | * x-gmkerl-thumb string 否 对拼接后的图片进行图片处理
69 | *
70 | */
71 | public final static String IMAGE_MATRIX = "image_matrix";
72 | public final static String SAVE_AS = "save_as";
73 | public final static String X_GMKERL_THUMB = "x-gmkerl-thumb";
74 | public final static String overwrite = "width";
75 |
76 | }
77 | }
78 |
--------------------------------------------------------------------------------
/src/main/java/com/upyun/MediaHandler.java:
--------------------------------------------------------------------------------
1 | package com.upyun;
2 |
3 | import java.io.IOException;
4 | import java.io.InputStream;
5 | import java.net.HttpURLConnection;
6 | import java.net.URL;
7 | import java.util.Map;
8 |
9 |
10 | public class MediaHandler extends AsyncProcessHandler {
11 |
12 |
13 | /**
14 | * 初始化影视频处理接口
15 | *
16 | * @param bucketName 空间名称
17 | * @param userName 操作员名称
18 | * @param password 密码,不需要MD5加密
19 | */
20 | public MediaHandler(String bucketName, String userName, String password) {
21 | super(bucketName, userName, password);
22 | }
23 |
24 |
25 | /**
26 | * 发起异步音视频处理请求
27 | *
28 | * @param params 请求参数
29 | * @return 请求结果
30 | * @throws IOException
31 | */
32 | public Result process(Map params) throws IOException, UpException {
33 | return super.process(params);
34 | }
35 |
36 |
37 | /**
38 | * 发起查询处理进度请求
39 | *
40 | * @param params 请求参数
41 | * @return 请求结果
42 | * @throws IOException
43 | */
44 | public Result getStatus(Map params) throws IOException, UpException {
45 | InputStream is = null;
46 | HttpURLConnection conn;
47 |
48 | StringBuilder sb = new StringBuilder("/status");
49 | sb.append("?");
50 | for (Map.Entry mapping : params.entrySet()) {
51 | sb.append(mapping.getKey() + "=" + mapping.getValue().toString() + "&");
52 | }
53 |
54 | String uriPath = sb.toString().substring(0, sb.length() - 1);
55 |
56 | URL url = new URL(HOST + uriPath);
57 |
58 | conn = (HttpURLConnection) url.openConnection();
59 |
60 | // 设置必要参数
61 | conn.setConnectTimeout(timeout);
62 | conn.setRequestMethod("GET");
63 | conn.setUseCaches(false);
64 | conn.setDoOutput(true);
65 | conn.setRequestProperty("Connection", "Keep-Alive");
66 | conn.setRequestProperty("User-Agent", UpYunUtils.VERSION);
67 |
68 | String date = UpYunUtils.getGMTDate();
69 |
70 | // 设置时间
71 | conn.setRequestProperty(DATE, date);
72 | // 设置签名
73 | conn.setRequestProperty(AUTHORIZATION,
74 | UpYunUtils.sign("GET", date, uriPath, userName, password, null));
75 |
76 | // 创建链接
77 | conn.connect();
78 |
79 | // 获取返回的信息
80 | Result result = getResp(conn);
81 |
82 | if (is != null) {
83 | is.close();
84 | }
85 | if (conn != null) {
86 | conn.disconnect();
87 | }
88 | return result;
89 | }
90 |
91 | /**
92 | * 发起查询处理结果请求
93 | *
94 | * @param params 请求参数
95 | * @return 请求结果
96 | * @throws IOException
97 | */
98 | public Result getResult(Map params) throws IOException, UpException {
99 | InputStream is = null;
100 | HttpURLConnection conn;
101 |
102 | StringBuilder sb = new StringBuilder("/result");
103 | sb.append("?");
104 | for (Map.Entry mapping : params.entrySet()) {
105 | sb.append(mapping.getKey() + "=" + mapping.getValue().toString() + "&");
106 | }
107 | String uriPath = sb.toString().substring(0, sb.length() - 1);
108 |
109 | URL url = new URL(HOST + uriPath);
110 |
111 | conn = (HttpURLConnection) url.openConnection();
112 |
113 | // 设置必要参数
114 | conn.setConnectTimeout(timeout);
115 | conn.setRequestMethod("GET");
116 | conn.setUseCaches(false);
117 | conn.setDoOutput(true);
118 | conn.setRequestProperty("Connection", "Keep-Alive");
119 | conn.setRequestProperty("User-Agent", UpYunUtils.VERSION);
120 |
121 | String date = UpYunUtils.getGMTDate();
122 |
123 | // 设置时间
124 | conn.setRequestProperty(DATE, date);
125 | // 设置签名
126 | conn.setRequestProperty(AUTHORIZATION,
127 | UpYunUtils.sign("GET", date, uriPath, userName, password, null));
128 |
129 | // 创建链接
130 | conn.connect();
131 |
132 | // 获取返回的信息
133 | Result result = getResp(conn);
134 |
135 | if (is != null) {
136 | is.close();
137 | }
138 | if (conn != null) {
139 | conn.disconnect();
140 | }
141 | return result;
142 | }
143 |
144 |
145 | public class Params {
146 | /**
147 | * 请求参数
148 | *
149 | * bucket_name string 是 文件所在服务名称(空间名称)
150 | * notify_url string 是 回调通知地址
151 | * source string 是 待处理文件路径
152 | * tasks string 是 处理任务信息,详见下
153 | * accept string 是 必须指定为 json
154 | */
155 | public final static String BUCKET_NAME = "bucket_name";
156 | public final static String NOTIFY_URL = "notify_url";
157 | public final static String SOURCE = "source";
158 | public final static String TASKS = "tasks";
159 | public final static String ACCEPT = "accept";
160 |
161 |
162 | /**
163 | * 回调通知参数
164 | *
165 | * status_code integer 处理结果状态码,200 表示成功处理
166 | * path array 输出文件保存路径
167 | * description string 处理结果描述
168 | * task_id string 任务对应的 task_id
169 | * info string 视频文件的元数据信息。经过 base64 处理过之后的 JSON 字符串,仅当 type 为 video且 return_info 为 true 时返回
170 | * signature string 回调验证签名,用户端程序可以通过校验签名,判断回调通知的合法性
171 | * timestamp integer 服务器回调此信息时的时间戳
172 | */
173 | public final static String STATUS_CODE = "status_code";
174 | public final static String PATH = "path";
175 | public final static String DESCRIPTION = "description";
176 | public final static String TASK_ID = "task_id";
177 | public final static String INFO = "info";
178 | public final static String SIGNATURE = "signature";
179 | public final static String TIMESTAMP = "timestamp";
180 |
181 | /**
182 | * 查询参数
183 | *
184 | * task_ids string 任务 id 以 , 作为分隔符,最多 20 个
185 | */
186 | public final static String TASK_IDS = "task_ids";
187 |
188 | /**
189 | * 处理通用参数
190 | *
191 | * type string 音视频处理类型。不同的处理任务对应不同的 type,详见下方各处理任务说明
192 | * save_as string 输出文件保存路径(同一个空间下),如果没有指定,系统自动生成在同空间同目录下
193 | * return_info boolean 是否返回 JSON 格式元数据,默认 false。支持 type 值为 video 功能
194 | * avopts string 音视频处理参数, 格式为 /key/value/key/value/...
195 | */
196 | public final static String TYPE = "type";
197 | public final static String SAVE_AS = "save_as";
198 | public final static String RETURN_INFO = "return_info";
199 | public final static String AVOPTS = "avopts";
200 |
201 | }
202 | }
203 |
--------------------------------------------------------------------------------
/src/main/java/com/upyun/ParallelUploader.java:
--------------------------------------------------------------------------------
1 | package com.upyun;
2 |
3 | import okhttp3.Request;
4 | import okhttp3.RequestBody;
5 | import okhttp3.Response;
6 |
7 | import java.io.IOException;
8 | import java.util.Map;
9 | import java.util.concurrent.ExecutorService;
10 | import java.util.concurrent.Executors;
11 | import java.util.concurrent.Future;
12 | import java.util.concurrent.TimeUnit;
13 |
14 | public class ParallelUploader extends BaseUploader {
15 |
16 | private volatile int blockProgress;
17 |
18 | public void setParallel(int parallel) {
19 | this.parallel = parallel;
20 | }
21 |
22 | //并行式断点并行数
23 | private int parallel = 4;
24 |
25 | //分块上传状态 1 成功 2 上传中 3 上传失败
26 | private int[] status;
27 |
28 | /**
29 | * 断点续传
30 | *
31 | * @return 是否上传成功
32 | * @throws IOException
33 | */
34 | public boolean resume() throws IOException, UpException {
35 | this.paused = false;
36 | return startUpload();
37 |
38 | }
39 |
40 | /**
41 | * 断点续传
42 | *
43 | * @param uuid 上传任务 uuid
44 | * @param status 分块上传状态
45 | * @return
46 | * @throws IOException
47 | */
48 | public boolean resume(String uuid, int[] status) throws IOException, UpException {
49 |
50 | this.uuid = uuid;
51 | this.status = status;
52 |
53 | if (uuid == null || status == null || status.length != totalBlock - 2) {
54 | throw new UpException("uuid or status is wrong, please restart!");
55 | } else {
56 | this.paused = false;
57 | return startUpload();
58 | }
59 | }
60 |
61 |
62 | /**
63 | * 初始化 SerialUploader
64 | *
65 | * @param bucketName 空间名称
66 | * @param userName 操作员名称
67 | * @param password 密码,需要MD5加密
68 | * @return SerialUploader object
69 | */
70 | public ParallelUploader(String bucketName, String userName, String password) {
71 | super(bucketName, userName, password);
72 | }
73 |
74 | public void setTimeout(int timeout) {
75 | this.timeout = timeout;
76 | }
77 |
78 | /**
79 | * 开始上传
80 | *
81 | * @param filePath 本地上传文件路径
82 | * @param uploadPath 上传服务器路径
83 | * @param params 通用上传参数(见 rest api 文档)
84 | * @return 是否上传成功
85 | * @throws IOException
86 | */
87 | public boolean upload(String filePath, String uploadPath, Map params) throws IOException, UpException {
88 |
89 | init(filePath, uploadPath, params);
90 |
91 | if (status == null || status.length != totalBlock - 2 || uuid == null) {
92 | status = new int[totalBlock - 2];
93 | }
94 |
95 | this.params.put(X_UPYUN_MULTI_DISORDER, "true");
96 |
97 | return startUpload();
98 | }
99 |
100 | /**
101 | * 获取分块状态
102 | *
103 | * @return
104 | */
105 | public int[] getStatus() {
106 | return status;
107 | }
108 |
109 | /**
110 | * 设置分块状态
111 | *
112 | * @param status
113 | */
114 | public void setStatus(int[] status) {
115 | this.status = status;
116 | }
117 |
118 | boolean processUpload() throws IOException, UpException {
119 |
120 | blockProgress = 0;
121 |
122 | ExecutorService uploadExecutor = Executors.newFixedThreadPool(parallel);
123 |
124 | for (int i = 0; i < totalBlock - 2; i++) {
125 |
126 | Future future = uploadExecutor.submit(uploadBlock(i));
127 |
128 | try {
129 | future.get();
130 | } catch (Exception e) {
131 | uploadExecutor.shutdown();
132 | if (randomAccessFile != null) {
133 | randomAccessFile.close();
134 | randomAccessFile = null;
135 | }
136 | throw new UpException(e.getMessage());
137 | }
138 | }
139 |
140 | uploadExecutor.shutdown();
141 |
142 | try {//等待直到所有任务完成
143 | uploadExecutor.awaitTermination(Long.MAX_VALUE, TimeUnit.MINUTES);
144 | } catch (InterruptedException e) {
145 | e.printStackTrace();
146 | }
147 |
148 | return completeUpload();
149 | }
150 |
151 | private Runnable uploadBlock(final int index) {
152 | return new Runnable() {
153 | public void run() {
154 |
155 | try {
156 | if (paused) {
157 | throw new UpException("upload paused");
158 | }
159 | if (status[index] == 1) {
160 | if (onProgressListener != null) {
161 | onProgressListener.onProgress(blockProgress + 2, totalBlock);
162 | }
163 | blockProgress++;
164 | return;
165 | } else if (status[index] == 2) {
166 | return;
167 | }
168 |
169 | status[index] = 2;
170 |
171 | byte[] data = readBlockByIndex(index);
172 |
173 | RequestBody requestBody = RequestBody.create(null, data);
174 |
175 | String date = UpYunUtils.getGMTDate();
176 |
177 | String md5 = null;
178 |
179 | if (checkMD5) {
180 | md5 = UpYunUtils.md5(data);
181 | }
182 |
183 | String sign = UpYunUtils.sign("PUT", date, uri, userName, password, md5).trim();
184 |
185 | Request.Builder builder = new Request.Builder()
186 | .url(url)
187 | .header(DATE, date)
188 | .header(AUTHORIZATION, sign)
189 | .header(X_UPYUN_MULTI_STAGE, "upload")
190 | .header(X_UPYUN_MULTI_UUID, uuid)
191 | .header(X_UPYUN_PART_ID, index + "")
192 | .header("User-Agent", UpYunUtils.VERSION)
193 | .put(requestBody);
194 |
195 | if (md5 != null) {
196 | builder.header(CONTENT_MD5, md5);
197 | }
198 |
199 | Response response = uploadRequest(builder);
200 |
201 | uuid = response.header(X_UPYUN_MULTI_UUID, "");
202 | status[index] = 1;
203 | } catch (Exception e) {
204 | status[index] = 3;
205 | throw new RuntimeException(e.getMessage());
206 | }
207 | }
208 | };
209 |
210 | }
211 |
212 | private Response uploadRequest(Request.Builder builder) {
213 |
214 | try {
215 | Response response = mClient.newCall(builder.build()).execute();
216 | if (!response.isSuccessful()) {
217 | int x_error_code = Integer.parseInt(response.header("X-Error-Code", "-1"));
218 | if (x_error_code == 40011061 || x_error_code == 40011059) {
219 | uuid = null;
220 | }
221 | throw new RuntimeException(response.body().string());
222 | } else {
223 | if (onProgressListener != null) {
224 | onProgressListener.onProgress(blockProgress + 2, totalBlock);
225 | }
226 | blockProgress++;
227 | }
228 | return response;
229 |
230 | } catch (IOException e) {
231 | throw new RuntimeException(e.toString());
232 | }
233 | }
234 |
235 | boolean completeUpload() throws IOException, UpException {
236 | completeRequest();
237 | status = null;
238 | uuid = null;
239 | return true;
240 | }
241 | }
242 |
--------------------------------------------------------------------------------
/src/main/java/com/upyun/Params.java:
--------------------------------------------------------------------------------
1 | package com.upyun;
2 |
3 | public class Params {
4 | /**
5 | * bucket 是 保存所上传的文件的 UPYUN 空间名
6 | * save-key 是 保存路径,如: '/path/to/file.ext',可用占位符 [注 1]
7 | * expiration 是 请求的过期时间,UNIX UTC 时间戳(秒)
8 | * allow-file-type 否 允许上传的文件扩展名,以 , 分隔。如 jpg,jpeg,png
9 | * content-length-range 否 文件大小限制,格式:min,max,单位:字节,如 102400,1024000,表示允许上传 100Kb~1Mb 的文件
10 | * content-md5 否 所上传的文件的 MD5 校验值,UPYUN 根据此来校验文件上传是否正确
11 | * content-secret 否 文件访问密钥 [注 2]
12 | * content-type 否 UPYUN 默认根据扩展名判断,手动指定可提高精确性。如 image/jpeg
13 | * image-width-range 否 图片宽度限制,格式:min,max,单位:像素,如 0,1024,允许上传宽度为 0~1024px 之间
14 | * image-height-range 否 图片高度限制,格式:min,max,单位:像素,如 0,1024,允许上传高度在 0~1024px 之间
15 | * notify-url 否 异步通知 URL,见 通知规则
16 | * return-url 否 同步通知 URL,见 通知规则
17 | * x-gmkerl-thumb 否 图片处理参数,见 上传作图
18 | * x-gmkerl-type 否 get_meta(获取图片信息)或 get_theme_color(主题色提取)
19 | * x-gmkerl-extract-color-count 否 主题色提取颜色数量,默认 256
20 | * x-gmkerl-extract-format 否 主题色提取格式,默认 hex
21 | * apps 否 json 格式的异步处理任务列表。见 异步处理任务
22 | * ext-param 否 额外参数,UTF-8 编码,并小于 255 个字符
23 | *
24 | *
25 | * 老作图参数:
26 | * x-gmkerl-thumbnail 否 缩略图版本名称,仅支持图片类空间,可搭配其他 x-gmkerl-* 参数使用 [注 3]
27 | * x-gmkerl-type 否 缩略类型 [注 4]
28 | * x-gmkerl-value 否 缩略类型对应的参数值 [注 4]
29 | * x-gmkerl-quality 否 默认 95缩略图压缩质量
30 | * x-gmkerl-unsharp 否 默认锐化(true)是否进行锐化处理
31 | * x-gmkerl-rotate 否 图片旋转(顺时针),可选:auto,90,180,270 之一
32 | * x-gmkerl-crop 否 图片裁剪,格式:x,y,width,height,均需为正整型
33 | * x-gmkerl-exif-switch 否 是否保留 exif 信息,仅在搭配 x-gmkerl-crop,x-gmkerl-type,x-gmkerl-thumbnail 时有效。
34 | *
35 | */
36 | //必选参数
37 | public final static String BUCKET = "bucket";
38 | public final static String SAVE_KEY = "save-key";
39 | public final static String EXPIRATION = "expiration";
40 | //可选参数
41 | public final static String DATE = "date";
42 | public final static String CONTENT_MD5 = "content-md5";
43 | public final static String ALLOW_FILE_TYPE = "allow-file-type";
44 | public final static String CONTENT_LENGTH_RANGE = "content-length-range";
45 | public final static String CONTENT_SECRET = "content-secret";
46 | public final static String CONTENT_TYPE = "content-type";
47 | public final static String IMAGE_WIDTH_RANGE = "image-width-range";
48 | public final static String IMAGE_HEIGHT_RANGE = "image-height-range";
49 | public final static String NOTIFY_URL = "notify-url";
50 | public final static String RETURN_URL = "return-url";
51 | public final static String X_GMKERL_THUMB = "x-gmkerl-thumb";
52 | public final static String x_gmkerl_type = "x-gmkerl-type";
53 | public final static String X_GMKERL_EXTRACT_COLOR_COUNT = "x-gmkerl-extract-color-count";
54 | public final static String X_GMKERL_EXTRACT_FORMAT = "x-gmkerl-extract-format";
55 | public final static String APPS = "apps";
56 | public final static String EXT_PARAM = "ext-param";
57 |
58 | //老作图参数
59 | public final static String X_GMKERL_THUMBNAIL = "x-gmkerl-thumbnail";
60 | public final static String X_GMKERL_TYPE = "x-gmkerl-type";
61 | public final static String X_GMKERL_VALUE = "x-gmkerl-value";
62 | public final static String X_GMKERL_QUALITY = "x-gmkerl-quality";
63 | public final static String X_GMKERL_UNSHARP = "x-gmkerl-unsharp";
64 | public final static String X_GMKERL_ROTATE = "x-gmkerl-rotate";
65 | public final static String X_GMKERL_CROP = "x-gmkerl-crop";
66 | public final static String X_GMKERL_EXIF_SWITCH = "x-gmkerl-exif-switch";
67 |
68 | }
69 |
--------------------------------------------------------------------------------
/src/main/java/com/upyun/PullingHandler.java:
--------------------------------------------------------------------------------
1 | package com.upyun;
2 |
3 |
4 | import java.io.IOException;
5 | import java.util.Map;
6 |
7 | public class PullingHandler extends AsyncProcessHandler {
8 |
9 |
10 | /**
11 | * 初始化异步文件拉取接口
12 | *
13 | * @param bucketName 空间名称
14 | * @param userName 操作员名称
15 | * @param password 密码,不需要MD5加密
16 | */
17 | public PullingHandler(String bucketName, String userName, String password) {
18 | super(bucketName, userName, password);
19 | }
20 |
21 | /**
22 | * 发起异步文件拉取请求
23 | *
24 | * @param params 请求参数
25 | * @return 请求结果
26 | * @throws IOException
27 | */
28 | public Result process(Map params) throws IOException, UpException {
29 | return super.process(params);
30 | }
31 |
32 |
33 | public class Params {
34 | /**
35 | * 请求参数
36 | *
37 | * bucket_name string 是 文件所在空间名称
38 | * notify_url string 是 回调通知地址
39 | * tasks string 是 处理任务信息,详见下
40 | * app_name string 是 任务所使用的云处理程序,文件拉取为 spiderman
41 | */
42 | public final static String BUCKET_NAME = "bucket_name";
43 | public final static String NOTIFY_URL = "notify_url";
44 | public final static String TASKS = "tasks";
45 | public final static String APP_NAME = "app_name";
46 |
47 |
48 | /**
49 | * 回调通知参数
50 | *
51 | * task_id string 任务对应的 TaskId
52 | * bucket_name string 文件所在的空间名
53 | * status_code integer 处理结果状态码,200 表示成功处理
54 | * path string 文件保存路径
55 | * error string 处理错误信息描述,空字符串表示没有错误
56 | */
57 | public final static String TASK_ID = "task_id";
58 | // public final static String BUCKET_NAME = "bucket_name";
59 | public final static String STATUS_CODE = "status_code";
60 | public final static String PATH = "path";
61 | public final static String ERROR = "error";
62 |
63 | /**
64 | * 处理参数
65 | *
66 | * url string 需要拉取文件的 url 地址,如 http://www.upyun.com/index.html
67 | * x-gmkerl-thumb string 图片处理参数,见 上传作图
68 | * random bool 是否追加随机数,默认 true
69 | * overwrite bool 是否覆盖,默认 false
70 | * save_as string 文件存放路径,必填项, 如 /site/index.html
71 | */
72 | public final static String URL = "url";
73 | public final static String X_GMKERL_THUMB = "x-gmkerl-thumb";
74 | public final static String RANDOM = "random";
75 | public final static String OVERWRITE = "overwrite";
76 | public final static String SAVE_AS = "save_as";
77 |
78 | }
79 | }
80 |
--------------------------------------------------------------------------------
/src/main/java/com/upyun/RestManager.java:
--------------------------------------------------------------------------------
1 | package com.upyun;
2 |
3 | import okhttp3.*;
4 | import okhttp3.internal.Util;
5 | import okio.BufferedSink;
6 | import okio.Okio;
7 | import okio.Source;
8 |
9 | import java.io.File;
10 | import java.io.IOException;
11 | import java.io.InputStream;
12 | import java.net.Proxy;
13 | import java.util.HashMap;
14 | import java.util.Map;
15 | import java.util.concurrent.TimeUnit;
16 |
17 | public class RestManager {
18 |
19 | /**
20 | * 路径的分割符
21 | */
22 | private final String SEPARATOR = "/";
23 |
24 | private final String AUTHORIZATION = "Authorization";
25 | private final String DATE = "Date";
26 |
27 |
28 | private final String METHOD_HEAD = "HEAD";
29 | private final String METHOD_GET = "GET";
30 | private final String METHOD_PUT = "PUT";
31 | private final String METHOD_POST = "POST";
32 | private final String METHOD_DELETE = "DELETE";
33 |
34 | private OkHttpClient mClient;
35 |
36 | /**
37 | * 根据网络条件自动选择接入点:v0.api.upyun.com
38 | */
39 | public static final String ED_AUTO = "https://v0.api.upyun.com";
40 | /**
41 | * 电信接入点:v1.api.upyun.com
42 | */
43 | public static final String ED_TELECOM = "https://v1.api.upyun.com";
44 | /**
45 | * 联通网通接入点:v2.api.upyun.com
46 | */
47 | public static final String ED_CNC = "https:/v2.api.upyun.com";
48 | /**
49 | * 移动铁通接入点:v3.api.upyun.com
50 | */
51 | public static final String ED_CTT = "https://v3.api.upyun.com";
52 |
53 | // 默认不开启debug模式
54 | public boolean debug = false;
55 | // 默认的超时时间:30秒
56 | private int timeout = 30;
57 | // 默认为自动识别接入点
58 | private String apiDomain = ED_AUTO;
59 | // 待上传文件的 Content-MD5 值
60 | private String contentMD5 = null;
61 | // 待上传文件的"访问密钥"
62 | private String fileSecret = null;
63 | // 空间名
64 | protected String bucketName = null;
65 | // 操作员名
66 | protected String userName = null;
67 | // 操作员密码
68 | protected String password = null;
69 |
70 | /**
71 | * 初始化 UpYun 存储接口
72 | *
73 | * @param bucketName 空间名称
74 | * @param userName 操作员名称
75 | * @param password 密码,不需要MD5加密
76 | * @return UpYun object
77 | */
78 | public RestManager(String bucketName, String userName, String password) {
79 | this.bucketName = bucketName;
80 | this.userName = userName;
81 | this.password = UpYunUtils.md5(password);
82 | this.mClient = new OkHttpClient.Builder()
83 | .connectTimeout(timeout, TimeUnit.SECONDS)
84 | .readTimeout(timeout, TimeUnit.SECONDS)
85 | .writeTimeout(timeout, TimeUnit.SECONDS)
86 | .build();
87 | }
88 |
89 | /**
90 | * 切换 API 接口的域名接入点
91 | *
92 | * 可选参数:
93 | * 1) UpYun.ED_AUTO(v0.api.upyun.com):默认,根据网络条件自动选择接入点
94 | * 2) UpYun.ED_TELECOM(v1.api.upyun.com):电信接入点
95 | * 3) UpYun.ED_CNC(v2.api.upyun.com):联通网通接入点
96 | * 4) UpYun.ED_CTT(v3.api.upyun.com):移动铁通接入点
97 | *
98 | * @param domain 域名接入点
99 | */
100 | public void setApiDomain(String domain) {
101 | this.apiDomain = domain;
102 | }
103 |
104 | /**
105 | * 查看当前的域名接入点
106 | *
107 | * @return
108 | */
109 | public String getApiDomain() {
110 | return apiDomain;
111 | }
112 |
113 | /**
114 | * 设置连接超时时间,默认为30秒
115 | *
116 | * @param second 秒数,60即为一分钟超时
117 | */
118 | public void setTimeout(int second) {
119 | this.timeout = second;
120 | this.mClient = mClient.newBuilder()
121 | .connectTimeout(timeout, TimeUnit.SECONDS)
122 | .readTimeout(timeout, TimeUnit.SECONDS)
123 | .writeTimeout(timeout, TimeUnit.SECONDS)
124 | .build();
125 | }
126 |
127 | /**
128 | * 设置代理
129 | */
130 | public void setProxy(Proxy proxy) {
131 | this.mClient = mClient.newBuilder()
132 | .proxy(proxy)
133 | .build();
134 | }
135 |
136 | /**
137 | * 查看当前的超时时间
138 | *
139 | * @return
140 | */
141 | public int getTimeout() {
142 | return timeout;
143 | }
144 |
145 | /**
146 | * 获取当前SDK的版本号
147 | *
148 | * @return SDK版本号
149 | */
150 | public String version() {
151 | return UpYunUtils.VERSION;
152 | }
153 |
154 |
155 | /**
156 | * 上传文件
157 | *
158 | * @param filePath 文件路径(包含文件名)
159 | * @param data 文件内容
160 | * @return response
161 | */
162 | public Response writeFile(String filePath, byte[] data, Map params) throws IOException, UpException {
163 | return request(METHOD_PUT, filePath, RequestBody.create(null, data), params);
164 | }
165 |
166 | /**
167 | * 上传文件
168 | *
169 | * @param filePath 文件路径(包含文件名)
170 | * @param file 待上传的文件
171 | * @param params 额外参数
172 | * @return response
173 | * @throws IOException
174 | */
175 | public Response writeFile(String filePath, File file, Map params) throws IOException, UpException {
176 | return request(METHOD_PUT, filePath, RequestBody.create(null, file), params);
177 | }
178 |
179 | /**
180 | * 上传文件
181 | *
182 | * @param filePath 文件路径(包含文件名)
183 | * @param inputStream 待上传的 inputStream
184 | * @param params 额外参数
185 | * @return response
186 | * @throws IOException
187 | */
188 | public Response writeFile(String filePath, InputStream inputStream, Map params) throws IOException, UpException {
189 | return request(METHOD_PUT, filePath, create(null, inputStream), params);
190 | }
191 |
192 | /**
193 | * 复制文件
194 | *
195 | * @param path 目标路径
196 | * @param sourcePath 原路径
197 | * @return
198 | * @throws IOException
199 | * @throws UpException
200 | */
201 | public Response copyFile(String path, String sourcePath, Map params) throws IOException, UpException {
202 | if (params == null) {
203 | params = new HashMap();
204 | }
205 | params.put(PARAMS.X_UPYUN_COPY_SOURCE.getValue(), sourcePath);
206 | return request(METHOD_PUT, path, RequestBody.create(null, ""), params);
207 | }
208 |
209 | /**
210 | * 移动文件
211 | *
212 | * @param path 目标路径
213 | * @param sourcePath 原路径
214 | * @return
215 | * @throws IOException
216 | * @throws UpException
217 | */
218 | public Response moveFile(String path, String sourcePath, Map params) throws IOException, UpException {
219 | if (params == null) {
220 | params = new HashMap();
221 | }
222 | params.put(PARAMS.X_UPYUN_MOVE_SOURCE.getValue(), sourcePath);
223 | return request(METHOD_PUT, path, RequestBody.create(null, ""), params);
224 | }
225 |
226 |
227 | /**
228 | * 读取文件
229 | *
230 | * @param filePath 文件路径(包含文件名)
231 | * @return 文件内容 或 null
232 | */
233 | public Response readFile(String filePath) throws IOException, UpException {
234 | return request(METHOD_GET, filePath, null, null);
235 | }
236 |
237 |
238 | /**
239 | * 删除文件
240 | *
241 | * @param filePath 文件路径(包含文件名)
242 | * @param params 额外参数
243 | * @return response
244 | */
245 | public Response deleteFile(String filePath, Map params) throws IOException, UpException {
246 | return request(METHOD_DELETE, filePath, null, params);
247 | }
248 |
249 | /**
250 | * 创建目录
251 | *
252 | * @param filePath 目录路径
253 | * @return response
254 | */
255 | public Response mkDir(String filePath) throws IOException, UpException {
256 | Map params = new HashMap();
257 | params.put(PARAMS.MAKE_DIR.getValue(), "true");
258 | return request(METHOD_POST, filePath, RequestBody.create(null, ""), params);
259 | }
260 |
261 | /**
262 | * 删除目录
263 | *
264 | * @param filePath 目录路径
265 | * @return response
266 | */
267 | public Response rmDir(String filePath) throws IOException, UpException {
268 | return request(METHOD_DELETE, filePath, null, null);
269 | }
270 |
271 | /**
272 | * 获取文件信息
273 | *
274 | * @param filePath 文件路径(包含文件名)
275 | * @return 文件信息 或 null
276 | */
277 | public Response getFileInfo(String filePath) throws IOException, UpException {
278 | return request(METHOD_HEAD, filePath, null, null);
279 | }
280 |
281 |
282 | /**
283 | * 读取目录列表
284 | *
285 | * @param path 目录路径
286 | * @param params 分页参数
287 | * @return response
288 | */
289 | public Response readDirIter(String path, Map params) throws IOException, UpException {
290 | return request(METHOD_GET, path, null, params);
291 | }
292 |
293 | /**
294 | * 获取服务使用量
295 | *
296 | * @return response
297 | */
298 | public Response getBucketUsage() throws IOException, UpException {
299 | return request(METHOD_GET, "/?usage", null, null);
300 | }
301 |
302 | private RequestBody create(final MediaType mediaType, final InputStream inputStream) {
303 | return new RequestBody() {
304 | @Override
305 | public MediaType contentType() {
306 | return mediaType;
307 | }
308 |
309 | @Override
310 | public long contentLength() {
311 | try {
312 | return inputStream.available();
313 | } catch (IOException e) {
314 | return 0;
315 | }
316 | }
317 |
318 | public void writeTo(BufferedSink bufferedSink) throws IOException {
319 | Source source = null;
320 | try {
321 | source = Okio.source(inputStream);
322 | bufferedSink.writeAll(source);
323 | } finally {
324 | Util.closeQuietly(source);
325 | }
326 | }
327 | };
328 | }
329 |
330 | /**
331 | * 判断字符串是否为空
332 | * getTextgetText
333 | *
334 | * @param str
335 | * @return 是否为空
336 | */
337 | private boolean isEmpty(String str) {
338 | return str == null || str.length() == 0;
339 | }
340 |
341 | /**
342 | * 格式化路径参数,去除前后的空格并确保以"/"开头,最后添加"/空间名"
343 | *
344 | * 最终构成的格式:"/空间名/文件路径"
345 | *
346 | * @param path 目录路径或文件路径
347 | * @return 格式化后的路径
348 | */
349 | private String formatPath(String path) {
350 |
351 | if (!isEmpty(path)) {
352 |
353 | // 去除前后的空格
354 | path = path.trim();
355 |
356 | // 确保路径以"/"开头
357 | if (!path.startsWith(SEPARATOR)) {
358 | return SEPARATOR + bucketName + SEPARATOR + path;
359 | }
360 | }
361 |
362 | return SEPARATOR + bucketName + path;
363 | }
364 |
365 |
366 | private Response request(String method, String filePath, RequestBody body, Map params) throws UpException, IOException {
367 |
368 | String date = UpYunUtils.getGMTDate();
369 |
370 | // 获取链接
371 | String url = apiDomain + UpYunUtils.formatPath(bucketName, filePath);
372 |
373 | String sign = UpYunUtils.sign(method, date, HttpUrl.get(url).encodedPath(), userName, password, params == null ? null : params.get(PARAMS.CONTENT_MD5.getValue()));
374 |
375 | Request.Builder builder = new Request.Builder()
376 | .url(url)
377 | .header(DATE, date)
378 | .header(AUTHORIZATION, sign)
379 | .header("User-Agent", UpYunUtils.VERSION)
380 | .method(method, body);
381 |
382 |
383 | if (params != null) {
384 | for (Map.Entry entry : params.entrySet()) {
385 | builder.header(entry.getKey(), entry.getValue());
386 | }
387 | }
388 | return mClient.newCall(builder.build()).execute();
389 | }
390 |
391 | /**
392 | * 其他额外参数的键值和参数值
393 | */
394 | public enum PARAMS {
395 |
396 | /**
397 | * 创建目录
398 | *
399 | * 说明:SDK内部使用
400 | */
401 | MAKE_DIR("folder"),
402 |
403 | /**
404 | * 复制文件
405 | *
406 | * 说明:SDK内部使用
407 | */
408 | X_UPYUN_COPY_SOURCE("X-Upyun-Copy-Source"),
409 |
410 | /**
411 | * 移动文件
412 | *
413 | * 说明:SDK内部使用
414 | */
415 | X_UPYUN_MOVE_SOURCE("X-Upyun-Move-Source"),
416 |
417 | /**
418 | * 分页参数
419 | * 分页开始位置,通过x-upyun-list-iter 响应头返回,所以第一次请求不需要填写
420 | */
421 | X_LIST_ITER("x-list-iter"),
422 |
423 | /**
424 | * 分页参数
425 | * 获取的文件数量,默认 100,最大 10000
426 | */
427 | X_LIST_LIMIT("x-list-limit"),
428 |
429 | /**
430 | * 分页参数
431 | * asc 或 desc,按文件名升序或降序排列。默认 asc
432 | */
433 | X_LIST_ORDER("x-list-order"),
434 |
435 | /**
436 | * 分页参数
437 | * application/json,返回json格式
438 | */
439 | ACCEPT("Accept"),
440 |
441 | /**
442 | * 删除参数
443 | * true 表示进行异步删除,不设置表示同步删除(默认)
444 | */
445 | X_UPYUN_ASYNC("x-upyun-async"),
446 |
447 | /**
448 | * 上传参数
449 | * 上传文件的 MD5 值,如果请求中文件太大计算 MD5 不方便,可以为空
450 | */
451 | CONTENT_MD5("Content-MD5"),
452 | /**
453 | * 上传参数
454 | * 文件类型,默认使用文件扩展名作为文件类型
455 | */
456 | CONTENT_TYPE("Content-Type"),
457 | /**
458 | * 文件密钥,用于保护文件,防止文件被直接访问
459 | */
460 | CONTENT_SECRET("Content-Secret"),
461 | /**
462 | * 文件元信息
463 | */
464 | X_UPYUN_META_X("x-upyun-meta-x"),
465 | /**
466 | * 文件元信息, 指定文件的生存时间,单位天
467 | */
468 | X_UPYUN_META_TTL("x-upyun-meta-ttl"),
469 | /**
470 | * 图片预处理参数
471 | */
472 | X_GMKERL_THUMB("x-gmkerl-thumb"),
473 | /**
474 | * 处理源文件的元信息
475 | */
476 | X_UPYUN_METADATA_DIRECTIVE("X-Upyun-Metadata-Directive"),
477 | /**
478 | * 获取文件信息参数
479 | */
480 | X_UPYUN_FILE_TYPE("x-upyun-file-type"),
481 | X_UPYUN_FILE_SIZE("x-upyun-file-size"),
482 | X_UPYUN_FILE_DATE("x-upyun-file-date");
483 |
484 | private final String value;
485 |
486 | private PARAMS(String val) {
487 | value = val;
488 | }
489 |
490 | public String getValue() {
491 | return value;
492 | }
493 | }
494 | }
--------------------------------------------------------------------------------
/src/main/java/com/upyun/Result.java:
--------------------------------------------------------------------------------
1 | package com.upyun;
2 |
3 | public class Result {
4 | public boolean isSucceed() {
5 | return succeed;
6 | }
7 |
8 | public void setSucceed(boolean succeed) {
9 | this.succeed = succeed;
10 | }
11 |
12 | public int getCode() {
13 | return code;
14 | }
15 |
16 | public void setCode(int code) {
17 | this.code = code;
18 | }
19 |
20 | public String getMsg() {
21 | return msg;
22 | }
23 |
24 | public void setMsg(String msg) {
25 | this.msg = msg;
26 | }
27 |
28 | private boolean succeed;
29 | private int code;
30 | private String msg;
31 |
32 | @Override
33 | public String toString() {
34 | return "Result{" +
35 | "succeed=" + succeed +
36 | ", code=" + code +
37 | ", msg='" + msg + '\'' +
38 | '}';
39 | }
40 | }
41 |
42 |
--------------------------------------------------------------------------------
/src/main/java/com/upyun/SerialUploader.java:
--------------------------------------------------------------------------------
1 | package com.upyun;
2 |
3 | import okhttp3.Request;
4 | import okhttp3.RequestBody;
5 | import okhttp3.Response;
6 |
7 | import java.io.IOException;
8 | import java.util.Map;
9 |
10 | public class SerialUploader extends BaseUploader {
11 |
12 | private int nextPartIndex;
13 |
14 | /**
15 | * 断点续传
16 | *
17 | * @return 是否上传成功
18 | * @throws IOException
19 | */
20 | public boolean resume() throws IOException, UpException {
21 | this.paused = false;
22 | return startUpload();
23 | }
24 |
25 | /**
26 | * 断点续传
27 | *
28 | * @param uuid 上传任务 uuid
29 | * @param nextPartIndex 下一个上传分块 index
30 | * @return
31 | * @throws IOException
32 | */
33 | public boolean resume(String uuid, int nextPartIndex) throws IOException, UpException {
34 |
35 | this.uuid = uuid;
36 | this.nextPartIndex = nextPartIndex;
37 |
38 | if (uuid == null) {
39 | throw new UpException("uuid is null, please restart!");
40 | } else {
41 | this.paused = false;
42 | return startUpload();
43 | }
44 | }
45 |
46 | /**
47 | * 初始化 SerialUploader
48 | *
49 | * @param bucketName 空间名称
50 | * @param userName 操作员名称
51 | * @param password 密码,不需要MD5加密
52 | * @return SerialUploader object
53 | */
54 | public SerialUploader(String bucketName, String userName, String password) {
55 | super(bucketName, userName, password);
56 | }
57 |
58 | /**
59 | * 开始上传
60 | *
61 | * @param filePath 本地上传文件路径
62 | * @param uploadPath 上传服务器路径
63 | * @param params 通用上传参数(见 rest api 文档)
64 | * @return 是否上传成功
65 | * @throws IOException
66 | */
67 | public boolean upload(String filePath, String uploadPath, Map params) throws IOException, UpException {
68 | init(filePath, uploadPath, params);
69 | return startUpload();
70 | }
71 |
72 | /**
73 | * 获取下一个上传分块 index
74 | *
75 | * @return index
76 | */
77 | public int getNextPartIndex() {
78 | return nextPartIndex;
79 | }
80 |
81 | public void setUuid(String uuid) {
82 | this.uuid = uuid;
83 | }
84 |
85 | public void setNextPartIndex(int nextPartIndex) {
86 | this.nextPartIndex = nextPartIndex;
87 | }
88 |
89 | boolean processUpload() throws IOException, UpException {
90 | byte[] data;
91 |
92 | while (nextPartIndex >= 0) {
93 |
94 | if (paused) {
95 | throw new UpException("upload paused");
96 | }
97 |
98 | data = readBlockByIndex(nextPartIndex);
99 |
100 | RequestBody requestBody = RequestBody.create(null, data);
101 |
102 | String date = UpYunUtils.getGMTDate();
103 |
104 | String md5 = null;
105 |
106 | if (checkMD5) {
107 | md5 = UpYunUtils.md5(data);
108 | }
109 |
110 | String sign = UpYunUtils.sign("PUT", date, uri, userName, password, md5);
111 |
112 | Request.Builder builder = new Request.Builder()
113 | .url(url)
114 | .header(DATE, date)
115 | .header(AUTHORIZATION, sign.trim())
116 | .header(X_UPYUN_MULTI_STAGE, "upload")
117 | .header(X_UPYUN_MULTI_UUID, uuid)
118 | .header(X_UPYUN_PART_ID, nextPartIndex + "")
119 | .header("User-Agent", UpYunUtils.VERSION)
120 | .put(requestBody);
121 |
122 | if (md5 != null) {
123 | builder.header(CONTENT_MD5, md5);
124 | }
125 |
126 | if (onProgressListener != null) {
127 | onProgressListener.onProgress(nextPartIndex + 2, totalBlock);
128 | }
129 | callProcessRequest(builder.build());
130 | }
131 |
132 | return completeUpload();
133 | }
134 |
135 | boolean completeUpload() throws IOException, UpException {
136 | completeRequest();
137 | uuid = null;
138 | return true;
139 | }
140 |
141 | private void callProcessRequest(Request request) throws IOException, UpException {
142 |
143 | Response response = mClient.newCall(request).execute();
144 | if (!response.isSuccessful()) {
145 | int x_error_code = Integer.parseInt(response.header("X-Error-Code", "-1"));
146 | if (x_error_code != 40011061 && x_error_code != 40011059) {
147 | if (randomAccessFile != null) {
148 | randomAccessFile.close();
149 | randomAccessFile = null;
150 | }
151 | uuid = null;
152 | throw new UpException(response.body().string());
153 | } else {
154 | nextPartIndex = Integer.parseInt(response.header(X_UPYUN_NEXT_PART_ID, "-2"));
155 | return;
156 | }
157 | }
158 |
159 | uuid = response.header(X_UPYUN_MULTI_UUID, "");
160 | nextPartIndex = Integer.parseInt(response.header(X_UPYUN_NEXT_PART_ID, "-2"));
161 | }
162 |
163 | }
164 |
--------------------------------------------------------------------------------
/src/main/java/com/upyun/UpAPIException.java:
--------------------------------------------------------------------------------
1 | package com.upyun;
2 |
3 | public class UpAPIException extends UpException {
4 | public int statusCode;
5 |
6 | public UpAPIException(int statusCode, String msg) {
7 | super("api error code:" + statusCode + "; msg:" + msg);
8 | this.statusCode = statusCode;
9 | }
10 |
11 | }
12 |
--------------------------------------------------------------------------------
/src/main/java/com/upyun/UpException.java:
--------------------------------------------------------------------------------
1 | package com.upyun;
2 |
3 | public class UpException extends Exception {
4 | public UpException(String msg) {
5 | super(msg);
6 | }
7 | }
8 |
--------------------------------------------------------------------------------
/src/main/java/com/upyun/UpYunUtils.java:
--------------------------------------------------------------------------------
1 | package com.upyun;
2 |
3 | import org.json.JSONObject;
4 |
5 | import javax.crypto.Mac;
6 | import javax.crypto.spec.SecretKeySpec;
7 | import java.io.*;
8 | import java.security.*;
9 | import java.text.SimpleDateFormat;
10 | import java.util.Date;
11 | import java.util.Locale;
12 | import java.util.Map;
13 | import java.util.TimeZone;
14 |
15 | public class UpYunUtils {
16 |
17 | public static final String VERSION = "upyun-java-sdk/4.2.2";
18 | private static final String SEPARATOR = "/";
19 |
20 | /**
21 | * 计算policy
22 | *
23 | * @param paramMap
24 | * @return
25 | */
26 | public static String getPolicy(Map paramMap) {
27 |
28 | JSONObject obj = new JSONObject(paramMap);
29 | return Base64Coder.encodeString(obj.toString());
30 | }
31 |
32 | /**
33 | * 计算签名
34 | *
35 | * @param policy
36 | * @param secretKey
37 | * @return
38 | */
39 | public static String getSignature(String policy,
40 | String secretKey) {
41 | return md5(policy + "&" + secretKey);
42 | }
43 |
44 | /**
45 | * 计算md5Ø
46 | *
47 | * @param string
48 | * @return
49 | */
50 | public static String md5(String string) {
51 | byte[] hash;
52 | try {
53 | hash = MessageDigest.getInstance("MD5").digest(string.getBytes("UTF-8"));
54 | } catch (UnsupportedEncodingException e) {
55 | throw new RuntimeException("UTF-8 is unsupported", e);
56 | } catch (NoSuchAlgorithmException e) {
57 | throw new RuntimeException("MessageDigest不支持MD5Util", e);
58 | }
59 | StringBuilder hex = new StringBuilder(hash.length * 2);
60 | for (byte b : hash) {
61 | if ((b & 0xFF) < 0x10) hex.append("0");
62 | hex.append(Integer.toHexString(b & 0xFF));
63 | }
64 | return hex.toString();
65 | }
66 |
67 | public static String md5(File file, int blockSize) {
68 | try {
69 | MessageDigest messageDigest = MessageDigest.getInstance("MD5");
70 | FileInputStream in = new FileInputStream(file);
71 | byte[] buffer = new byte[blockSize];
72 | int length;
73 | while ((length = in.read(buffer)) > 0) {
74 | messageDigest.update(buffer, 0, length);
75 | }
76 | byte[] hash = messageDigest.digest();
77 | StringBuilder hex = new StringBuilder(hash.length * 2);
78 | for (byte b : hash) {
79 | if ((b & 0xFF) < 0x10) hex.append("0");
80 | hex.append(Integer.toHexString(b & 0xFF));
81 | }
82 | return hex.toString();
83 | } catch (FileNotFoundException e) {
84 | throw new RuntimeException("file not found", e);
85 | } catch (IOException e) {
86 | throw new RuntimeException("file get md5 failed", e);
87 | } catch (NoSuchAlgorithmException e) {
88 | throw new RuntimeException("MessageDigest不支持MD5Util", e);
89 | }
90 | }
91 |
92 | public static String md5(byte[] bytes) {
93 | byte[] hash;
94 | try {
95 | hash = MessageDigest.getInstance("MD5").digest(bytes);
96 | } catch (NoSuchAlgorithmException e) {
97 | throw new RuntimeException("MessageDigest不支持MD5Util", e);
98 | }
99 | StringBuilder hex = new StringBuilder(hash.length * 2);
100 | for (byte b : hash) {
101 | if ((b & 0xFF) < 0x10) hex.append("0");
102 | hex.append(Integer.toHexString(b & 0xFF));
103 | }
104 | return hex.toString();
105 | }
106 |
107 | private static final String HMAC_SHA1_ALGORITHM = "HmacSHA1";
108 |
109 | public static String sign(String method, String date, String path, String userName, String password, String md5) throws UpException {
110 |
111 | StringBuilder sb = new StringBuilder();
112 | String sp = "&";
113 | sb.append(method);
114 | sb.append(sp);
115 | sb.append(path);
116 |
117 | sb.append(sp);
118 | sb.append(date);
119 |
120 | if (md5 != null && md5.length() > 0) {
121 | sb.append(sp);
122 | sb.append(md5);
123 | }
124 | String raw = sb.toString().trim();
125 | byte[] hmac = null;
126 | try {
127 | hmac = calculateRFC2104HMACRaw(password, raw);
128 | } catch (Exception e) {
129 | throw new UpException("calculate SHA1 wrong.");
130 | }
131 |
132 | if (hmac != null) {
133 | return "UPYUN " + userName + ":" + Base64Coder.encodeLines(hmac).trim();
134 | }
135 |
136 | return null;
137 | }
138 |
139 | public static byte[] calculateRFC2104HMACRaw(String key, String data)
140 | throws SignatureException, NoSuchAlgorithmException, InvalidKeyException {
141 | byte[] keyBytes = key.getBytes();
142 | SecretKeySpec signingKey = new SecretKeySpec(keyBytes, HMAC_SHA1_ALGORITHM);
143 |
144 | // Get an hmac_sha1 Mac instance and initialize with the signing key
145 | Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM);
146 | mac.init(signingKey);
147 | // Compute the hmac on input data bytes
148 | return mac.doFinal(data.getBytes());
149 | }
150 |
151 | private static boolean isEmpty(String str) {
152 | return str == null || str.length() == 0;
153 | }
154 |
155 | public static String formatPath(String bucketName, String path) {
156 |
157 | if (!isEmpty(path)) {
158 |
159 | // 去除前后的空格
160 | path = path.trim();
161 |
162 | // 确保路径以"/"开头
163 | if (!path.startsWith(SEPARATOR)) {
164 | return SEPARATOR + bucketName + SEPARATOR + path;
165 | }
166 | }
167 |
168 | return SEPARATOR + bucketName + path;
169 | }
170 |
171 | /**
172 | * 获取 GMT 格式时间戳
173 | *
174 | * @return GMT 格式时间戳
175 | */
176 | public static String getGMTDate() {
177 | SimpleDateFormat formater = new SimpleDateFormat(
178 | "EEE, dd MMM yyyy HH:mm:ss 'GMT'", Locale.US);
179 | formater.setTimeZone(TimeZone.getTimeZone("GMT"));
180 | return formater.format(new Date());
181 | }
182 | }
183 |
--------------------------------------------------------------------------------
/src/main/java/demo/CompressDemo.java:
--------------------------------------------------------------------------------
1 | package demo;
2 |
3 | import com.upyun.CompressHandler;
4 | import com.upyun.MediaHandler;
5 | import com.upyun.Result;
6 | import com.upyun.UpException;
7 | import org.json.JSONArray;
8 | import org.json.JSONObject;
9 |
10 | import java.io.IOException;
11 | import java.util.Arrays;
12 | import java.util.HashMap;
13 | import java.util.Map;
14 |
15 | public class CompressDemo {
16 |
17 | // 运行前先设置好以下三个参数
18 | private static final String BUCKET_NAME = "空间名称";
19 | private static final String OPERATOR_NAME = "操作员名称";
20 | private static final String OPERATOR_PWD = "操作员密码";
21 |
22 |
23 | public static void main(String[] args) {
24 | testCompress();
25 | // testDecompress();
26 | }
27 |
28 | private static void testDecompress() {
29 |
30 | CompressHandler handler = new CompressHandler(BUCKET_NAME, OPERATOR_NAME, OPERATOR_PWD);
31 |
32 | //初始化参数组 Map
33 | Map paramsMap = new HashMap();
34 |
35 | //空间名
36 | paramsMap.put(CompressHandler.Params.BUCKET_NAME, BUCKET_NAME);
37 | //回调地址
38 | paramsMap.put(CompressHandler.Params.NOTIFY_URL, "http://httpbin.org/post");
39 | //选择处理任务
40 | paramsMap.put(CompressHandler.Params.APP_NAME, "depress");
41 |
42 | //已json格式生成任务信息
43 | JSONArray array = new JSONArray();
44 | JSONObject json = new JSONObject();
45 |
46 | //添加处理参数
47 | json.put(CompressHandler.Params.SOURCES, "/result/compress/a.zip");
48 | json.put(CompressHandler.Params.SAVE_AS, "/result/depress");
49 |
50 | JSONObject json2 = new JSONObject();
51 |
52 | //添加处理参数
53 | json2.put(CompressHandler.Params.SOURCES, "/result/compress/b.zip");
54 | json2.put(CompressHandler.Params.SAVE_AS, "/result/depress2");
55 |
56 | array.put(json2);
57 | array.put(json);
58 |
59 | //添加任务信息
60 | paramsMap.put(CompressHandler.Params.TASKS, array);
61 |
62 | try {
63 | Result result = handler.process(paramsMap);
64 | System.out.println(result);
65 | if (result.isSucceed()) {
66 |
67 | String[] ids = handler.getTaskId(result.getMsg());
68 | System.out.println(Arrays.toString(ids));
69 |
70 | }
71 | } catch (IOException e) {
72 | e.printStackTrace();
73 | } catch (UpException e) {
74 | e.printStackTrace();
75 | }
76 |
77 | }
78 |
79 | private static void testCompress() {
80 |
81 | CompressHandler handler = new CompressHandler(BUCKET_NAME, OPERATOR_NAME, OPERATOR_PWD);
82 |
83 | //初始化参数组 Map
84 | Map paramsMap = new HashMap();
85 |
86 | //空间名
87 | paramsMap.put(CompressHandler.Params.BUCKET_NAME, BUCKET_NAME);
88 | //回调地址
89 | paramsMap.put(CompressHandler.Params.NOTIFY_URL, "http://httpbin.org/post");
90 | //选择处理任务
91 | paramsMap.put(CompressHandler.Params.APP_NAME, "compress");
92 |
93 | //已json格式生成任务信息
94 | JSONArray array = new JSONArray();
95 | JSONObject json = new JSONObject();
96 |
97 | JSONArray array2 = new JSONArray();
98 | array2.put("/a/b/c/sample.jpeg");
99 | array2.put("/a/b/c/rotate.jpg");
100 |
101 | //添加处理参数
102 | json.put(CompressHandler.Params.SOURCES, array2);
103 | json.put(CompressHandler.Params.SAVE_AS, "/result/compress/a.zip");
104 | json.put(CompressHandler.Params.HOME_DIR, "a/b/c");
105 |
106 | JSONObject json2 = new JSONObject();
107 |
108 | //添加处理参数
109 | json2.put(CompressHandler.Params.SOURCES, array2);
110 | json2.put(CompressHandler.Params.SAVE_AS, "/result/compress/b.zip");
111 | json2.put(CompressHandler.Params.HOME_DIR, "a/b/c");
112 |
113 | array.put(json2);
114 | array.put(json);
115 |
116 | //添加任务信息
117 | paramsMap.put(CompressHandler.Params.TASKS, array);
118 |
119 | try {
120 | Result result = handler.process(paramsMap);
121 | System.out.println(result);
122 | if (result.isSucceed()) {
123 |
124 | String[] ids = handler.getTaskId(result.getMsg());
125 | System.out.println(Arrays.toString(ids));
126 |
127 | }
128 | } catch (IOException e) {
129 | e.printStackTrace();
130 | } catch (UpException e) {
131 | e.printStackTrace();
132 | }
133 |
134 | }
135 | }
136 |
--------------------------------------------------------------------------------
/src/main/java/demo/ConvertDemo.java:
--------------------------------------------------------------------------------
1 | package demo;
2 |
3 | import com.upyun.ConvertHandler;
4 | import com.upyun.Result;
5 | import com.upyun.UpException;
6 | import org.json.JSONArray;
7 | import org.json.JSONObject;
8 |
9 | import java.io.IOException;
10 | import java.util.HashMap;
11 | import java.util.Map;
12 |
13 | import static org.junit.Assert.assertNotNull;
14 | import static org.junit.Assert.assertTrue;
15 |
16 | public class ConvertDemo {
17 |
18 | // 运行前先设置好以下三个参数
19 | private static final String BUCKET_NAME = "空间名称";
20 | private static final String OPERATOR_NAME = "操作员名称";
21 | private static final String OPERATOR_PWD = "操作员密码";
22 |
23 |
24 | public static void main(String[] args) {
25 | testConvert();
26 | }
27 |
28 | private static void testConvert() {
29 |
30 | ConvertHandler handler = new ConvertHandler(BUCKET_NAME, OPERATOR_NAME, OPERATOR_PWD);
31 |
32 | //初始化参数组 Map
33 | Map paramsMap = new HashMap();
34 |
35 | paramsMap.put(ConvertHandler.Params.BUCKET_NAME, BUCKET_NAME);
36 | paramsMap.put(ConvertHandler.Params.NOTIFY_URL, "http://httpbin.org/post");
37 | paramsMap.put(ConvertHandler.Params.APP_NAME, "uconvert");
38 |
39 | //已json格式生成任务信息
40 | JSONArray array = new JSONArray();
41 | JSONObject json = new JSONObject();
42 |
43 | //添加处理参数
44 | json.put(ConvertHandler.Params.SOURCE, "/test_ppt.pptx");
45 | json.put(ConvertHandler.Params.SAVE_AS, "/result/convert/convert");
46 |
47 | array.put(json);
48 |
49 | //添加任务信息
50 | paramsMap.put(ConvertHandler.Params.TASKS, array);
51 |
52 | try {
53 | Result result = handler.process(paramsMap);
54 |
55 | assertNotNull(result);
56 | assertTrue(result.isSucceed());
57 | assertNotNull(result.getMsg());
58 |
59 | String[] ids = handler.getTaskId(result.getMsg());
60 | assertNotNull(ids);
61 |
62 | } catch (IOException e) {
63 | e.printStackTrace();
64 | } catch (UpException e) {
65 | e.printStackTrace();
66 | }
67 |
68 |
69 | }
70 | }
71 |
--------------------------------------------------------------------------------
/src/main/java/demo/FileBucketDemo.java:
--------------------------------------------------------------------------------
1 | package demo;
2 |
3 | import com.UpYun;
4 | import com.upyun.UpException;
5 |
6 | import java.io.File;
7 | import java.io.IOException;
8 | import java.util.HashMap;
9 | import java.util.List;
10 | import java.util.Map;
11 |
12 | import static org.junit.Assert.assertTrue;
13 |
14 | /**
15 | * 文件类空间的demo
16 | */
17 | public class FileBucketDemo {
18 |
19 | // 运行前先设置好以下三个参数
20 | private static final String BUCKET_NAME = "空间名称";
21 | private static final String OPERATOR_NAME = "操作员名称";
22 | private static final String OPERATOR_PWD = "操作员密码";
23 |
24 | /**
25 | * 根目录
26 | */
27 | private static final String DIR_ROOT = "/";
28 | /**
29 | * 多级目录
30 | */
31 | private static final String DIR_MORE = "/1/2/3/";
32 | /**
33 | * 目录名
34 | */
35 | private static final String FOLDER_NAME = "tmp";
36 | /**
37 | * 上传到upyun的文件名
38 | */
39 | private static final String FILE_NAME = "test.txt";
40 |
41 | /**
42 | * 本地待上传的测试文件
43 | */
44 | private static final String SAMPLE_TXT_FILE = System
45 | .getProperty("user.dir") + "/test.txt";
46 |
47 | private static UpYun upyun = null;
48 |
49 | static {
50 | File txtFile = new File(SAMPLE_TXT_FILE);
51 |
52 | if (!txtFile.isFile()) {
53 | System.out.println("本地待上传的测试文件不存在!");
54 | }
55 | }
56 |
57 | public static void main(String[] args) throws IOException, UpException {
58 |
59 | // 初始化空间
60 | upyun = new UpYun(BUCKET_NAME, OPERATOR_NAME, OPERATOR_PWD);
61 |
62 | // ****** 可选设置 begin ******
63 |
64 | // 切换 API 接口的域名接入点,默认为自动识别接入点
65 | // upyun.setApiDomain(UpYun.ED_AUTO);
66 |
67 | // 设置连接超时时间,默认为30秒
68 | // upyun.setTimeout(60);
69 |
70 | // 设置是否开启debug模式,默认不开启
71 | upyun.setDebug(true);
72 |
73 | // ****** 可选设置 end ******
74 |
75 | // 1.创建目录,有两种形式
76 | testMkDir();
77 |
78 | // 2.上传文件,图片空间的文件上传请参考 PicBucketDemo.java
79 | testWriteFile();
80 | // 3.获取文件信息
81 | testGetFileInfo();
82 |
83 | // 4.读取目录
84 | testReadDir();
85 |
86 | // 5.获取空间占用大小
87 | testGetBucketUsage();
88 |
89 | // 6.获取某个目录的空间占用大小
90 | testGetFolderUsage();
91 |
92 | // 7.读取文件/下载文件
93 | testReadFile();
94 |
95 | // 8.删除文件
96 | testDeleteFile();
97 |
98 | // 9.删除目录
99 | testRmDir();
100 |
101 | // 10.复制文件
102 | testCopyFile();
103 |
104 | // 9.移动文件
105 | testMoveFile();
106 | }
107 |
108 | /**
109 | * 获取空间占用大小
110 | */
111 | public static void testGetBucketUsage() throws IOException, UpException {
112 |
113 | long usage = upyun.getBucketUsage();
114 |
115 | System.out.println("空间总使用量:" + usage + "B");
116 | System.out.println();
117 | }
118 |
119 | /**
120 | * 获取某个目录的空间占用大小
121 | */
122 | public static void testGetFolderUsage() throws IOException, UpException {
123 |
124 | // 带查询的目录,如 "/" 或 "/tmp"
125 | String dirPath = DIR_ROOT;
126 |
127 | long usage = upyun.getFolderUsage(dirPath);
128 |
129 | System.out.println("'" + dirPath + "'目录占用量: " + usage + "B");
130 | System.out.println();
131 | }
132 |
133 | /**
134 | * 上传文件
135 | *
136 | * @throws IOException
137 | */
138 | public static void testWriteFile() throws IOException, UpException {
139 |
140 | // 要上传的纯文字内容
141 | String content = "test content";
142 |
143 | // 要传到upyun后的文件路径
144 | String filePath = DIR_ROOT + FILE_NAME;
145 | // 要传到upyun后的文件路径:多级目录
146 | String filePath2 = DIR_MORE + FILE_NAME;
147 |
148 | /*
149 | * 上传方法1:文本内容直接上传
150 | */
151 | boolean result1 = upyun.writeFile(filePath, content);
152 | System.out.println("1.上传 " + filePath + isSuccess(result1));
153 |
154 | /*
155 | * 上传方法2:文本内容直接上传,可自动创建父级目录(最多10级)
156 | */
157 | boolean result2 = upyun.writeFile(filePath2, content, true);
158 | System.out.println("2.上传 " + filePath2 + isSuccess(result2));
159 |
160 | /*
161 | * 上传方法3:采用数据流模式上传文件(节省内存),可自动创建父级目录(最多10级)
162 | */
163 | File file = new File(SAMPLE_TXT_FILE);
164 | boolean result3 = upyun.writeFile(filePath, file, true);
165 | System.out.println("3.上传 " + filePath + isSuccess(result3));
166 |
167 | /*
168 | * 上传方法4:对待上传的文件设置 MD5 值,确保上传到 Upyun 的文件的完整性和正确性
169 | */
170 | File file4 = new File(SAMPLE_TXT_FILE);
171 | // 设置待上传文件的 Content-MD5 值
172 | // 如果又拍云服务端收到的文件MD5值与用户设置的不一致,将回报 406 NotAcceptable 错误
173 | upyun.setContentMD5(UpYun.md5(file4));
174 |
175 | boolean result4 = upyun.writeFile(filePath, file4, true);
176 | System.out.println("4.上传 " + filePath + isSuccess(result4));
177 | System.out.println();
178 |
179 | }
180 |
181 | /**
182 | * 获取文件信息
183 | */
184 | public static void testGetFileInfo() throws IOException, UpException {
185 |
186 | // upyun空间下存在的文件的路径
187 | String filePath = DIR_ROOT + FILE_NAME;
188 |
189 | System.out.println(filePath + " 的文件信息:" + upyun.getFileInfo(filePath));
190 | System.out.println();
191 | }
192 |
193 | /**
194 | * 读取文件/下载文件
195 | *
196 | * @throws IOException
197 | */
198 | public static void testReadFile() throws IOException, UpException {
199 |
200 | // upyun空间下存在的文件的路径
201 | String filePath = DIR_ROOT + FILE_NAME;
202 |
203 | /*
204 | * 方法1:直接读取文本内容
205 | */
206 | String datas = upyun.readFile(filePath);
207 | System.out.println(filePath + " 的文件内容:" + datas);
208 |
209 | /*
210 | * 方法2:下载文件,采用数据流模式下载文件(节省内存)
211 | */
212 | // 要写入的本地临时文件
213 | File file = File.createTempFile("upyunTempFile_", "");
214 |
215 | // 把upyun空间下的文件下载到本地的临时文件
216 | boolean result = upyun.readFile(filePath, file);
217 | System.out.println(filePath + " 下载" + isSuccess(result) + ",保存到 "
218 | + file.getAbsolutePath());
219 | System.out.println();
220 | }
221 |
222 | /**
223 | * 删除文件
224 | */
225 | public static void testDeleteFile() throws IOException, UpException {
226 |
227 | // upyun空间下存在的文件的路径
228 | String filePath = DIR_ROOT + FILE_NAME;
229 |
230 | // 删除文件
231 | boolean result = upyun.deleteFile(filePath, null);
232 |
233 | System.out.println(filePath + " 删除" + isSuccess(result));
234 | System.out.println();
235 | }
236 |
237 | /**
238 | * 创建目录
239 | */
240 | public static void testMkDir() throws IOException, UpException {
241 |
242 | // 方法1:创建一级目录
243 | String dir1 = DIR_ROOT + FOLDER_NAME;
244 |
245 | boolean result1 = upyun.mkDir(dir1);
246 | System.out.println("创建目录:" + dir1 + isSuccess(result1));
247 |
248 | // 方法2:创建多级目录,自动创建父级目录(最多10级)
249 | String dir2 = DIR_MORE + FOLDER_NAME;
250 |
251 | boolean result2 = upyun.mkDir(dir2, true);
252 | System.out.println("自动创建多级目录:" + dir2 + isSuccess(result2));
253 | System.out.println();
254 | }
255 |
256 | /**
257 | * 读取目录下的文件列表
258 | */
259 | public static void testReadDir() throws IOException, UpException {
260 |
261 | // 参数可以换成其他目录路径
262 | String dirPath = DIR_ROOT;
263 |
264 | Map params = new HashMap();
265 |
266 | params.put(UpYun.PARAMS.KEY_X_LIST_LIMIT.getValue(), "10");
267 |
268 | // 读取目录列表,将返回 List 或 NULL
269 | // List items = upyun.readDir(dirPath, params);
270 | //
271 | // if (null == items) {
272 | // System.out.println("'" + dirPath + "'目录下没有文件。");
273 | //
274 | // } else {
275 | //
276 | //
277 | // for (int i = 0; i < items.size(); i++) {
278 | // System.out.println(items.get(i));
279 | // }
280 | //
281 | // System.out.println("'" + dirPath + "'目录总共有 " + items.size()
282 | // + " 个文件。");
283 | // }
284 |
285 | UpYun.FolderItemIter folderItemIter = upyun.readDirIter(dirPath, params);
286 | System.out.println(folderItemIter);
287 |
288 | String json = upyun.readDirJson(dirPath, params);
289 | System.out.println(json);
290 |
291 | System.out.println();
292 | }
293 |
294 | /**
295 | * 删除目录
296 | */
297 | public static void testRmDir() throws IOException, UpException {
298 |
299 | // 带删除的目录必须存在,并且目录下已不存在任何文件或子目录
300 | String dirPath = DIR_MORE + FOLDER_NAME;
301 |
302 | boolean result = upyun.rmDir(dirPath);
303 |
304 | System.out.println("删除目录:" + dirPath + isSuccess(result));
305 | System.out.println();
306 | }
307 |
308 |
309 | /**
310 | * 复制文件
311 | *
312 | * @throws IOException
313 | * @throws UpException
314 | */
315 | public static void testCopyFile() throws IOException, UpException {
316 | String filePath = DIR_ROOT + FILE_NAME;
317 |
318 | boolean result = upyun.copyFile("/test.aa", "/" + BUCKET_NAME + filePath);
319 |
320 | assertTrue(result);
321 | }
322 |
323 | /**
324 | * 移动文件
325 | *
326 | * @throws IOException
327 | * @throws UpException
328 | */
329 | public static void testMoveFile() throws IOException, UpException {
330 | String filePath = DIR_ROOT + FILE_NAME;
331 |
332 | boolean result = upyun.moveFile("/test.aa", "/" + BUCKET_NAME + filePath);
333 |
334 | assertTrue(result);
335 | }
336 |
337 | private static String isSuccess(boolean result) {
338 | return result ? " 成功" : " 失败";
339 | }
340 | }
341 |
--------------------------------------------------------------------------------
/src/main/java/demo/FormUploadDemo.java:
--------------------------------------------------------------------------------
1 | package demo;
2 |
3 | import com.upyun.*;
4 | import org.json.JSONArray;
5 | import org.json.JSONObject;
6 |
7 | import java.io.*;
8 | import java.security.InvalidKeyException;
9 | import java.security.NoSuchAlgorithmException;
10 | import java.security.SignatureException;
11 | import java.util.HashMap;
12 | import java.util.Map;
13 |
14 | public class FormUploadDemo {
15 | // 运行前先设置好以下三个参数
16 | private static final String BUCKET_NAME = "formtest";
17 | private static final String OPERATOR_NAME = "one";
18 | private static final String OPERATOR_PWD = "qwertyuiop";
19 |
20 |
21 | //上传测试文件
22 | private static final String SAMPLE_PIC_FILE = System.getProperty("user.dir") + "/sample.jpeg";
23 |
24 |
25 | private static File file = new File(SAMPLE_PIC_FILE);
26 | //保存路径 必须设置该参数
27 | private static String savePath = "/uploads/{year}{mon}{day}/{random32}{.suffix}";
28 |
29 | public static void main(String[] args) throws NoSuchAlgorithmException, SignatureException, InvalidKeyException {
30 |
31 | testWriteFile();
32 | testWatermark();
33 | testSync();
34 | testAsync();
35 | }
36 |
37 | /**
38 | * 测试上传文件
39 | */
40 | private static void testWriteFile() throws NoSuchAlgorithmException, SignatureException, InvalidKeyException {
41 | final Map paramsMap = new HashMap();
42 | paramsMap.put(Params.SAVE_KEY, savePath);
43 |
44 | FormUploader uploader = new FormUploader(BUCKET_NAME, OPERATOR_NAME, OPERATOR_PWD);
45 | Result result = uploader.upload(paramsMap, file);
46 | System.out.println(result);
47 |
48 | System.out.println(uploader.upload(paramsMap, "test1".getBytes()));
49 | }
50 |
51 | /**
52 | * 测试上传图片添加水印
53 | */
54 |
55 | private static void testWatermark() throws NoSuchAlgorithmException, SignatureException, InvalidKeyException {
56 | FormUploader uploader = new FormUploader(BUCKET_NAME, OPERATOR_NAME, OPERATOR_PWD);
57 |
58 | final Map paramsMap = new HashMap();
59 | paramsMap.put(Params.SAVE_KEY, savePath);
60 | paramsMap.put(Params.X_GMKERL_THUMB, "/watermark/text/5L2g5aW977yB");
61 |
62 | System.out.println(uploader.upload(paramsMap, file));
63 | }
64 |
65 | /**
66 | * 测试上传同步作图
67 | */
68 |
69 | private static void testSync() throws NoSuchAlgorithmException, SignatureException, InvalidKeyException {
70 | //初始化uploader
71 | FormUploader uploader = new FormUploader(BUCKET_NAME, OPERATOR_NAME, OPERATOR_PWD);
72 |
73 | //初始化参数组 Map
74 | final Map paramsMap = new HashMap();
75 |
76 | //添加 SAVE_KEY 参数
77 | paramsMap.put(Params.SAVE_KEY, savePath);
78 |
79 | //添加同步上传作图参数 X_GMKERL_THUMB
80 | paramsMap.put(Params.X_GMKERL_THUMB, "/fw/300/unsharp/true/quality/80/format/png");
81 |
82 | //打印结果
83 | System.out.println(uploader.upload(paramsMap, file));
84 | }
85 |
86 | /**
87 | * 测试上传异步作图
88 | */
89 |
90 | private static void testAsync() throws NoSuchAlgorithmException, SignatureException, InvalidKeyException {
91 | //uploader
92 | FormUploader uploader = new FormUploader(BUCKET_NAME, OPERATOR_NAME, OPERATOR_PWD);
93 |
94 | //初始化参数组 Map
95 | final Map paramsMap = new HashMap();
96 |
97 | //添加 SAVE_KEY 参数
98 | paramsMap.put(Params.SAVE_KEY, savePath);
99 |
100 | //初始化JSONArray
101 | JSONArray array = new JSONArray();
102 |
103 | //初始化JSONObject
104 | JSONObject json = new JSONObject();
105 |
106 | //json 添加 name 属性
107 | json.put("name", "thumb");
108 |
109 | //json 添加 X_GMKERL_THUMB 属性
110 | json.put(Params.X_GMKERL_THUMB, "/fw/300/unsharp/true/quality/80/format/png");
111 |
112 | //json 添加 save_as 属性
113 | json.put("save_as", "/path/to/fw_100.jpg");
114 |
115 | //json 添加 notify_url 属性
116 | json.put("notify_url", "http://httpbin.org/post");
117 |
118 | //将json 对象放入 JSONArray
119 | array.put(json);
120 |
121 | //添加异步作图参数 APPS
122 | paramsMap.put(Params.APPS, array);
123 |
124 | //打印结果
125 | System.out.println(uploader.upload(paramsMap, file));
126 | }
127 |
128 | }
129 |
--------------------------------------------------------------------------------
/src/main/java/demo/JigsawDemo.java:
--------------------------------------------------------------------------------
1 | package demo;
2 |
3 | import com.upyun.JigsawHandler;
4 | import com.upyun.Result;
5 | import com.upyun.UpException;
6 | import org.json.JSONArray;
7 | import org.json.JSONObject;
8 |
9 | import java.io.IOException;
10 | import java.util.HashMap;
11 | import java.util.Map;
12 |
13 | import static org.junit.Assert.assertNotNull;
14 | import static org.junit.Assert.assertTrue;
15 |
16 | public class JigsawDemo {
17 |
18 | // 运行前先设置好以下三个参数
19 | private static final String BUCKET_NAME = "空间名称";
20 | private static final String OPERATOR_NAME = "操作员名称";
21 | private static final String OPERATOR_PWD = "操作员密码";
22 |
23 |
24 | public static void main(String[] args) {
25 | testJigsaw();
26 | }
27 |
28 | public static void testJigsaw() {
29 |
30 | JigsawHandler handler = new JigsawHandler(BUCKET_NAME, OPERATOR_NAME, OPERATOR_PWD);
31 |
32 | //初始化参数组 Map
33 | Map paramsMap = new HashMap();
34 |
35 | paramsMap.put(JigsawHandler.Params.BUCKET_NAME, BUCKET_NAME);
36 | paramsMap.put(JigsawHandler.Params.NOTIFY_URL, "http://httpbin.org/post");
37 | paramsMap.put(JigsawHandler.Params.APP_NAME, "jigsaw");
38 |
39 | //已json格式生成任务信息
40 | JSONArray array = new JSONArray();
41 | JSONObject json = new JSONObject();
42 |
43 | String[][] pigs = new String[1][3];
44 |
45 | pigs[0][0] = "/result/convert/convert-00.png";
46 | pigs[0][1] = "/result/convert/convert-01.png";
47 | pigs[0][2] = "/result/convert/convert-03.png";
48 |
49 | //添加处理参数
50 | json.put(JigsawHandler.Params.IMAGE_MATRIX, pigs);
51 | json.put(JigsawHandler.Params.SAVE_AS, "/result/jigsaw/a.jpg");
52 |
53 | array.put(json);
54 |
55 | //添加任务信息
56 | paramsMap.put(JigsawHandler.Params.TASKS, array);
57 |
58 | try {
59 | Result result = handler.process(paramsMap);
60 |
61 | assertNotNull(result);
62 | assertTrue(result.isSucceed());
63 | assertNotNull(result.getMsg());
64 |
65 | String[] ids = handler.getTaskId(result.getMsg());
66 | assertNotNull(ids);
67 |
68 | } catch (IOException e) {
69 | e.printStackTrace();
70 | } catch (UpException e) {
71 | e.printStackTrace();
72 | }
73 |
74 | }
75 | }
76 |
--------------------------------------------------------------------------------
/src/main/java/demo/MediaHandlerDemo.java:
--------------------------------------------------------------------------------
1 | package demo;
2 |
3 | import com.upyun.MediaHandler;
4 | import com.upyun.Result;
5 | import com.upyun.UpException;
6 | import org.json.JSONArray;
7 | import org.json.JSONObject;
8 |
9 | import java.io.IOException;
10 | import java.util.Arrays;
11 | import java.util.HashMap;
12 | import java.util.Map;
13 |
14 | public class MediaHandlerDemo {
15 | // 运行前先设置好以下三个参数
16 | private static final String BUCKET_NAME = "空间名称";
17 | private static final String OPERATOR_NAME = "操作员名称";
18 | private static final String OPERATOR_PWD = "操作员密码";
19 |
20 | public static void main(String[] args) {
21 | String[] ids = testMediaProcess();
22 |
23 | if (ids != null) {
24 | testMediaStatus(ids);
25 | testMediaResult(ids);
26 | }
27 | }
28 |
29 |
30 | /**
31 | * 发起异步影视频处理请求DEMO
32 | *
33 | * @return TaskId 数组
34 | */
35 | private static String[] testMediaProcess() {
36 |
37 | //初始化 MediaHandler
38 | MediaHandler handler = new MediaHandler(BUCKET_NAME, OPERATOR_NAME, OPERATOR_PWD);
39 |
40 | //初始化参数组 Map
41 | Map paramsMap = new HashMap();
42 |
43 | //添加必选参数 bucket_name, notify_url, source, tasks, accept
44 | //空间名
45 | paramsMap.put(MediaHandler.Params.BUCKET_NAME, BUCKET_NAME);
46 | //回调地址
47 | paramsMap.put(MediaHandler.Params.NOTIFY_URL, "http://httpbin.org/post");
48 | //必须指定为 json
49 | paramsMap.put(MediaHandler.Params.ACCEPT, "json");
50 | //需要处理视频路径
51 | paramsMap.put(MediaHandler.Params.SOURCE, "/test.mp4");
52 |
53 |
54 | //已json格式生成任务信息
55 | JSONArray array = new JSONArray();
56 | JSONObject json = new JSONObject();
57 |
58 | //添加处理参数
59 | //不同的处理任务对应不同的 type
60 | json.put(MediaHandler.Params.TYPE, "video");
61 | //影视频处理参数 包括视频转码,HLS 切片,视频水印,视频截图,视频拼接,音频剪辑,元数据获取 请见API文档
62 | json.put(MediaHandler.Params.AVOPTS, "/s/240p(4:3)/as/1/r/30");
63 | //是否返回 JSON 格式元数据,默认 false。支持 type 值为 video 功能
64 | json.put(MediaHandler.Params.RETURN_INFO, "true");
65 | //输出文件保存路径(同一个空间下),如果没有指定,系统自动生成在同空间同目录下
66 | json.put(MediaHandler.Params.SAVE_AS, "testProcess.mp4");
67 |
68 | JSONObject json2 = new JSONObject();
69 |
70 | json2.put(MediaHandler.Params.TYPE, "video");
71 | json2.put(MediaHandler.Params.AVOPTS, "/s/240p(4:3)/as/1/r/30");
72 | json2.put(MediaHandler.Params.RETURN_INFO, "true");
73 | json2.put(MediaHandler.Params.SAVE_AS, "testProcess2.mp4");
74 |
75 | array.put(json2);
76 | array.put(json);
77 |
78 | //添加任务信息
79 | paramsMap.put(MediaHandler.Params.TASKS, array);
80 |
81 | try {
82 | Result result = handler.process(paramsMap);
83 | System.out.println(result);
84 | if (result.isSucceed()) {
85 |
86 | String[] ids = handler.getTaskId(result.getMsg());
87 | System.out.println(Arrays.toString(ids));
88 | return ids;
89 |
90 | }
91 | } catch (IOException e) {
92 | e.printStackTrace();
93 | } catch (UpException e) {
94 | e.printStackTrace();
95 | }
96 |
97 | return null;
98 | }
99 |
100 | /**
101 | * 查询处理进度DEMO
102 | *
103 | * @param ids 需要查询的任务ID
104 | */
105 | private static void testMediaStatus(String[] ids) {
106 |
107 | MediaHandler handle = new MediaHandler(BUCKET_NAME, OPERATOR_NAME, OPERATOR_PWD);
108 |
109 | //初始化参数组 Map
110 | Map paramsMap = new HashMap();
111 |
112 | paramsMap.put(MediaHandler.Params.BUCKET_NAME, BUCKET_NAME);
113 |
114 | StringBuilder sb = new StringBuilder();
115 |
116 | for (int i = 0; i < ids.length; i++) {
117 | sb.append(ids[i] + ",");
118 | }
119 |
120 | String task_ids = sb.toString().substring(0, sb.length() - 1);
121 | paramsMap.put(MediaHandler.Params.TASK_IDS, task_ids);
122 |
123 | try {
124 | Result result = handle.getStatus(paramsMap);
125 | System.out.println("status:" + result);
126 |
127 | } catch (IOException e) {
128 | e.printStackTrace();
129 | } catch (UpException e) {
130 | e.printStackTrace();
131 | }
132 |
133 | }
134 |
135 | /**
136 | * 查询处理结果DEMO
137 | *
138 | * @param ids 需要查询的任务ID
139 | */
140 | private static void testMediaResult(String[] ids) {
141 |
142 | MediaHandler handle = new MediaHandler(BUCKET_NAME, OPERATOR_NAME, OPERATOR_PWD);
143 |
144 | //初始化参数组 Map
145 | Map paramsMap = new HashMap();
146 |
147 | paramsMap.put(MediaHandler.Params.BUCKET_NAME, BUCKET_NAME);
148 |
149 | StringBuilder sb = new StringBuilder();
150 |
151 | for (int i = 0; i < ids.length; i++) {
152 | sb.append(ids[i] + ",");
153 | }
154 |
155 | String task_ids = sb.toString().substring(0, sb.length() - 1);
156 | paramsMap.put(MediaHandler.Params.TASK_IDS, task_ids);
157 |
158 | try {
159 | Result result = handle.getResult(paramsMap);
160 | System.out.println("result:" + result);
161 |
162 | } catch (IOException e) {
163 | e.printStackTrace();
164 | } catch (UpException e) {
165 | e.printStackTrace();
166 | }
167 |
168 | }
169 |
170 | }
171 |
--------------------------------------------------------------------------------
/src/main/java/demo/ParallelUploadDemo.java:
--------------------------------------------------------------------------------
1 | package demo;
2 |
3 | import com.upyun.BaseUploader;
4 | import com.upyun.ParallelUploader;
5 | import com.upyun.SerialUploader;
6 | import com.upyun.UpException;
7 |
8 | import java.io.IOException;
9 | import java.util.concurrent.ExecutionException;
10 |
11 | public class ParallelUploadDemo {
12 |
13 | // 运行前先设置好以下三个参数
14 | private static final String BUCKET_NAME = "空间名称";
15 | private static final String OPERATOR_NAME = "操作员名称";
16 | private static final String OPERATOR_PWD = "操作员密码";
17 |
18 | //上传测试文件
19 | private static final String SAMPLE_PIC_FILE = System.getProperty("user.dir") + "/test.MOV";
20 |
21 | //上传至空间路径
22 | private static final String UPLOAD_PATH = "/test.MOV";
23 |
24 | public static void main(String[] args) throws InterruptedException, IOException, UpException {
25 |
26 | final ParallelUploader parallelUploader = new ParallelUploader(BUCKET_NAME, OPERATOR_NAME, OPERATOR_PWD);
27 |
28 | //设置上传进度监听
29 | parallelUploader.setOnProgressListener(new BaseUploader.OnProgressListener() {
30 | public void onProgress(int index, int total) {
31 | System.out.println(index + "::" + total + "::" + index * 100 / total + "%");
32 | }
33 | });
34 |
35 | new Thread() {
36 | public void run() {
37 | try {
38 | parallelUploader.upload(SAMPLE_PIC_FILE, UPLOAD_PATH, null);
39 | } catch (IOException e) {
40 | e.printStackTrace();
41 | } catch (UpException e) {
42 | e.printStackTrace();
43 | }
44 | }
45 | }.start();
46 |
47 | Thread.sleep(2000);
48 |
49 | parallelUploader.pause();
50 |
51 | Thread.sleep(2000);
52 |
53 | System.out.println(parallelUploader.resume());
54 | }
55 | }
--------------------------------------------------------------------------------
/src/main/java/demo/PicBucketDemo.java:
--------------------------------------------------------------------------------
1 | package demo;
2 |
3 | import com.upyun.RestManager;
4 | import com.upyun.UpException;
5 | import com.upyun.UpYunUtils;
6 | import okhttp3.Response;
7 |
8 | import java.io.File;
9 | import java.io.IOException;
10 | import java.util.HashMap;
11 | import java.util.Map;
12 |
13 | /**
14 | * 图片类空间的demo,一般性操作参考文件空间的demo(FileBucketDemo.java)
15 | *
16 | * 注意:直接使用部分图片处理功能后,将会丢弃原图保存处理后的图片
17 | */
18 | public class PicBucketDemo {
19 |
20 | // 运行前先设置好以下三个参数
21 | private static final String BUCKET_NAME = "空间名称";
22 | private static final String OPERATOR_NAME = "操作员名称";
23 | private static final String OPERATOR_PWD = "操作员密码";
24 |
25 | /**
26 | * 根目录
27 | */
28 | private static final String DIR_ROOT = "/";
29 |
30 | /**
31 | * 上传到upyun的图片名
32 | */
33 | private static final String PIC_NAME = "sample.jpeg";
34 |
35 | /**
36 | * 本地待上传的测试文件
37 | */
38 | private static final String SAMPLE_PIC_FILE = System
39 | .getProperty("user.dir") + "/sample.jpeg";
40 |
41 | static {
42 | File picFile = new File(SAMPLE_PIC_FILE);
43 |
44 | if (!picFile.isFile()) {
45 | System.out.println("本地待上传的测试文件不存在!");
46 | }
47 | }
48 |
49 | public static void main(String[] args) throws IOException, UpException {
50 |
51 | // 初始化空间
52 | RestManager restManager = new RestManager(BUCKET_NAME, OPERATOR_NAME, OPERATOR_PWD);
53 |
54 | // 要传到upyun后的文件路径
55 | String filePath = DIR_ROOT + PIC_NAME;
56 |
57 | // 本地待上传的图片文件
58 | File file = new File(SAMPLE_PIC_FILE);
59 |
60 | Map params = new HashMap();
61 | // 设置待上传文件的 Content-MD5 值
62 | // 如果又拍云服务端收到的文件MD5值与用户设置的不一致,将回报 406 NotAcceptable 错误
63 | params.put(RestManager.PARAMS.CONTENT_MD5.getValue(), UpYunUtils.md5(file, 1024));
64 |
65 | // 设置待上传文件的"访问密钥"
66 | // 注意:
67 | // 仅支持图片空!,设置密钥后,无法根据原文件URL直接访问,需带URL后面加上(缩略图间隔标志符+密钥)进行访问
68 | // 举例:
69 | // 如果缩略图间隔标志符为"!",密钥为"bac",上传文件路径为"/folder/test.jpg",
70 | // 那么该图片的对外访问地址为:http://空间域名 /folder/test.jpg!bac
71 | params.put(RestManager.PARAMS.CONTENT_SECRET.getValue(), "bac");
72 |
73 | //图片预处理参数
74 | params.put(RestManager.PARAMS.X_GMKERL_THUMB.getValue(),
75 | "/fw/300/unsharp/true/rotate/90");
76 |
77 | // 上传文件
78 | Response response = restManager.writeFile(filePath, file, params);
79 | System.out.println("图片上传:" + isSuccess(response.isSuccessful()));
80 | }
81 |
82 |
83 | private static String isSuccess(boolean result) {
84 | return result ? " 成功" : " 失败";
85 | }
86 | }
87 |
--------------------------------------------------------------------------------
/src/main/java/demo/PullingDemo.java:
--------------------------------------------------------------------------------
1 | package demo;
2 |
3 | import com.upyun.PullingHandler;
4 | import com.upyun.Result;
5 | import com.upyun.UpException;
6 | import org.json.JSONArray;
7 | import org.json.JSONObject;
8 |
9 | import java.io.IOException;
10 | import java.util.Arrays;
11 | import java.util.HashMap;
12 | import java.util.Map;
13 |
14 | public class PullingDemo {
15 |
16 | // 运行前先设置好以下三个参数
17 | private static final String BUCKET_NAME = "空间名称";
18 | private static final String OPERATOR_NAME = "操作员名称";
19 | private static final String OPERATOR_PWD = "操作员密码";
20 |
21 |
22 | public static void main(String[] args) {
23 | testPulling();
24 | }
25 |
26 |
27 | private static void testPulling() {
28 |
29 | PullingHandler handler = new PullingHandler(BUCKET_NAME, OPERATOR_NAME, OPERATOR_PWD);
30 |
31 | //初始化参数组 Map
32 | Map paramsMap = new HashMap();
33 |
34 | //空间名
35 | paramsMap.put(PullingHandler.Params.BUCKET_NAME, BUCKET_NAME);
36 | //回调地址
37 | paramsMap.put(PullingHandler.Params.NOTIFY_URL, "http://httpbin.org/post");
38 | //选择任务
39 | paramsMap.put(PullingHandler.Params.APP_NAME, "spiderman");
40 |
41 | //以json格式生成任务信息
42 | JSONArray array = new JSONArray();
43 | JSONObject json = new JSONObject();
44 |
45 | //添加处理参数
46 | json.put(PullingHandler.Params.URL, "http://formtest.b0.upaiyun.com/sample.jpeg");
47 | json.put(PullingHandler.Params.RANDOM, false);
48 | json.put(PullingHandler.Params.OVERWRITE, true);
49 | json.put(PullingHandler.Params.X_GMKERL_THUMB, "/watermark/text/5L2g5aW977yB");
50 | json.put(PullingHandler.Params.SAVE_AS, "/result/pulling/a.jpg");
51 |
52 | JSONObject json2 = new JSONObject();
53 |
54 | //添加处理参数
55 | json2.put(PullingHandler.Params.URL, "http://formtest.b0.upaiyun.com/sample.jpeg");
56 | json2.put(PullingHandler.Params.RANDOM, false);
57 | json2.put(PullingHandler.Params.OVERWRITE, true);
58 | json2.put(PullingHandler.Params.X_GMKERL_THUMB, "/fw/300/unsharp/true/quality/80/format/png");
59 | json2.put(PullingHandler.Params.SAVE_AS, "/result/pulling/b.jpg");
60 |
61 | array.put(json2);
62 | array.put(json);
63 |
64 | //添加任务信息
65 | paramsMap.put(PullingHandler.Params.TASKS, array);
66 |
67 | try {
68 | Result result = handler.process(paramsMap);
69 | System.out.println(result);
70 | if (result.isSucceed()) {
71 |
72 | String[] ids = handler.getTaskId(result.getMsg());
73 | System.out.println(Arrays.toString(ids));
74 |
75 | }
76 | } catch (IOException e) {
77 | e.printStackTrace();
78 | } catch (UpException e) {
79 | e.printStackTrace();
80 | }
81 |
82 | }
83 | }
84 |
--------------------------------------------------------------------------------
/src/main/java/demo/RestManagerDemo.java:
--------------------------------------------------------------------------------
1 | package demo;
2 |
3 | import com.UpYun;
4 | import com.upyun.RestManager;
5 | import com.upyun.UpException;
6 | import okhttp3.Response;
7 |
8 | import java.io.File;
9 | import java.io.FileInputStream;
10 | import java.io.IOException;
11 | import java.util.HashMap;
12 | import java.util.Map;
13 |
14 | import static org.junit.Assert.assertTrue;
15 |
16 | /**
17 | * 文件类空间的demo
18 | */
19 | public class RestManagerDemo {
20 |
21 | // 运行前先设置好以下三个参数
22 | private static final String BUCKET_NAME = "空间名称";
23 | private static final String OPERATOR_NAME = "操作员名称";
24 | private static final String OPERATOR_PWD = "操作员密码";
25 |
26 | /**
27 | * 根目录
28 | */
29 | private static final String DIR_ROOT = "/";
30 | /**
31 | * 多级目录
32 | */
33 | private static final String DIR_MORE = "/1/2/3/";
34 | /**
35 | * 目录名
36 | */
37 | private static final String FOLDER_NAME = "tmp";
38 | /**
39 | * 上传到upyun的文件名
40 | */
41 | private static final String FILE_NAME = "test.txt";
42 |
43 | /**
44 | * 本地待上传的测试文件
45 | */
46 | private static final String SAMPLE_TXT_FILE = System
47 | .getProperty("user.dir") + "/test.txt";
48 |
49 | private static RestManager restManager = null;
50 |
51 | static {
52 | File txtFile = new File(SAMPLE_TXT_FILE);
53 |
54 | if (!txtFile.isFile()) {
55 | System.out.println("本地待上传的测试文件不存在!");
56 | }
57 | }
58 |
59 | public static void main(String[] args) throws IOException, UpException {
60 |
61 | // 初始化空间
62 | restManager = new RestManager(BUCKET_NAME, OPERATOR_NAME, OPERATOR_PWD);
63 |
64 | // ****** 可选设置 begin ******
65 |
66 | // 切换 API 接口的域名接入点,默认为自动识别接入点
67 | restManager.setApiDomain(RestManager.ED_AUTO);
68 |
69 | // 设置连接超时时间,默认为30秒
70 | restManager.setTimeout(60);
71 |
72 | // ****** 可选设置 end ******
73 |
74 | //上传文件,图片空间的文件上传请参考 PicBucketDemo.java
75 | testWriteFile();
76 |
77 | //复制文件
78 | testCopyFile();
79 |
80 | //移动文件
81 | testMoveFile();
82 |
83 | //读取文件/下载文件
84 | testReadFile();
85 |
86 | //删除文件
87 | testDeleteFile();
88 |
89 | //创建目录
90 | testMkDir();
91 |
92 | //删除目录
93 | testRmDir();
94 |
95 | //获取文件信息
96 | testGetFileInfo();
97 |
98 | //获取目录文件列表
99 | testReadDir();
100 |
101 | //获取服务使用量
102 | testGetBucketUsage();
103 |
104 | }
105 |
106 | /**
107 | * 获取空间占用大小
108 | */
109 | public static void testGetBucketUsage() throws IOException, UpException {
110 |
111 | Response response = restManager.getBucketUsage();
112 |
113 | System.out.println("空间总使用量:" + response.body().string() + "B");
114 | System.out.println();
115 | }
116 |
117 | /**
118 | * 上传文件
119 | *
120 | * @throws IOException
121 | */
122 | public static void testWriteFile() throws IOException, UpException {
123 |
124 | // 要上传的纯文字内容
125 | String content = "test content";
126 |
127 | // 要传到upyun后的文件路径
128 | String filePath = DIR_ROOT + FILE_NAME;
129 | // 要传到upyun后的文件路径:多级目录
130 | String filePath2 = DIR_MORE + FILE_NAME;
131 | String filePath3 = DIR_MORE + "test3.txt";
132 |
133 | /*
134 | * 上传方法1:上传 byte[]
135 | */
136 | Response response = restManager.writeFile(filePath, content.getBytes(), null);
137 | System.out.println("1.上传 " + filePath + isSuccess(response));
138 |
139 |
140 | /*
141 | * 上传方法2:上传文件
142 | */
143 | File file = new File(SAMPLE_TXT_FILE);
144 | Response response2 = restManager.writeFile(filePath2, file, null);
145 | System.out.println("2.上传 " + filePath2 + isSuccess(response2));
146 |
147 | /*
148 | * 上传方法3:上传流
149 | */
150 | File file2 = new File(SAMPLE_TXT_FILE);
151 | Response response3 = restManager.writeFile(filePath3, new FileInputStream(file2), null);
152 | System.out.println("3.上传 " + filePath3 + isSuccess(response3));
153 | }
154 |
155 | /**
156 | * 获取文件信息
157 | */
158 | public static void testGetFileInfo() throws IOException, UpException {
159 |
160 | // upyun空间下存在的文件的路径
161 | String filePath = DIR_MORE + "test3.txt";
162 |
163 | System.out.println(filePath + " 的文件信息:" + restManager.getFileInfo(filePath).headers());
164 | System.out.println();
165 | }
166 |
167 | /**
168 | * 读取文件/下载文件
169 | *
170 | * @throws IOException
171 | */
172 | public static void testReadFile() throws IOException, UpException {
173 |
174 | // upyun空间下存在的文件的路径
175 | String filePath = DIR_ROOT + FILE_NAME;
176 |
177 | /*
178 | * 下载文件
179 | */
180 | Response response = restManager.readFile(filePath);
181 | System.out.println(filePath + " 的文件内容:" + response.body().string());
182 | }
183 |
184 | /**
185 | * 删除文件
186 | */
187 | public static void testDeleteFile() throws IOException, UpException {
188 |
189 | // upyun空间下存在的文件的路径
190 | String filePath = DIR_ROOT + FILE_NAME;
191 |
192 | // 删除文件
193 | Response response = restManager.deleteFile(filePath, null);
194 |
195 | System.out.println(filePath + " 删除" + isSuccess(response));
196 | System.out.println();
197 | }
198 |
199 | /**
200 | * 创建目录
201 | */
202 | public static void testMkDir() throws IOException, UpException {
203 | String dir1 = DIR_ROOT + FOLDER_NAME;
204 | Response response = restManager.mkDir(dir1);
205 | System.out.println("创建目录:" + dir1 + isSuccess(response));
206 |
207 |
208 | }
209 |
210 | /**
211 | * 删除目录
212 | */
213 | public static void testRmDir() throws IOException, UpException {
214 |
215 | // 带删除的目录必须存在,并且目录下已不存在任何文件或子目录
216 | String dirPath = DIR_ROOT + FOLDER_NAME;
217 | Response response = restManager.rmDir(dirPath);
218 | System.out.println("删除目录:" + dirPath + isSuccess(response));
219 | }
220 |
221 | /**
222 | * 读取目录下的文件列表
223 | */
224 | public static void testReadDir() throws IOException, UpException {
225 |
226 | // 参数可以换成其他目录路径
227 | String dirPath = DIR_ROOT;
228 |
229 | Map params = new HashMap();
230 |
231 | params.put(UpYun.PARAMS.KEY_X_LIST_LIMIT.getValue(), "10");
232 |
233 | Response response = restManager.readDirIter(dirPath, params);
234 | System.out.println(response.body().string());
235 | }
236 |
237 |
238 | /**
239 | * 复制文件
240 | *
241 | * @throws IOException
242 | * @throws UpException
243 | */
244 | public static void testCopyFile() throws IOException, UpException {
245 | String sourcePath = "/" + BUCKET_NAME + DIR_ROOT + FILE_NAME;
246 | Response response = restManager.copyFile("/copy.txt", sourcePath, null);
247 | System.out.println("复制文件:" + sourcePath + isSuccess(response));
248 | }
249 |
250 | /**
251 | * 移动文件
252 | *
253 | * @throws IOException
254 | * @throws UpException
255 | */
256 | public static void testMoveFile() throws IOException, UpException {
257 | String sourcePath = "/" + BUCKET_NAME + DIR_MORE + FILE_NAME;
258 | Response response = restManager.moveFile("/move.txt", sourcePath, null);
259 | System.out.println("移动文件:" + sourcePath + isSuccess(response));
260 | }
261 |
262 | private static String isSuccess(Response response) {
263 | return response.isSuccessful() ? " 成功" : " 失败";
264 | }
265 | }
266 |
--------------------------------------------------------------------------------
/src/main/java/demo/SerialUploadDemo.java:
--------------------------------------------------------------------------------
1 | package demo;
2 |
3 | import com.upyun.BaseUploader;
4 | import com.upyun.SerialUploader;
5 | import com.upyun.UpException;
6 |
7 | import java.io.IOException;
8 |
9 | public class SerialUploadDemo {
10 |
11 | // 运行前先设置好以下三个参数
12 | private static final String BUCKET_NAME = "空间名称";
13 | private static final String OPERATOR_NAME = "操作员名称";
14 | private static final String OPERATOR_PWD = "操作员密码";
15 |
16 | //上传测试文件
17 | private static final String SAMPLE_PIC_FILE = System.getProperty("user.dir") + "/test.MOV";
18 |
19 | //上传至空间路径
20 | private static final String UPLOAD_PATH = "/test.MOV";
21 |
22 | public static void main(String[] args) throws IOException, UpException, InterruptedException {
23 |
24 | final SerialUploader resume = new SerialUploader(BUCKET_NAME, OPERATOR_NAME, OPERATOR_PWD);
25 |
26 | //设置上传进度监听
27 | resume.setOnProgressListener(new BaseUploader.OnProgressListener() {
28 | public void onProgress(int index, int total) {
29 | System.out.println(index + "::" + total + "::" + index * 100 / total + "%");
30 | }
31 | });
32 |
33 | //设置 MD5 校验
34 | resume.setCheckMD5(true);
35 |
36 |
37 | new Thread() {
38 | public void run() {
39 | try {
40 | System.out.println("first:" + resume.upload(SAMPLE_PIC_FILE, UPLOAD_PATH, null));
41 | } catch (IOException e) {
42 | e.printStackTrace();
43 | } catch (UpException e) {
44 | e.printStackTrace();
45 | }
46 | }
47 | }.start();
48 |
49 | Thread.sleep(2000);
50 |
51 | resume.pause();
52 |
53 | Thread.sleep(2000);
54 |
55 | System.out.println(resume.resume());
56 | }
57 | }
58 |
--------------------------------------------------------------------------------
/src/test/java/CompressTest.java:
--------------------------------------------------------------------------------
1 | import com.upyun.CompressHandler;
2 | import com.upyun.Result;
3 | import com.upyun.UpException;
4 | import org.json.JSONArray;
5 | import org.json.JSONObject;
6 | import org.junit.Test;
7 |
8 | import java.io.IOException;
9 | import java.util.HashMap;
10 | import java.util.Map;
11 |
12 | import static org.junit.Assert.assertNotNull;
13 | import static org.junit.Assert.assertTrue;
14 |
15 | public class CompressTest {
16 | private static final String BUCKET_NAME = "formtest";
17 | private static final String OPERATOR_NAME = "one";
18 | private static final String OPERATOR_PWD = "qwertyuiop";
19 |
20 | @Test
21 | public void testDecompress() {
22 |
23 | CompressHandler handler = new CompressHandler(BUCKET_NAME, OPERATOR_NAME, OPERATOR_PWD);
24 |
25 | //初始化参数组 Map
26 | Map paramsMap = new HashMap();
27 |
28 | paramsMap.put(CompressHandler.Params.BUCKET_NAME, BUCKET_NAME);
29 | paramsMap.put(CompressHandler.Params.NOTIFY_URL, "http://httpbin.org/post");
30 | paramsMap.put(CompressHandler.Params.APP_NAME, "depress");
31 |
32 | //已json格式生成任务信息
33 | JSONArray array = new JSONArray();
34 | JSONObject json = new JSONObject();
35 |
36 | //添加处理参数
37 | json.put(CompressHandler.Params.SOURCES, "/result/compress/a.zip");
38 | json.put(CompressHandler.Params.SAVE_AS, "/result/depress");
39 |
40 | JSONObject json2 = new JSONObject();
41 |
42 | //添加处理参数
43 | json2.put(CompressHandler.Params.SOURCES, "/result/compress/b.zip");
44 | json2.put(CompressHandler.Params.SAVE_AS, "/result/depress2");
45 |
46 | array.put(json2);
47 | array.put(json);
48 |
49 | //添加任务信息
50 | paramsMap.put(CompressHandler.Params.TASKS, array);
51 |
52 | try {
53 | Result result = handler.process(paramsMap);
54 | assertNotNull(result);
55 | assertTrue(result.isSucceed());
56 | assertNotNull(result.getMsg());
57 |
58 | String[] ids = handler.getTaskId(result.getMsg());
59 | assertNotNull(ids);
60 | } catch (IOException e) {
61 | e.printStackTrace();
62 | } catch (UpException e) {
63 | e.printStackTrace();
64 | }
65 |
66 | }
67 |
68 | @Test
69 | public void testCompress() {
70 |
71 | CompressHandler handler = new CompressHandler(BUCKET_NAME, OPERATOR_NAME, OPERATOR_PWD);
72 |
73 | //初始化参数组 Map
74 | Map paramsMap = new HashMap();
75 |
76 | paramsMap.put(CompressHandler.Params.BUCKET_NAME, BUCKET_NAME);
77 | paramsMap.put(CompressHandler.Params.NOTIFY_URL, "http://httpbin.org/post");
78 | paramsMap.put(CompressHandler.Params.APP_NAME, "compress");
79 |
80 | //已json格式生成任务信息
81 | JSONArray array = new JSONArray();
82 | JSONObject json = new JSONObject();
83 |
84 | JSONArray array2 = new JSONArray();
85 | array2.put("/a/b/c/sample.jpeg");
86 | array2.put("/a/b/c/rotate.jpg");
87 |
88 | //添加处理参数
89 | json.put(CompressHandler.Params.SOURCES, array2);
90 | json.put(CompressHandler.Params.SAVE_AS, "/result/compress/a.zip");
91 | json.put(CompressHandler.Params.HOME_DIR, "a/b/c");
92 |
93 | JSONObject json2 = new JSONObject();
94 |
95 | //添加处理参数
96 | json2.put(CompressHandler.Params.SOURCES, array2);
97 | json2.put(CompressHandler.Params.SAVE_AS, "/result/compress/b.zip");
98 | json2.put(CompressHandler.Params.HOME_DIR, "a/b/c");
99 |
100 | array.put(json2);
101 | array.put(json);
102 |
103 | //添加任务信息
104 | paramsMap.put(CompressHandler.Params.TASKS, array);
105 |
106 | try {
107 | Result result = handler.process(paramsMap);
108 |
109 | assertNotNull(result);
110 | assertTrue(result.isSucceed());
111 | assertNotNull(result.getMsg());
112 |
113 | String[] ids = handler.getTaskId(result.getMsg());
114 | assertNotNull(ids);
115 |
116 | } catch (IOException e) {
117 | e.printStackTrace();
118 | } catch (UpException e) {
119 | e.printStackTrace();
120 | }
121 |
122 |
123 | }
124 |
125 | }
126 |
--------------------------------------------------------------------------------
/src/test/java/ConvertTest.java:
--------------------------------------------------------------------------------
1 | import com.upyun.ConvertHandler;
2 | import com.upyun.ConvertHandler;
3 | import com.upyun.Result;
4 | import com.upyun.UpException;
5 | import org.json.JSONArray;
6 | import org.json.JSONObject;
7 | import org.junit.Test;
8 |
9 | import java.io.IOException;
10 | import java.util.HashMap;
11 | import java.util.Map;
12 |
13 | import static org.junit.Assert.assertNotNull;
14 | import static org.junit.Assert.assertTrue;
15 |
16 | public class ConvertTest {
17 | private static final String BUCKET_NAME = "formtest";
18 | private static final String OPERATOR_NAME = "one";
19 | private static final String OPERATOR_PWD = "qwertyuiop";
20 |
21 |
22 | @Test
23 | public void testConvert() {
24 |
25 | ConvertHandler handler = new ConvertHandler(BUCKET_NAME, OPERATOR_NAME, OPERATOR_PWD);
26 |
27 | //初始化参数组 Map
28 | Map paramsMap = new HashMap();
29 |
30 | paramsMap.put(ConvertHandler.Params.BUCKET_NAME, BUCKET_NAME);
31 | paramsMap.put(ConvertHandler.Params.NOTIFY_URL, "http://httpbin.org/post");
32 | paramsMap.put(ConvertHandler.Params.APP_NAME, "uconvert");
33 |
34 | //已json格式生成任务信息
35 | JSONArray array = new JSONArray();
36 | JSONObject json = new JSONObject();
37 |
38 | //添加处理参数
39 | json.put(ConvertHandler.Params.SOURCE, "/test_ppt.pptx");
40 | json.put(ConvertHandler.Params.SAVE_AS, "/result/convert/convert");
41 |
42 | array.put(json);
43 |
44 | //添加任务信息
45 | paramsMap.put(ConvertHandler.Params.TASKS, array);
46 |
47 | try {
48 | Result result = handler.process(paramsMap);
49 |
50 | assertNotNull(result);
51 | assertTrue(result.isSucceed());
52 | assertNotNull(result.getMsg());
53 |
54 | String[] ids = handler.getTaskId(result.getMsg());
55 | assertNotNull(ids);
56 |
57 | } catch (IOException e) {
58 | e.printStackTrace();
59 | } catch (UpException e) {
60 | e.printStackTrace();
61 | }
62 |
63 | }
64 | }
65 |
--------------------------------------------------------------------------------
/src/test/java/FormUploaderTest.java:
--------------------------------------------------------------------------------
1 | import com.upyun.*;
2 | import org.junit.Test;
3 |
4 | import java.io.File;
5 | import java.security.InvalidKeyException;
6 | import java.security.NoSuchAlgorithmException;
7 | import java.security.SignatureException;
8 | import java.util.HashMap;
9 | import java.util.Map;
10 |
11 | import static org.junit.Assert.*;
12 |
13 | public class FormUploaderTest {
14 |
15 | private static final String BUCKET_NAME = "formtest";
16 | private static final String OPERATOR_NAME = "one";
17 | private static final String OPERATOR_PWD = "qwertyuiop";
18 |
19 | //上传测试文件
20 | private static final String SAMPLE_PIC_FILE = System.getProperty("user.dir") + "/sample.jpeg";
21 |
22 | @Test
23 | public void testUploadFile() throws NoSuchAlgorithmException, SignatureException, InvalidKeyException {
24 | File file = new File(SAMPLE_PIC_FILE);
25 | //保存路径 必须设置该参数
26 | String savePath = "/uploads/{year}{mon}{day}/{random32}{.suffix}";
27 | final Map paramsMap = new HashMap();
28 | paramsMap.put(Params.SAVE_KEY, savePath);
29 |
30 | FormUploader uploader = new FormUploader(BUCKET_NAME, OPERATOR_NAME, OPERATOR_PWD);
31 | Result result = uploader.upload(paramsMap, file);
32 | assertTrue(result.isSucceed());
33 | }
34 |
35 | @Test
36 | public void testUploadByte() throws NoSuchAlgorithmException, SignatureException, InvalidKeyException {
37 | //保存路径 必须设置该参数
38 | String savePath = "/uploads/{year}{mon}{day}/{random32}{.suffix}";
39 | final Map paramsMap = new HashMap();
40 | paramsMap.put(Params.SAVE_KEY, savePath);
41 |
42 | FormUploader uploader = new FormUploader(BUCKET_NAME, OPERATOR_NAME, OPERATOR_PWD);
43 | Result result = uploader.upload(paramsMap, "test1".getBytes());
44 | assertTrue(result.isSucceed());
45 | }
46 |
47 | }
--------------------------------------------------------------------------------
/src/test/java/JigsawTest.java:
--------------------------------------------------------------------------------
1 | import com.upyun.JigsawHandler;
2 | import com.upyun.JigsawHandler;
3 | import com.upyun.Result;
4 | import com.upyun.UpException;
5 | import org.json.JSONArray;
6 | import org.json.JSONObject;
7 | import org.junit.Test;
8 |
9 | import java.io.IOException;
10 | import java.util.HashMap;
11 | import java.util.Map;
12 |
13 | import static org.junit.Assert.assertNotNull;
14 | import static org.junit.Assert.assertTrue;
15 |
16 | public class JigsawTest {
17 | private static final String BUCKET_NAME = "formtest";
18 | private static final String OPERATOR_NAME = "one";
19 | private static final String OPERATOR_PWD = "qwertyuiop";
20 |
21 |
22 | @Test
23 | public void testJigsaw() {
24 |
25 | JigsawHandler handler = new JigsawHandler(BUCKET_NAME, OPERATOR_NAME, OPERATOR_PWD);
26 |
27 | //初始化参数组 Map
28 | Map paramsMap = new HashMap();
29 |
30 | paramsMap.put(JigsawHandler.Params.BUCKET_NAME, BUCKET_NAME);
31 | paramsMap.put(JigsawHandler.Params.NOTIFY_URL, "http://httpbin.org/post");
32 | paramsMap.put(JigsawHandler.Params.APP_NAME, "jigsaw");
33 |
34 | //已json格式生成任务信息
35 | JSONArray array = new JSONArray();
36 | JSONObject json = new JSONObject();
37 |
38 |
39 | String[][] pigs = new String[1][3];
40 |
41 | pigs[0][0] = "/result/convert/convert-00.png";
42 | pigs[0][1] = "/result/convert/convert-01.png";
43 | pigs[0][2] = "/result/convert/convert-03.png";
44 |
45 | //添加处理参数
46 | json.put(JigsawHandler.Params.IMAGE_MATRIX, pigs);
47 | json.put(JigsawHandler.Params.SAVE_AS, "/result/jigsaw/a.jpg");
48 |
49 | array.put(json);
50 |
51 | //添加任务信息
52 | paramsMap.put(JigsawHandler.Params.TASKS, array);
53 |
54 | try {
55 | Result result = handler.process(paramsMap);
56 |
57 | assertNotNull(result);
58 | assertTrue(result.isSucceed());
59 | assertNotNull(result.getMsg());
60 |
61 | String[] ids = handler.getTaskId(result.getMsg());
62 | assertNotNull(ids);
63 |
64 | } catch (IOException e) {
65 | e.printStackTrace();
66 | } catch (UpException e) {
67 | e.printStackTrace();
68 | }
69 |
70 | }
71 | }
72 |
--------------------------------------------------------------------------------
/src/test/java/MediaHandlerTest.java:
--------------------------------------------------------------------------------
1 | import com.upyun.MediaHandler;
2 | import com.upyun.Result;
3 | import com.upyun.UpException;
4 | import org.json.JSONArray;
5 | import org.json.JSONObject;
6 | import org.junit.Test;
7 |
8 | import java.io.IOException;
9 | import java.util.HashMap;
10 | import java.util.Map;
11 |
12 | import static org.junit.Assert.assertNotNull;
13 | import static org.junit.Assert.assertTrue;
14 |
15 | public class MediaHandlerTest {
16 |
17 | private static final String BUCKET_NAME = "formtest";
18 | private static final String OPERATOR_NAME = "one";
19 | private static final String OPERATOR_PWD = "qwertyuiop";
20 |
21 |
22 | @Test
23 | public void testMediaProcess() {
24 | MediaHandler handler = new MediaHandler(BUCKET_NAME, OPERATOR_NAME, OPERATOR_PWD);
25 |
26 | //初始化参数组 Map
27 | Map paramsMap = new HashMap();
28 |
29 | paramsMap.put(MediaHandler.Params.BUCKET_NAME, BUCKET_NAME);
30 | paramsMap.put(MediaHandler.Params.NOTIFY_URL, "http://httpbin.org/post");
31 | paramsMap.put(MediaHandler.Params.ACCEPT, "json");
32 | paramsMap.put(MediaHandler.Params.SOURCE, "/test.mp4");
33 |
34 | JSONArray array = new JSONArray();
35 |
36 | JSONObject json = new JSONObject();
37 |
38 | json.put(MediaHandler.Params.TYPE, "video");
39 | json.put(MediaHandler.Params.AVOPTS, "/s/240p(4:3)/as/1/r/30");
40 | json.put(MediaHandler.Params.RETURN_INFO, "true");
41 | json.put(MediaHandler.Params.SAVE_AS, "testProcess.mp4");
42 |
43 | JSONObject json2 = new JSONObject();
44 |
45 | json2.put(MediaHandler.Params.TYPE, "video");
46 | json2.put(MediaHandler.Params.AVOPTS, "/s/240p(4:3)/as/1/r/30");
47 | json2.put(MediaHandler.Params.RETURN_INFO, "true");
48 | json2.put(MediaHandler.Params.SAVE_AS, "testProcess2.mp4");
49 |
50 | array.put(json2);
51 | array.put(json);
52 |
53 | paramsMap.put(MediaHandler.Params.TASKS, array);
54 |
55 | Result result = null;
56 | try {
57 | result = handler.process(paramsMap);
58 |
59 | } catch (IOException e) {
60 | e.printStackTrace();
61 | } catch (UpException e) {
62 | e.printStackTrace();
63 | }
64 |
65 | assertNotNull(result);
66 | assertTrue(result.isSucceed());
67 | assertNotNull(result.getMsg());
68 |
69 | String[] ids = handler.getTaskId(result.getMsg());
70 | assertNotNull(ids);
71 | }
72 |
73 | @Test
74 | public void testMediaStatus() {
75 | String[] ids = new String[]{"02774703e7f5cc855681a7c42d819722", "921110d3843e92ac7932ff216e5ea348"};
76 |
77 | MediaHandler handle = new MediaHandler(BUCKET_NAME, OPERATOR_NAME, OPERATOR_PWD);
78 |
79 | //初始化参数组 Map
80 | Map paramsMap = new HashMap();
81 |
82 | paramsMap.put(MediaHandler.Params.BUCKET_NAME, BUCKET_NAME);
83 |
84 | StringBuilder sb = new StringBuilder();
85 |
86 | for (int i = 0; i < ids.length; i++) {
87 | sb.append(ids[i] + ",");
88 | }
89 |
90 | String task_ids = sb.toString().substring(0, sb.length() - 1);
91 | paramsMap.put(MediaHandler.Params.TASK_IDS, task_ids);
92 |
93 | Result result = null;
94 | try {
95 | result = handle.getStatus(paramsMap);
96 |
97 | } catch (IOException e) {
98 | e.printStackTrace();
99 | } catch (UpException e) {
100 | e.printStackTrace();
101 | }
102 |
103 | assertNotNull(result);
104 | assertTrue(result.isSucceed());
105 | assertNotNull(result.getMsg());
106 | }
107 |
108 | @Test
109 | public void testMediaResult() {
110 | String[] ids = new String[]{"02774703e7f5cc855681a7c42d819722", "921110d3843e92ac7932ff216e5ea348"};
111 |
112 | MediaHandler handle = new MediaHandler(BUCKET_NAME, OPERATOR_NAME, OPERATOR_PWD);
113 |
114 | //初始化参数组 Map
115 | Map paramsMap = new HashMap();
116 |
117 | paramsMap.put(MediaHandler.Params.BUCKET_NAME, BUCKET_NAME);
118 |
119 | StringBuilder sb = new StringBuilder();
120 |
121 | for (int i = 0; i < ids.length; i++) {
122 | sb.append(ids[i] + ",");
123 | }
124 |
125 | String task_ids = sb.toString().substring(0, sb.length() - 1);
126 | paramsMap.put(MediaHandler.Params.TASK_IDS, task_ids);
127 |
128 | Result result = null;
129 | try {
130 | result = handle.getStatus(paramsMap);
131 |
132 | } catch (IOException e) {
133 | e.printStackTrace();
134 | } catch (UpException e) {
135 | e.printStackTrace();
136 | }
137 |
138 | assertNotNull(result);
139 | assertTrue(result.isSucceed());
140 | assertNotNull(result.getMsg());
141 | }
142 |
143 |
144 | }
145 |
--------------------------------------------------------------------------------
/src/test/java/PullingTest.java:
--------------------------------------------------------------------------------
1 | import com.upyun.PullingHandler;
2 | import com.upyun.Result;
3 | import com.upyun.UpException;
4 | import org.json.JSONArray;
5 | import org.json.JSONObject;
6 | import org.junit.Test;
7 |
8 | import java.io.IOException;
9 | import java.util.HashMap;
10 | import java.util.Map;
11 |
12 | import static org.junit.Assert.assertNotNull;
13 | import static org.junit.Assert.assertTrue;
14 |
15 | public class PullingTest {
16 | private static final String BUCKET_NAME = "formtest";
17 | private static final String OPERATOR_NAME = "one";
18 | private static final String OPERATOR_PWD = "qwertyuiop";
19 |
20 |
21 | @Test
22 | public void testPulling() {
23 |
24 | PullingHandler handler = new PullingHandler(BUCKET_NAME, OPERATOR_NAME, OPERATOR_PWD);
25 |
26 | //初始化参数组 Map
27 | Map paramsMap = new HashMap();
28 |
29 | paramsMap.put(PullingHandler.Params.BUCKET_NAME, BUCKET_NAME);
30 | paramsMap.put(PullingHandler.Params.NOTIFY_URL, "http://httpbin.org/post");
31 | paramsMap.put(PullingHandler.Params.APP_NAME, "spiderman");
32 |
33 | //已json格式生成任务信息
34 | JSONArray array = new JSONArray();
35 | JSONObject json = new JSONObject();
36 |
37 | //添加处理参数
38 | json.put(PullingHandler.Params.URL, "http://formtest.b0.upaiyun.com/sample.jpeg");
39 | json.put(PullingHandler.Params.RANDOM, false);
40 | json.put(PullingHandler.Params.OVERWRITE, true);
41 | json.put(PullingHandler.Params.X_GMKERL_THUMB, "/watermark/text/5L2g5aW977yB");
42 | json.put(PullingHandler.Params.SAVE_AS, "/result/pulling/a.jpg");
43 |
44 | JSONObject json2 = new JSONObject();
45 |
46 | //添加处理参数
47 | json2.put(PullingHandler.Params.URL, "http://formtest.b0.upaiyun.com/sample.jpeg");
48 | json2.put(PullingHandler.Params.RANDOM, false);
49 | json2.put(PullingHandler.Params.OVERWRITE, true);
50 | json2.put(PullingHandler.Params.X_GMKERL_THUMB, "/fw/300/unsharp/true/quality/80/format/png");
51 | json2.put(PullingHandler.Params.SAVE_AS, "/result/pulling/b.jpg");
52 |
53 | array.put(json2);
54 | array.put(json);
55 |
56 | //添加任务信息
57 | paramsMap.put(PullingHandler.Params.TASKS, array);
58 |
59 | try {
60 | Result result = handler.process(paramsMap);
61 |
62 | assertNotNull(result);
63 | assertTrue(result.isSucceed());
64 | assertNotNull(result.getMsg());
65 |
66 | String[] ids = handler.getTaskId(result.getMsg());
67 | assertNotNull(ids);
68 |
69 | } catch (IOException e) {
70 | e.printStackTrace();
71 | } catch (UpException e) {
72 | e.printStackTrace();
73 | }
74 |
75 | }
76 | }
77 |
--------------------------------------------------------------------------------
/src/test/java/ResumeTest.java:
--------------------------------------------------------------------------------
1 | import com.upyun.SerialUploader;
2 | import com.upyun.UpException;
3 | import org.junit.Assert;
4 | import org.junit.Test;
5 |
6 | import java.io.IOException;
7 | import java.util.concurrent.CountDownLatch;
8 |
9 | public class ResumeTest {
10 | private static final String BUCKET_NAME = "formtest";
11 | private static final String OPERATOR_NAME = "one";
12 | private static final String OPERATOR_PWD = "qwertyuiop";
13 |
14 |
15 | //上传测试文件
16 | private static final String SAMPLE_PIC_FILE = System.getProperty("user.dir") + "/test.MOV";
17 |
18 | //上传至空间路径
19 | private static final String UPLOAD_PATH = "/test.MOV";
20 |
21 | @Test
22 | public void testResumeUpload() throws InterruptedException, IOException, UpException {
23 |
24 | final SerialUploader resume = new SerialUploader(BUCKET_NAME, OPERATOR_NAME, OPERATOR_PWD);
25 | final CountDownLatch latch = new CountDownLatch(1);
26 |
27 | //设置上传进度监听
28 | resume.setOnProgressListener(new SerialUploader.OnProgressListener() {
29 | public void onProgress(int index, int total) {
30 | Assert.assertTrue(index <= total);
31 | System.out.println(index + "::" + total + "::" + index * 100 / total + "%");
32 | }
33 | });
34 |
35 | //设置 MD5 校验
36 | resume.setCheckMD5(true);
37 |
38 | resume.upload(SAMPLE_PIC_FILE, UPLOAD_PATH, null);
39 |
40 | // new Thread() {
41 | // @Override
42 | // public void run() {
43 | // super.run();
44 | // //开始上传
45 | // try {
46 | // Assert.assertFalse(resume.upload(SAMPLE_PIC_FILE, UPLOAD_PATH, null));
47 | // latch.countDown();
48 | // } catch (Exception e) {
49 | // System.out.println(e);
50 | // }
51 | // }
52 | // }.start();
53 |
54 | // Thread.sleep(2000);
55 | //
56 | // resume.interrupt(new SerialUploader.OnInterruptListener() {
57 | // public void OnInterrupt(boolean interrupted) {
58 | //
59 | // System.out.println("interrupted:" + interrupted);
60 | // if (interrupted) {
61 | // try {
62 | // Assert.assertTrue(resume.upload(SAMPLE_PIC_FILE, UPLOAD_PATH, null));
63 | // } catch (IOException e) {
64 | // Assert.fail();
65 | // } catch (UpException e) {
66 | // Assert.fail();
67 | // }
68 | // }
69 | // }
70 | // });
71 | //
72 | // latch.await();
73 | }
74 |
75 | }
76 |
--------------------------------------------------------------------------------
/src/test/java/TestFileBucket.java:
--------------------------------------------------------------------------------
1 | //import com.UpYun;
2 | //import com.upyun.UpException;
3 | //import org.junit.Assert;
4 | //import org.junit.Test;
5 | //
6 | //import java.io.File;
7 | //import java.io.IOException;
8 | //import java.util.HashMap;
9 | //import java.util.List;
10 | //import java.util.Map;
11 | //
12 | //import static org.junit.Assert.assertTrue;
13 | //
14 | //
15 | ////请求太频繁容易失败 影响 maven 上传 注释之
16 | //public class TestFileBucket {
17 | //
18 | // private static final String BUCKET_NAME = "sdkimg";
19 | // private static final String OPERATOR_NAME = "tester";
20 | // private static final String OPERATOR_PWD = "grjxv2mxELR3";
21 | //
22 | // private UpYun upyun = new UpYun(BUCKET_NAME, OPERATOR_NAME, OPERATOR_PWD);
23 | //
24 | // /**
25 | // * 根目录
26 | // */
27 | // private static final String DIR_ROOT = "/";
28 | // /**
29 | // * 多级目录
30 | // */
31 | // private static final String DIR_MORE = "/1/2/3/";
32 | // /**
33 | // * 目录名
34 | // */
35 | // private static final String FOLDER_NAME = "tmp";
36 | // /**
37 | // * 上传到upyun的文件名
38 | // */
39 | // private static final String FILE_NAME = "test.txt";
40 | // /**
41 | // * 本地待上传的测试文件
42 | // */
43 | // private static final String SAMPLE_TXT_FILE = System.getProperty("user.dir") + "/test.txt";
44 | //
45 | // private static final String content = "tmp content";
46 | //
47 | //
48 | // //创建目录测试
49 | // @Test
50 | // public void testMkDir() throws IOException, UpException {
51 | // // 方法1:创建一级目录
52 | // String dir1 = DIR_ROOT + FOLDER_NAME;
53 | //
54 | // boolean result1 = upyun.mkDir(dir1);
55 | // assertTrue(result1);
56 | //
57 | // // 方法2:创建多级目录,自动创建父级目录(最多10级)
58 | // String dir2 = DIR_MORE + FOLDER_NAME;
59 | //
60 | // boolean result2 = upyun.mkDir(dir2, true);
61 | // assertTrue(result2);
62 | // }
63 | //
64 | // //上传普通文件测试
65 | // @Test
66 | // public void testWriteFile() throws IOException, UpException {
67 | // // 保存在又拍云的文件路径
68 | // String filePath = DIR_ROOT + FILE_NAME;
69 | // // 保存在又拍云的文件路径:多级目录
70 | // String filePath2 = DIR_MORE + FILE_NAME;
71 | //
72 | // /*
73 | // * 上传方法1:文本内容直接上传
74 | // */
75 | // boolean result1 = upyun.writeFile(filePath, content);
76 | // assertTrue(result1);
77 | //
78 | // /*
79 | // * 上传方法2:文本内容直接上传,可自动创建父级目录(最多10级)
80 | // */
81 | // boolean result2 = upyun.writeFile(filePath2, content, true);
82 | // assertTrue(result2);
83 | //
84 | // /*
85 | // * 上传方法3:采用数据流模式上传文件(节省内存),可自动创建父级目录(最多10级)
86 | // */
87 | // File file = new File(SAMPLE_TXT_FILE);
88 | // boolean result3 = upyun.writeFile(filePath, file, true);
89 | // assertTrue(result3);
90 | //
91 | // /*
92 | // * 上传方法4:对待上传的文件设置 MD5 值,确保上传到 Upyun 的文件的完整性和正确性
93 | // */
94 | // File file4 = new File(SAMPLE_TXT_FILE);
95 | // // 设置待上传文件的 Content-MD5 值
96 | // // 如果又拍云服务端收到的文件MD5值与用户设置的不一致,将回报 406 NotAcceptable 错误
97 | // upyun.setContentMD5(UpYun.md5(file4));
98 | //
99 | // boolean result4 = upyun.writeFile(filePath, file4, true);
100 | // assertTrue(result4);
101 | //
102 | // }
103 | //
104 | // //获取文件信息测试
105 | // @Test
106 | // public void testGetFileInfo() throws IOException, UpException {
107 | // // upyun空间下存在的文件的路径
108 | // String filePath = DIR_ROOT + FILE_NAME;
109 | //
110 | // Map result = upyun.getFileInfo(filePath);
111 | // Assert.assertNotNull(result);
112 | // }
113 | //
114 | // //读取目录文件列表测试
115 | // @Test
116 | // public void testReadDir() throws IOException, UpException {
117 | //
118 | // // 参数可以换成其他目录路径
119 | // String dirPath = DIR_ROOT;
120 | //
121 | // // 读取目录列表,将返回 List 或 NULL
122 | // Map params = new HashMap();
123 | //
124 | // params.put(UpYun.PARAMS.KEY_X_LIST_LIMIT.getValue(), "10");
125 | // List items = upyun.readDir(dirPath, params);
126 | // UpYun.FolderItemIter folderItemIter = upyun.readDirIter(dirPath, params);
127 | // String json = upyun.readDirJson(dirPath, params);
128 | // assertTrue(items.size() > 0);
129 | // }
130 | //
131 | // //获取空间使用量测试
132 | // @Test
133 | // public void testGetBucketUsage() throws IOException, UpException {
134 | // long usage = upyun.getBucketUsage();
135 | //
136 | // assertTrue(usage > 0);
137 | // }
138 | //
139 | // //获取目录大小信息测试
140 | // @Test
141 | // public void testGetFolderUsage() throws IOException, UpException {
142 | // // 带查询的目录,如 "/" 或 "/tmp"
143 | // String dirPath = DIR_ROOT;
144 | //
145 | // long usage = upyun.getFolderUsage(dirPath);
146 | //
147 | // assertTrue(usage > 0);
148 | // }
149 | //
150 | // //读取文件测试
151 | // @Test
152 | // public void testReadFile() throws IOException, UpException {
153 | // // upyun空间下存在的文件的路径
154 | // String filePath = DIR_ROOT + FILE_NAME;
155 | //
156 | // /*
157 | // * 方法1:直接读取文本内容
158 | // */
159 | // String datas = upyun.readFile(filePath);
160 | // assertTrue(content.equals(datas));
161 | //
162 | // /*
163 | // * 方法2:下载文件,采用数据流模式下载文件(节省内存)
164 | // */
165 | // // 要写入的本地临时文件
166 | // File file = File.createTempFile("upyunTempFile_", "");
167 | //
168 | // // 把upyun空间下的文件下载到本地的临时文件
169 | // boolean result = upyun.readFile(filePath, file);
170 | // assertTrue(result);
171 | // }
172 | //
173 | // //删除文件测试
174 | // @Test
175 | // public void testDeleteFile() throws IOException, UpException {
176 | // // upyun空间下存在的文件的路径
177 | // String filePath = DIR_ROOT + FILE_NAME;
178 | //
179 | // // 删除文件
180 | // boolean result = upyun.deleteFile(filePath, null);
181 | //
182 | // assertTrue(result);
183 | // }
184 | //
185 | // //删除目录测试
186 | // @Test
187 | // public void testRmDir() throws IOException, UpException {
188 | // // 带删除的目录必须存在,并且目录下已不存在任何文件或子目录
189 | // String dirPath = DIR_MORE + FOLDER_NAME;
190 | //
191 | // boolean result = upyun.rmDir(dirPath);
192 | //
193 | // assertTrue(result);
194 | // }
195 | //
196 | // //复制文件测试
197 | // @Test
198 | // public void testCopyFile() throws IOException, UpException {
199 | // String filePath = DIR_ROOT + FILE_NAME;
200 | //
201 | // boolean result = upyun.copyFile("/test.aa", "/" + BUCKET_NAME + filePath);
202 | //
203 | // assertTrue(result);
204 | // }
205 | //
206 | // //移动文件测试
207 | // @Test
208 | // public void testMoveFile() throws IOException, UpException {
209 | // String filePath = DIR_ROOT + FILE_NAME;
210 | //
211 | // boolean result = upyun.moveFile("/test.aa", "/" + BUCKET_NAME + filePath);
212 | //
213 | // assertTrue(result);
214 | // }
215 | //}
216 |
--------------------------------------------------------------------------------
/src/test/java/TestPicBucket.java:
--------------------------------------------------------------------------------
1 | import com.upyun.RestManager;
2 | import com.upyun.RestManager.PARAMS;
3 | import com.upyun.UpException;
4 | import com.upyun.UpYunUtils;
5 | import okhttp3.Response;
6 | import org.junit.Test;
7 |
8 | import java.io.File;
9 | import java.io.IOException;
10 | import java.util.HashMap;
11 | import java.util.Map;
12 |
13 | import static org.junit.Assert.assertTrue;
14 |
15 | public class TestPicBucket {
16 | // 运行前先设置好以下三个参数
17 | private static final String BUCKET_NAME = "sdkimg";
18 | private static final String OPERATOR_NAME = "tester";
19 | private static final String OPERATOR_PWD = "grjxv2mxELR3";
20 |
21 | /**
22 | * 根目录
23 | */
24 | private static final String DIR_ROOT = "/";
25 |
26 | /**
27 | * 上传到upyun的图片名
28 | */
29 | private static final String PIC_NAME = "sample.aaa";
30 |
31 | /**
32 | * 本地待上传的测试文件
33 | */
34 | private static final String SAMPLE_PIC_FILE = System
35 | .getProperty("user.dir") + "/sample.jpeg";
36 | RestManager restManager = new RestManager(BUCKET_NAME, OPERATOR_NAME, OPERATOR_PWD);
37 |
38 | // 测试图片文件测试
39 | @Test
40 | public void testWritePic() throws IOException, UpException {
41 |
42 | // 要传到upyun后的文件路径
43 | String filePath = DIR_ROOT + PIC_NAME;
44 |
45 | // 本地待上传的图片文件
46 | File file = new File(SAMPLE_PIC_FILE);
47 |
48 | Map params = new HashMap();
49 | // 设置待上传文件的 Content-MD5 值
50 | // 如果又拍云服务端收到的文件MD5值与用户设置的不一致,将回报 406 NotAcceptable 错误
51 | params.put(PARAMS.CONTENT_MD5.getValue(), UpYunUtils.md5(file, 1024));
52 |
53 | // 设置待上传文件的"访问密钥"
54 | // 注意:
55 | // 仅支持图片空!,设置密钥后,无法根据原文件URL直接访问,需带URL后面加上(缩略图间隔标志符+密钥)进行访问
56 | // 举例:
57 | // 如果缩略图间隔标志符为"!",密钥为"bac",上传文件路径为"/folder/test.jpg",
58 | // 那么该图片的对外访问地址为:http://空间域名 /folder/test.jpg!bac
59 | params.put(PARAMS.CONTENT_SECRET.getValue(), "bac");
60 |
61 | //图片预处理参数
62 | params.put(PARAMS.X_GMKERL_THUMB.getValue(),
63 | "/fw/300/unsharp/true/rotate/90");
64 |
65 | // 上传文件
66 | Response response = restManager.writeFile(filePath, file, params);
67 | assertTrue(response.isSuccessful());
68 |
69 | }
70 | }
71 |
--------------------------------------------------------------------------------
/src/test/java/TestRestManager.java:
--------------------------------------------------------------------------------
1 | import com.UpYun;
2 | import com.upyun.RestManager;
3 | import com.upyun.UpException;
4 | import okhttp3.Response;
5 | import org.junit.Assert;
6 | import org.junit.Test;
7 |
8 | import java.io.File;
9 | import java.io.FileInputStream;
10 | import java.io.IOException;
11 | import java.util.HashMap;
12 | import java.util.List;
13 | import java.util.Map;
14 |
15 | import static org.junit.Assert.assertTrue;
16 |
17 |
18 | public class TestRestManager {
19 |
20 | private static final String BUCKET_NAME = "sdkimg";
21 | private static final String OPERATOR_NAME = "tester";
22 | private static final String OPERATOR_PWD = "grjxv2mxELR3";
23 |
24 | private RestManager restManager = new RestManager(BUCKET_NAME, OPERATOR_NAME, OPERATOR_PWD);
25 |
26 | /**
27 | * 根目录
28 | */
29 | private static final String DIR_ROOT = "/";
30 | /**
31 | * 多级目录
32 | */
33 | private static final String DIR_MORE = "/1/2/3/";
34 | /**
35 | * 目录名
36 | */
37 | private static final String FOLDER_NAME = "tmp";
38 | /**
39 | * 上传到upyun的文件名
40 | */
41 | private static final String FILE_NAME = "test.txt";
42 | /**
43 | * 本地待上传的测试文件
44 | */
45 | private static final String SAMPLE_TXT_FILE = System.getProperty("user.dir") + "/test.txt";
46 |
47 | /**
48 | * 获取空间占用大小
49 | */
50 | @Test
51 | public void testGetBucketUsage() throws IOException, UpException {
52 |
53 | Response response = restManager.getBucketUsage();
54 |
55 | System.out.println("空间总使用量:" + response.body().string() + "B");
56 | System.out.println();
57 | }
58 |
59 | /**
60 | * 上传文件
61 | *
62 | * @throws IOException
63 | */
64 | @Test
65 | public void testWriteFile() throws IOException, UpException {
66 |
67 | // 要上传的纯文字内容
68 | String content = "test content";
69 |
70 | // 要传到upyun后的文件路径
71 | String filePath = DIR_ROOT + FILE_NAME;
72 | // 要传到upyun后的文件路径:多级目录
73 | String filePath2 = DIR_MORE + FILE_NAME;
74 | String filePath3 = DIR_MORE + "test3.txt";
75 |
76 | /*
77 | * 上传方法1:上传 byte[]
78 | */
79 | Response response = restManager.writeFile(filePath, content.getBytes(), null);
80 | System.out.println("1.上传 " + filePath + isSuccess(response));
81 |
82 |
83 | /*
84 | * 上传方法2:上传文件
85 | */
86 | File file = new File(SAMPLE_TXT_FILE);
87 | Response response2 = restManager.writeFile(filePath2, file, null);
88 | System.out.println("2.上传 " + filePath2 + isSuccess(response2));
89 |
90 | /*
91 | * 上传方法3:上传流
92 | */
93 | File file2 = new File(SAMPLE_TXT_FILE);
94 | Response response3 = restManager.writeFile(filePath3, new FileInputStream(file2), null);
95 | System.out.println("3.上传 " + filePath3 + isSuccess(response3));
96 | }
97 |
98 | /**
99 | * 获取文件信息
100 | */
101 | @Test
102 | public void testGetFileInfo() throws IOException, UpException {
103 |
104 | // upyun空间下存在的文件的路径
105 | String filePath = DIR_MORE + "test3.txt";
106 |
107 | System.out.println(filePath + " 的文件信息:" + restManager.getFileInfo(filePath).headers());
108 | System.out.println();
109 | }
110 |
111 | /**
112 | * 读取文件/下载文件
113 | *
114 | * @throws IOException
115 | */
116 | @Test
117 | public void testReadFile() throws IOException, UpException {
118 |
119 | // upyun空间下存在的文件的路径
120 | String filePath = DIR_ROOT + FILE_NAME;
121 |
122 | /*
123 | * 下载文件
124 | */
125 | Response response = restManager.readFile(filePath);
126 | System.out.println(filePath + " 的文件内容:" + response.body().string());
127 | }
128 |
129 | /**
130 | * 删除文件
131 | */
132 | @Test
133 | public void testDeleteFile() throws IOException, UpException {
134 |
135 | // upyun空间下存在的文件的路径
136 | String filePath = DIR_ROOT + FILE_NAME;
137 |
138 | // 删除文件
139 | Response response = restManager.deleteFile(filePath, null);
140 |
141 | System.out.println(filePath + " 删除" + isSuccess(response));
142 | System.out.println();
143 | }
144 |
145 | /**
146 | * 创建目录
147 | */
148 | @Test
149 | public void testMkDir() throws IOException, UpException {
150 | String dir1 = DIR_ROOT + FOLDER_NAME;
151 | Response response = restManager.mkDir(dir1);
152 | System.out.println("创建目录:" + dir1 + isSuccess(response));
153 |
154 |
155 | }
156 |
157 | /**
158 | * 删除目录
159 | */
160 | @Test
161 | public void testRmDir() throws IOException, UpException {
162 |
163 | // 带删除的目录必须存在,并且目录下已不存在任何文件或子目录
164 | String dirPath = DIR_ROOT + FOLDER_NAME;
165 | Response response = restManager.rmDir(dirPath);
166 | System.out.println("删除目录:" + dirPath + isSuccess(response));
167 | }
168 |
169 | /**
170 | * 读取目录下的文件列表
171 | */
172 | @Test
173 | public void testReadDir() throws IOException, UpException {
174 |
175 | // 参数可以换成其他目录路径
176 | String dirPath = DIR_ROOT;
177 |
178 | Map params = new HashMap();
179 |
180 | params.put(UpYun.PARAMS.KEY_X_LIST_LIMIT.getValue(), "10");
181 |
182 | Response response = restManager.readDirIter(dirPath, params);
183 | System.out.println(response.body().string());
184 | }
185 |
186 |
187 | /**
188 | * 复制文件
189 | *
190 | * @throws IOException
191 | * @throws UpException
192 | */
193 | @Test
194 | public void testCopyFile() throws IOException, UpException {
195 | String sourcePath = "/" + BUCKET_NAME + DIR_ROOT + FILE_NAME;
196 | Response response = restManager.copyFile("/copy.txt", sourcePath, null);
197 | System.out.println("复制文件:" + sourcePath + isSuccess(response));
198 | }
199 |
200 | /**
201 | * 移动文件
202 | *
203 | * @throws IOException
204 | * @throws UpException
205 | */
206 | @Test
207 | public void testMoveFile() throws IOException, UpException {
208 | String sourcePath = "/" + BUCKET_NAME + DIR_MORE + FILE_NAME;
209 | Response response = restManager.moveFile("/move.txt", sourcePath, null);
210 | System.out.println("移动文件:" + sourcePath + isSuccess(response));
211 | }
212 |
213 | private String isSuccess(Response response) {
214 | return response.isSuccessful() ? " 成功" : " 失败";
215 | }
216 | }
--------------------------------------------------------------------------------
/test.MOV:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/upyun/java-sdk/75fdd4538da12d5cf7f8c65fb7edeca6f4d47829/test.MOV
--------------------------------------------------------------------------------
/test.mp4:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/upyun/java-sdk/75fdd4538da12d5cf7f8c65fb7edeca6f4d47829/test.mp4
--------------------------------------------------------------------------------
/test.txt:
--------------------------------------------------------------------------------
1 | tmp content
--------------------------------------------------------------------------------