Overview

AppGallery Connect Cloud Storage is scalable and maintenance-free. When the Cloud Storage SDK is integrated, it provides you with the functions such as storage instance management, file management, and file metadata management.

What You Will Create

In this codelab, you will create a server-side app that integrates Cloud Storage capabilities. Your app will allow users to upload a file to the cloud and download it to a local path by calling APIs.

What You Will Learn

Development Environment and Skill Requirements

Device Requirements

To integrate Cloud Storage of AppGallery Connect, you must complete the following preparations:

For details, please refer to Integration Preparations.

Enabling Cloud Storage

Before integrating the Cloud Storage SDK, you need to enable Cloud Storage in AppGallery Connect.

  1. Sign in to AppGallery Connect and click My projects.
  2. Click the project for which you need to enable Cloud Storage.
  3. Go to Build > Cloud Storage. On the Cloud Storage page, click Enable now.
  4. Enter the storage instance name and select the default data processing location.
  5. Click Next. The Define security rules page is displayed by default.
  6. Click Finish.
    When the service is enabled, AppGallery Connect creates a default storage instance for you, and its name is in the format Storage instance name entered in step4-Five random digits and letters.

Integrating the Cloud Storage SDK

If you are using Java development environment, you need to integrate the Cloud Storage SDK into your Java SDK project before development.

  1. Sign in to AppGallery Connect and click My projects.
  2. Find and click your project.
  3. Go to Project settings > Server SDK. Create and download the API authentication credential.
  4. Change the authentication credential file name and copy the authentication credential to the project directory.

The Cloud Storage Java Server SDK is released in the Maven repository. You need to add the Maven repository address and Cloud Storage SDK dependency to the pom.xml file.

  1. Find the pom.xml file in the project and add the Maven repository address to it.
    <repositories> <repository> <id>sz-maven-public</id> <name>sz-maven-public</name> <url>https://developer.huawei.com/repo/</url> </repository> </repositories>
  2. Add the dependency of the Cloud Storage SDK.
    <dependency> <groupId>com.huawei.agconnect.server</groupId> <artifactId>agconnect-storage</artifactId> <version>1.2.0.300</version> </dependency>
  3. Use the downloaded authentication credential to initialize the SDK.
    public static String BUCKET_NAME = "your bucket name"; CredentialService credential = CredentialParser.toCredential(path + "agc-apiclient-xxxxx-xxxxx.json"); AGCParameter agcParameter = AGCParameter.builder().setCredential(credential).build(); // Initialize a client whose name is clientName and the region code is CN. Use clientName to obtain AGCClient.initialize("agcClient", agcParameter, "CN");

You can call related APIs of the Cloud Storage SDK to develop functions.

Initializing the Instances

Before using Cloud Storage APIs, you need to initialize the cloud storage instance and file instance as required. To obtain the storage instance name, sign in to AppGallery Connect, go to Build > Cloud Storage, and check the value of Storage instance.

// Initialize multiple storage locations. For details, please refer to the AGCClient API reference. StorageManagement storageManagement = AGCStorageManagement.getInstance(AGCClient.getInstance("agcClient"), "cn-north-4", BUCKET_NAME);

Uploading a File

Call the StorageReference.putObject method to upload the file to the cloud.

private static final String OBJECT_NAME = "2M.txt"; public static void uploadFile() throws AGCException { **2M.txt**// 2M.txt is the file to be uploa**path** and path indicates the local path to this file. File file = new File(path+ "/2M.txt"); storageManagement = AGCStorageManagement.getInstance(AGCClient.getInstance("agcClient"), "cn-north-4", BUCKET_NAME); StorageReference storageReference = storageManagement.getStorageReference(); String[] result = {""}; ProgressListener listener = new ProgressListener() { @Override public void inProgress(ProgressStatus status) { result[0] = "upload transferred/total:" + status.getTransferredBytes() + "/" + status.getTotalBytes() + "," + status.getTransferPercentage() + "%, " + "instantaneous speed: " + status.getInstantaneousSpeed() + ", avg speed: " + status.getAverageSpeed(); } }; ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor(); service.scheduleAtFixedRate(() -> System.out.println(result[0]), 2, 3, TimeUnit.SECONDS); PutObjectRequest putObjectRequest = new PutObjectRequest(); putObjectRequest.setObjectMetadata(null); putObjectRequest.setObjectName(OBJECT_NAME); putObjectRequest.setUploadFile(file); putObjectRequest.setProgressListener(listener); storageReference.putObject(putObjectRequest); System.out.println(OBJECT_NAME + " upload succeeded " + storageReference.doesObjectExist(OBJECT_NAME)); }

Downloading a File

Call the download() method to download files from the cloud to a local device. If no storage path is specified, the file will be saved to the local project directory by default.

public static void downloadFile() throws StorageException { StorageReference storageReference = storageManagement.getStorageReference(OBJECT_NAME); final String[] result = {""}; DownloadFileRequest request = new DownloadFileRequest(); request.setOffset(0); request.setSaveFile(new File(OBJECT_NAME)); request.setProgressListener(new ProgressListener() { @Override public void inProgress(ProgressStatus status) { result[0] = "download transferred/total:" + status.getTransferredBytes() + "/" + status.getTotalBytes() + "," + status.getTransferPercentage() + "%, " + "instantaneous speed: " + status.getInstantaneousSpeed() + ", avg speed: " + status.getAverageSpeed(); } }); ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor(); service.scheduleAtFixedRate(() -> System.out.println(result[0]), 2, 3, TimeUnit.SECONDS); storageReference.download(request); }

Managing File Metadata

  1. Call the getObjectMetadata() method to obtain the file metadata.
    public static void getMetadata() throws StorageException { storageManagement = AGCStorageManagement.getInstance(AGCClient.getInstance("agcClient"), "cn-north-4", BUCKET_NAME); StorageReference storageReference = storageManagement.getStorageReference(OBJECT_NAME); ObjectMetadata objectMetadata = storageReference.getObjectMetadata(); System.out.println(objectMetadata.getContentType()); System.out.println(objectMetadata.getCacheControl()); System.out.println(objectMetadata.getContentEncoding()); System.out.println(objectMetadata.getContentDisposition()); System.out.println(objectMetadata.getContentLanguage()); }
  2. Call the updateObjectMetadata() method to update the file metadata.
    public static void updateMetadata() throws StorageException { storageManagement = AGCStorageManagement.getInstance(AGCClient.getInstance("agcClient"), "cn-north-4", BUCKET_NAME); StorageReference storageReference = storageManagement.getStorageReference(OBJECT_NAME); ObjectMetadata updatedObjectMetadata = storageReference.updateObjectMetadata(initObjectMetadata()); System.out.println(updatedObjectMetadata.getContentType()); System.out.println(updatedObjectMetadata.getCacheControl()); System.out.println(updatedObjectMetadata.getContentEncoding()); System.out.println(updatedObjectMetadata.getContentDisposition()); System.out.println(updatedObjectMetadata.getContentLanguage()); }

Obtaining the File List

Call the getFileList() method to obtain the file list from the cloud.

public static void listObjects() throws StorageException { storageManagement = AGCStorageManagement.getInstance(AGCClient.getInstance("agcClient"), "cn-north-4", BUCKET_NAME); StorageReference storageReference = storageManagement.getStorageReference(OBJECT_NAME); ListObjectsRequest listObjectsRequest = new ListObjectsRequest(); listObjectsRequest.setMarker(""); listObjectsRequest.setMaxKeys(100); listObjectsRequest.setDelimiter("/"); listObjectsRequest.setListTimeout(5); ListObjectsResult objectsResult = storageReference.listObjects(listObjectsRequest); for (String file : objectsResult.getFileList()) { System.out.println("file - " + file); } for (String dir : objectsResult.getDirList()) { System.out.println("dir - " + dir); } }

Deleting a File

Call the deleteObject() method to delete the uploaded file from the cloud.

public static void deleteFile() throws StorageException { storageManagement = AGCStorageManagement.getInstance(AGCClient.getInstance("agcClient"), "cn-north-4", BUCKET_NAME); StorageReference storageReference = storageManagement.getStorageReference(OBJECT_NAME); DeleteObjectResult deleteObjectResult = storageReference.deleteObject(OBJECT_NAME); System.out.println("Delete object " + deleteObjectResult.getObjectName() + " succeeded"); }

Call methods to test functions. Sample code in this section is for your reference.

Uploading a File

uploadFile();

When the message "2M.txt upload succeeded true" is displayed on the console, the file is successfully uploaded.

You can also view the upload progress on the console.

Downloading a File

download();

When the message "download finished" is displayed on the console, the file is successfully downloaded. After the download is complete, you can find the downloaded file in the project directory.

You can also view the download progress on the console.

Managing File Metadata

Obtaining Metadata

getFileMetadata();

After the metadata is successfully obtained, you can view the result on the console.

Updating Metadata

updateFileMetadata();

After the metadata is successfully updated, you can view the result on the console.

Obtaining the File List

getFileList();

After the file list is obtained successfully, you can view the file list on the console.

Deleting a File

deleteFile();

After this method is called, you can access the Cloud Storage page in AppGallery Connect to check whether files are successfully deleted.

Cloud Storage provides visualized file management and data analysis.

  1. Sign in to AppGallery Connect and click My projects.
  2. Find and click your project.
  3. Go to Build > Cloud Storage. On the Cloud Storage page that is displayed, you can manage files, including uploading, viewing, downloading, and deleting files.
  4. Click the Usage tab to view data analysis of Cloud Storage. The page displays the storage usage, number of storage objects, network traffic, and number of requests of the current storage instance. You can select a time segment (current day, yesterday, last 7 days, or last 30 days) in the upper right corner of the page.

Well done. You have successfully built an app that integrates Cloud Storage of AppGallery Connect and learned how to manage Cloud Storage in AppGallery Connect.

Code copied