package ;/**
* Created by TongGuoBo on 2019/6/14.
*/
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import .*;
import ;
import ;
import ;
import ;
/**
* @ClassName Examples
* @Description TODO
* @Author TongGuoBo
* @Date 2019/6/14 8:55
**/
public class Examples {
private static final String ACCESS_KEY = "your_access_key";
private static final String ACCESS_SECRET = "your_access_secret";
public static final String PROTOCOL = "https";
public static final String HOST = "";
public static void main(String... args) {
Examples examples = new Examples();
EnvContext context = new EnvContext(ACCESS_KEY, ACCESS_SECRET);
(PROTOCOL);
(HOST);
(QSConstant.PATH_STYLE);
String zoneKey = "pek3b";
String bucketName = "test-in-2018-08-08-by-chengww";
Bucket bucket = new Bucket(context, zoneKey, bucketName);
(bucket, bucketName);
}
public void testAll(Bucket bucket, String bucketName) {
long start = ();
try {
// Create a new Bucket
output = ();
if (() == 201) {
("Put Bucket OK");
headBucket(bucket);
putBucketACL(bucket);
getBucketACL(bucket);
putBucketPolicy(bucket, bucketName);
getBucketPolicy(bucket);
deleteBucketPolicy(bucket);
putBucketCORS(bucket);
getBucketCORS(bucket);
deleteBucketCORS(bucket);
putBucketExternalMirror(bucket);
getBucketExternalMirror(bucket);
deleteBucketExternalMirror(bucket);
putBucketNotification(bucket);
getBucketNotification(bucket);
deleteBucketNotification(bucket);
putBucketLifecycle(bucket);
getBucketLifecycle(bucket);
deleteBucketLifecycle(bucket);
String uploadFileName = "";
try {
putObject(bucket, "folder/" + uploadFileName, "/Users/chengww/Downloads/vpn/" + uploadFileName);
} catch (FileNotFoundException e) {
();
}
String multiPartUploadFileName = "";
String filePath = "/Users/chengww/Downloads/backup/";
putObjectAuto(bucket, filePath);
getObject(bucket, "folder/" + uploadFileName, "/Users/chengww/Desktop/");
putObjectCopy(bucket, "/" + bucketName + "/folder/" + uploadFileName, "folder-copied/" + uploadFileName);
putObjectMove(bucket, "/" + bucketName + "/folder/" + uploadFileName, "folder-moved/" + uploadFileName);
putObjectFetch(bucket, "/static/assets/images/icons/common/footer_logo.svg", "folder-fetched/qingcloud_footer_logo.svg");
headObject(bucket, "folder-copied/" + uploadFileName);
optionsObject(bucket, "folder-copied/" + uploadFileName);
listObjects(bucket, null, null);
listMultipartUploads(bucket);
getBucketStatistics(bucket);
deleteObject(bucket, "folder-copied/" + uploadFileName);
List<String> objectKeys = new ArrayList<>();
(multiPartUploadFileName);
("folder-moved/" + uploadFileName);
("folder-fetched/qingcloud_footer_logo.svg");
deleteMultpieObjects(bucket, objectKeys);
deleteBucket(bucket);
} else {
handleError(output);
}
} catch (QSException e) {
();
}
("End: Time = " + (() - start) + " ms");
}
/**
* Delete Multpie Objects once
*
* @param bucket bucket
* @param objectKeys a string list of the objectKey
* objectKey looks like this: "folder/fileName".<br/>
* If objectKey = "fileName", means the object is in the bucket's root folder.
* @throws QSException exception will be thrown if (objectKeys == null || () < 1)
*/
public void deleteMultpieObjects(Bucket bucket, List<String> objectKeys) throws QSException {
if (objectKeys == null || () < 1) {
throw new QSException("ObjectKeys list must contains at least one key.");
}
deleteInput = new ();
List<> keyList = new ArrayList<>();
for (String key : objectKeys) {
keyModel = new ();
(key);
(keyModel);
}
(keyList);
output = (deleteInput);
if (() == 200 || () == 204) {
// Deleted
("Delete Multpie Objects: Deleted.");
("Delete Multpie Objects: Keys = \n" + new Gson().toJson(keyList));
} else {
// Failed
("Failed to delete multpie objects.");
handleError(output);
}
}
/**
* Delete Object
*
* @param bucket bucket
* @param objectKey looks like this: "folder/fileName".<br/>
* If objectKey = "fileName", means the object is in the bucket's root folder.
*/
public void deleteObject(Bucket bucket, String objectKey) {
try {
output = (objectKey);
if (() == 204) {
// Deleted
("Delete Object: Deleted. ");
("Delete Object: Object key = " + objectKey);
} else {
// Failed
("Failed to delete " + objectKey);
("StatueCode = " + ());
("Message = " + ());
("RequestId = " + ());
("Code = " + ());
("Url = " + ());
}
} catch (QSException e) {
();
}
}
/**
* Head Object
*
* @param bucket bucket
* @param objectKey looks like this: "folder/fileName".<br/>
* If objectKey = "fileName", means the object is in the bucket's root folder.
*/
public void headObject(Bucket bucket, String objectKey) {
try {
input = new ();
output = (objectKey, input);
if (() == 200) {
("Head Object success.");
("ObjectKey = " + objectKey);
("ContentLength = " + ());
("ContentType = " + ());
("ETag = " + ());
("LastModified = " + ());
("XQSEncryptionCustomerAlgorithm = " + ());
("XQSStorageClass = " + ());
} else {
// Failed
("Head Object failed.");
("ObjectKey = " + objectKey);
handleError(output);
}
} catch (QSException e) {
();
}
}
/**
* Get(Download) an object from the bucket.
*
* @param bucket bucket
* @param objectKey looks like this: "folder/fileName".<br/>
* If objectKey = "fileName", means the object is in the bucket's root folder.
* @param localKeptPath the object will be kept in this path.
*/
public void getObject(Bucket bucket, String objectKey, String localKeptPath) {
try {
input = new ();
output = (objectKey, input);
InputStream inputStream = ();
if (() == 200) {
if (inputStream != null) {
FileOutputStream fos = new FileOutputStream(localKeptPath);
int len;
byte[] bytes = new byte[4096];
while ((len = (bytes)) != -1) {
(bytes, 0, len);
}
();
();
("Get object success.");
("ObjectKey = " + objectKey);
("LocalKeptPath = " + localKeptPath);
} else {
("Get object status code == 200, but inputStream is null, skipped.");
}
} else {
// Failed
("Failed to get object.");
handleError(output);
}
if (inputStream != null) ();
} catch (QSException | IOException e) {
();
}
}
public void putObjectMove(Bucket bucket, String moveSource, String newObjectKey) {
try {
input = new ();
(moveSource); // MoveSource looks like this: "/bucketName/folder/fileName"
output = (newObjectKey, input); // NewObjectKey looks like this: "folder-moved/fileName"
if (() == 201) {
// Created
("Put Object Move: Moved.");
("From " + moveSource + " to " + newObjectKey);
} else {
// Failed
("Put Object Move: Failed to move.");
("From " + moveSource + " to " + newObjectKey);
handleError(output);
}
} catch (QSException e) {
();
}
}
public void putObjectCopy(Bucket bucket, String copySource, String newObjectKey) {
try {
input = new ();
(copySource); // CopySource looks like this: "/bucketName/folder/fileName"
output = (newObjectKey, input); // NewObjectKey looks like this: "folder-copied/fileName"
if (() == 201) {
// Created
("Put Object Copy: Copied.");
("From " + copySource + " to " + newObjectKey);
} else {
// Failed
("Put Object Copy: Failed to copy.");
("From " + copySource + " to " + newObjectKey);
handleError(output);
}
} catch (QSException e) {
();
}
}
public void putObjectFetch(Bucket bucket, String fetchSource, String newObjectKey) {
try {
input = new ();
(fetchSource); // Fetch source looks like this: "protocol://host[:port]/[path]"
output = (newObjectKey, input); // NewObjectKey looks like this: "folder-fetched/fileName"
if (() == 201) {
// Success
("Put Object - Fetch success.");
("From " + fetchSource + " to " + newObjectKey);
} else {
// Failed
("Put Object - Fetch failed.");
("From " + fetchSource + " to " + newObjectKey);
handleError(output);
}
} catch (QSException e) {
();
}
}
/**
* Put a file to the bucket.
*
* @param bucket bucket
* @param objectKey looks like this: "folder/fileName".<br/>
* If objectKey = "fileName", we will put the object into the bucket's root.
* @param filePath local file path
* @throws FileNotFoundException if file does not exist, the exception will occurred.
*/
public void putObject(Bucket bucket, String objectKey, String filePath) throws FileNotFoundException {
File file = new File(filePath);
if (!() || ())
throw new FileNotFoundException("File does not exist or it is a directory.");
input = new ();
// Using the JDK1.7 self-bringing method to get content type(Requires JDK 1.7+, linux requires GLib.)
try {
String contentType = ((filePath));
(contentType);
("Put Object: ContentType = " + contentType);
} catch (IOException e) {
();
("Put Object: Get file's content type error.");
}
(());
(file);
try {
output = (objectKey, input);
if (() == 201) {
("PUT Object OK.");
("key = " + objectKey);
("path = " + filePath);
} else {
// Failed
("Failed to PUT object.");
("key = " + objectKey);
handleError(output);
}
} catch (QSException e) {
();
}
}
public void putObjectAuto(Bucket bucket, String filePath) {
UploadManager uploadManager = new UploadManager(bucket, null, new UploadProgressListener() {
@Override
public void onProgress(String objectKey, long currentSize, long totalSize) {
float progress = (float) currentSize * 100 / totalSize;
(objectKey + ": uploading = " + ("%.2f", progress) + " %");
}
}, null, new UploadManagerCallback() {
@Override
public void onAPIResponse(String objectKey, OutputModel output) {
if (() == 200 || () == 201) {
("Upload success.");
} else if (() == QSConstant.REQUEST_ERROR_CANCELLED) {
("Stopped.");
} else {
handleError(output);
}
}
});
try {
(new File(filePath));
} catch (QSException e) {
();
}
}
public void putBucketACL(Bucket bucket) {
try {
input = new ();
acl = new ();
("FULL_CONTROL");
gm = new ();
("QS_ALL_USERS");
("group");
(gm);
List<> lstACL = new ArrayList<>();
(acl);
(lstACL);
output = (input);
if (() == 200) {
("Put bucket ACL OK.");
} else {
// Failed
("Failed to put bucket ACL.");
handleError(output);
}
} catch (QSException e) {
();
}
}
/**
* List objects start with prefix(folderName), after a object named marker. Limit up to 100 data.
* 列取所有前缀为 prefix(folderName) ,在 marker 之后的对象。每次最多 100 条数据。
* @param bucket bucket
* @param prefix prefix(folderName)
* @param marker View the data on the next page. The marker is the value of next_marker returned by the last Response
* 查看下一页的数据。marker 为上一次 Response 返回的 next_marker 的值
* @return next_marker
*/
public String listObjects(Bucket bucket, String prefix, String marker) {
input = new ();
if (null != prefix && !"".equals(prefix)) {
// Only show objects name start with 'prefix'
(prefix);
}
if (null != marker && !"".equals(marker)) {
// Sort by name after a object named marker
(marker);
}
("/");
(100); // Default 200, max 1000
try {
output = (input);
if (() == 200) {
// Success
("List Objects success.");
("=======List Objects:Folders======");
List<String> commonPrefixes = ();
for (String folderName : commonPrefixes) {
("folderName = " + folderName);
}
("=======List Objects:Files======");
List<> keys = ();
if (keys != null && () > 0) {
("keys = " + new Gson().toJson(keys));
}
("=============");
return ();
} else {
// Failed
("List Objects failed.");
handleError(output);
}
} catch (QSException e) {
// NetWork exception
();
}
return null;
}
public void getBucketACL(Bucket bucket) {
try {
output = ();
if (() == 200) {
// Success
owner = ();
if (owner != null) {
("owner = {'name': " + () + ", 'ID': " + () + "}");
} else {
("owner = null");
}
("=======Get Bucket ACL======");
List<> acls = ();
if (acls != null && () > 0) {
("ACLs = " + new Gson().toJson(acls));
} else {
("ACLs is empty.");
}
("=============");
} else {
// Failed
("Failed to Get Bucket ACL.");
handleError(output);
}
} catch (QSException e) {
();
}
}
public void listMultipartUploads(Bucket bucket) {
try {
input = new ();
// See Request Parameters to set input
output = (input);
if (() == 200) {
// Success
("=======List Multipart Uploads======");
("Name = " + ());
List<> uploads = ();
if (uploads != null && () > 0) {
("Uploads = " + new Gson().toJson(uploads));
} else {
("Uploads is empty.");
}
("=============");
} else {
// Failed
("Failed to List Multipart Uploads.");
handleError(output);
}
} catch (QSException e) {
();
}
}
public void getBucketStatistics(Bucket bucket) {
try {
output = ();
if (() == 200) {
// Success
("Get Bucket Statistics success.");
("Name = " + ());
("Created = " + ());
("Location = " + ());
("Status = " + ());
("URL = " + ()); // The method is different of ().
("Count = " + ());
("Size = " + ());
} else {
// Failed
("Failed to Get Bucket Statistics.");
handleError(output);
}
} catch (QSException e) {
();
}
}
public void headBucket(Bucket bucket) {
try {
output = ();
if (() == 200) {
("Head Bucket success.");
// You can print http headers/parameters you defined here.
// See [Get/Set HTTP Headers/Parameters Of A Request](./get_set_http_headers.md)
("You can access the Bucket.");
("You can print http headers/parameters you defined here.");
} else {
// Failed
("Head Bucket: You cannot access the Bucket or it does not exist.");
handleError(output);
}
} catch (QSException e) {
();
}
}
public void deleteBucket(Bucket bucket) {
try {
output = ();
if (() == 204) {
// Deleted
("Delete Bucket: Deleted.");
} else {
// Failed
("Failed to Delete Bucket.");
handleError(output);
}
} catch (QSException e) {
();
}
}
public void putBucket(Bucket bucket) {
try {
output = ();
if (() == 201) {
// Created
("Put Bucket: Created.");
} else {
// Failed
("Failed to Put Bucket.");
handleError(output);
}
} catch (QSException e) {
();
}
}
public void deleteBucketPolicy(Bucket bucket) {
try {
output = ();
if (() == 204) {
("The policy of bucket deleted.");
} else {
// Failed
("Failed to delete bucket policy.");
handleError(output);
}
} catch (QSException e) {
();
}
}
public void getBucketPolicy(Bucket bucket) {
try {
output = ();
if (() == 200) {
("====Get Bucket Policy====");
List<> statements = ();
if (statements != null && () > 0) {
("Statements = " + new Gson().toJson(statements));
} else {
("Statement list is empty, Policy is empty.");
}
("========");
} else {
// Failed
("Failed to Get Bucket Policy.");
handleError(output);
}
} catch (QSException e) {
();
}
}
public void putBucketPolicy(Bucket bucket, String bucketName) {
try {
input = new ();
List<> statement = new ArrayList<>();
statementModel = new ();
// ID
("allow certain site to get objects");
// User
List<String> user = new ArrayList<>();
("*");
(user);
// Action
List<String> action = new ArrayList<>();
("get_object");
(action);
// Effect
("allow");
// Resource
List<String> resource = new ArrayList<>();
(bucketName + "/*");
(resource);
// Condition
conditionModel = new ();
stringLikeModel = new ();
List<String> referer = new ArrayList<>();
("*.");
("*.");
(referer);
(stringLikeModel);
(conditionModel);
(statementModel);
(statement);
output = (input);
if (() == 200) {
("PUT Bucket Policy OK.");
} else {
// Failed
("PUT Bucket Policy failed.");
handleError(output);
}
} catch (QSException e) {
();
}
}
public void deleteBucketCORS(Bucket bucket) {
try {
output = ();
if (() == 204) {
("Delete bucket CORS OK.");
} else {
// Failed
("Failed to delete bucket CORS.");
handleError(output);
}
} catch (QSException e) {
();
}
}
public void getBucketCORS(Bucket bucket) {
try {
output = ();
if (() == 200) {
("====Get Bucket CORS====");
List<> corsRules = ();
if (corsRules != null && () > 0) {
("CorsRules = " + new Gson().toJson(corsRules));
} else {
("CorsRules list is empty, CORS is empty.");
}
("========");
} else {
// Failed
("Failed to GET Bucket CORS.");
handleError(output);
}
} catch (QSException e) {
();
}
}
public void putBucketCORS(Bucket bucket) {
input = new ();
List<> corsRuleModels = new ArrayList<>();
corsRuleModel = new ();
// Allowed_origin
("http://*.");
// Allowed_methods
List<String> allowed_methods = new ArrayList<>();
allowed_methods.add("PUT");
allowed_methods.add("GET");
allowed_methods.add("DELETE");
allowed_methods.add("POST");
(allowed_methods);
// Allowed_headers
List<String> allowed_headers = new ArrayList<>();
allowed_headers.add("x-qs-date");
allowed_headers.add("Content-Type");
allowed_headers.add("Content-MD5");
allowed_headers.add("Authorization");
(allowed_headers);
// Max_age_seconds
(200);
// Expose_headers
List<String> expose_headers = new ArrayList<>();
expose_headers.add("x-qs-date");
(expose_headers);
(corsRuleModel);
(corsRuleModels);
try {
output = (input);
if (() == 200) {
("PUT Bucket CORS OK.");
} else {
// Failed
("PUT Bucket CORS failed.");
handleError(output);
}
} catch (QSException e) {
();
}
}
public void deleteBucketLifecycle(Bucket bucket) {
try {
output = ();
if (() == 204) {
("Delete bucket lifecycle OK.");
} else {
// Failed
("Failed to delete bucket lifecycle.");
handleError(output);
}
} catch (QSException e) {
();
}
}
public void getBucketLifecycle(Bucket bucket) {
try {
output = ();
if (() == 200) {
("======GET Bucket Lifecycle=======");
List<> rules = ();
if (rules != null && () > 0) {
("Rules = " + new Gson().toJson(rules));
} else {
("GET Bucket Lifecycle: Rules is empty.");
}
("=============");
} else {
// Failed
("Failed to GET Bucket Lifecycle.");
handleError(output);
}
} catch (QSException e) {
();
}
}
public void putBucketLifecycle(Bucket bucket) {
input = new ();
List<> rules = new ArrayList<>();
rule = new ();
// ID
("delete-logs");
// Status
("enabled");
// Filter
filter = new ();
("logs/");
(filter);
// Expiration
expiration = new ();
(180);
(expiration);
(rule);
(rules);
try {
output = (input);
if (() == 200) {
("Put bucket lifecycle OK.");
} else {
// Failed
("Failed to put bucket lifecycle.");
handleError(output);
}
} catch (QSException e) {
();
}
}
public void deleteBucketNotification(Bucket bucket) {
try {
output = ();
if (() == 204) {
("The notification of bucket deleted.");
} else {
// Failed
("Failed to delete bucket notification.");
handleError(output);
}
} catch (QSException e) {
();
}
}
public void getBucketNotification(Bucket bucket) {
try {
output = ();
if (() == 200) {
("=======GET Bucket Notification======");
List<> notifications = ();
if (notifications != null && () > 0) {
("Notifications = " + new Gson().toJson(notifications));
} else {
("GET Bucket Notification: Notifications is empty.");
}
("=============");
} else {
// Failed
("Failed to GET Bucket Notification.");
handleError(output);
}
} catch (QSException e) {
();
}
}
public void putBucketNotification(Bucket bucket) {
input = new ();
List<> notifications = new ArrayList<>();
notification = new ();
// Cloudfunc
("tupu-porn");
// EventTypes
List<String> eventTypes = new ArrayList<>();
("create_object");
(eventTypes);
// ID
("notification-1");
// ObjectFilters: List or String
List<String> objectFilters = new ArrayList<>();
("*");
("test_classes");
(objectFilters);
// NotifyURL
("http://user_notify_url");
(notification);
(notifications);
try {
output = (input);
if (() == 200 || () == 201) {
("Put bucket notification OK.");
} else {
// Failed
("Failed to put bucket notification.");
handleError(output);
}
} catch (QSException e) {
();
}
}
public void deleteBucketExternalMirror(Bucket bucket) {
try {
output = ();
if (() == 204) {
("Delete bucket external mirror OK.");
} else {
// Failed
("Failed to delete bucket external mirror.");
handleError(output);
}
} catch (QSException e) {
();
}
}
public void getBucketExternalMirror(Bucket bucket) {
try {
output = ();
if (() == 200) {
String sourceSite = ();
("GET Bucket External Mirror: SourceSite = " + sourceSite);
} else {
// Failed
("Failed to GET Bucket External Mirror.");
handleError(output);
}
} catch (QSException e) {
();
}
}
public void putBucketExternalMirror(Bucket bucket) {
input = new ();
(":80/image/");
try {
output = (input);
if (() == 200) {
("PUT Bucket External Mirror OK.");
} else {
// Failed
("Failed to PUT Bucket External Mirror.");
handleError(output);
}
} catch (QSException e) {
();
}
}
/**
* Options Object
*
* @param bucket bucket
* @param objectKey looks like this: "folder/fileName".<br/>
* If objectKey = "fileName", means the object is in the bucket's root folder.
*/
public void optionsObject(Bucket bucket, String objectKey) {
try {
input = new ();
("Origin");
("<http-method>");
("<request-header>");
output = (objectKey, input);
if (() == 200) {
// Success
("Options Object success.");
("AccessControlAllowOrigin = " + ());
("AccessControlMaxAge = " + ());
("AccessControlAllowMethods = " + ());
("AccessControlAllowHeaders = " + ());
("AccessControlExposeHeaders = " + ());
} else {
// Failed
("Failed to Options Object.");
handleError(output);
}
} catch (QSException e) {
();
}
}
public void handleError(OutputModel output) {
if (output == null) return;
("StatusCode = " + ());
("Message = " + ());
("RequestId = " + ());
("Code = " + ());
("Url = " + ());
}
private void listBuckets(EnvContext context) {
QingStor stor = new QingStor(context);
try {
output = (null);
if (() == 200) {
("Count = " + ());
List<> buckets = ();
("buckets = " + new Gson().toJson(buckets));
} else {
handleError(output);
}
} catch (QSException e) {
();
}
}
}