All Products
Search
Document Center

Elastic Compute Service:General process

Last Updated:Jan 26, 2024

This topic describes how to use Elastic Compute Service (ECS) SDK for Java. In the example, ECS SDK for Java is used to call the DescribeImages operation to query available image resources.

Prerequisites

An AccessKey pair is created. For more information, see Obtain an AccessKey pair.

Note

To protect the AccessKey pair of your Alibaba Cloud account, we recommend that you create a Resource Access Management (RAM) user, grant the RAM user the permissions to access ECS instances, and then use the AccessKey pair of the RAM user to call ECS SDK for Java. For more information, see Control access to resources by using RAM users.

Background information

  • In this example, the IClientProfile and IAcsClient classes are included in aliyun-java-sdk-core, and the other classes are included in aliyun-java-sdk-ecs.

  • This example is used to show how to query ECS public images. For information about public images, see Overview of public images.

  • The following table describes the differences between the previous and new SDK versions in methods, classes, and objects. If you are using the previous SDK version, we recommend that you switch to the new version to obtain new features.

    Item

    New SDK version

    Previous SDK version

    Request submission

    getAcsResponse()

    execute()

    Class that stores the AccessKey pair

    IClientProfile

    AliyunClient

    Object that stores identity credentials

    DefaultProfile.getProfile(RegionId, AccessKey, AccessKeySecret)

    new DefaultAliyunClient(APIUrl, AccessKey, AccessKeySecret)

    Package name prefix

    com.aliyuncs

    com.aliyun.api

Procedure

  1. Generate the profile object from the IClientProfile class.

    The profile object stores the AccessKey ID, AccessKey secret, and region. In this example, the China (Hangzhou) region (cn-hangzhou) is used. For more information about regions, see Regions and Zones.

    // Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables are configured in the code runtime environment. 
    IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou",System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"), System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
  2. Generate the client object of IAcsClient from the IClientProfile class.

    Obtain subsequent responses from IClientProfile.

    IAcsClient client = new DefaultAcsClient(profile);
  3. Create a request for the API operation and use a constructor to generate a default request class.

    The class is named after the API operation, followed by Request. The API operation that is used to obtain an image list is named DescribeImages. Therefore, the corresponding request class is named DescribeImagesRequest.

    DescribeImagesRequest request = new DescribeImagesRequest();
  4. Configure parameters for the request class.

    Call the setXxx method of the request class to configure required parameters for the API operation. In this example:

    • The DescribeImages operation uses RegionId to specify the region.

    • The DescribeImages operation uses ImageOwnerAlias to specify the image type to be queried. The setImageOwnerAlias parameter is set to system, which indicates public images.

    request.setImageOwnerAlias("system");
  5. Use the client object to obtain the response to the request.

    DescribeImagesResponse response = client.getAcsResponse(request);
    System.out.println(JSON.toJSONString(response));
  6. Call the corresponding getXxx method in the response to obtain the values of response parameters.

    If you want to obtain the name of an image, call the getImages() method to obtain the image objects, traverse the image objects to obtain the information of the image, and then call the getImageName() or getImageId method to obtain the details of the image.

    for(DescribeImagesResponse.Image image:response.getImages())
                {
                    System.out.println(image.getImageId());
                    System.out.println(image.getImageName());
                }

    An API operation may return multiple layers of information in a response. For example, if you call the DescribeImages operation, the returned information is a collection in the form of a list that stores information about each image. You must call the getImages() method to obtain the image objects, traverse the image objects to obtain the information of an image, and then call the getXxx method to obtain the details of the image.

  7. Call the catch() method to handle server and client errors.

    • Server error

      catch (ServerException e) {
                  e.printStackTrace();
                                 }
    • Client error

      catch (ClientException e) {
                  System.out.println("ErrCode:" + e.getErrCode());
                  System.out.println("ErrMsg:" + e.getErrMsg());
                  System.out.println("RequestId:" + e.getRequestId());
                                 }

Execution results

  • Complete response:

    {
        "PageNumber": 1,
        "TotalCount": 43,
        "PageSize": 1,
        "RegionId": "cn-hangzhou",
        "RequestId": "C93F3D9F-CF25-47DF-9C0F-614395E5DCAC",
        "Images": {
            "Image": [
                {
                    "ImageId": "freebsd_11_02_64_30G_alibase_20190722.vhd",
                    "Description": "",
                    "OSNameEn": "FreeBSD  11.2 64 bit",
                    "ProductCode": "",
                    "ResourceGroupId": "",
                    "OSType": "linux",
                    "Architecture": "x86_64",
                    "OSName": "FreeBSD  11.2 64-bit",
                    "DiskDeviceMappings": {
                        "DiskDeviceMapping": []
                    },
                    "ImageOwnerAlias": "system",
                    "Progress": "100%",
                    "IsSupportCloudinit": false,
                    "Usage": "instance",
                    "CreationTime": "2019-07-23T05:41:06Z",
                    "Tags": {
                        "Tag": []
                    },
                    "ImageVersion": "",
                    "Status": "Available",
                    "ImageName": "freebsd_11_02_64_30G_alibase_20190722.vhd",
                    "IsSupportIoOptimized": true,
                    "IsSelfShared": "",
                    "IsCopied": false,
                    "IsSubscribed": false,
                    "Platform": "Freebsd",
                    "Size": 30
                }
            ]
        }
    }
  • Obtain the values of specific response parameters, such as ImageId and ImageName.

    freebsd_11_02_64_30G_alibase_20190722.vhd
    freebsd_11_02_64_30G_alibase_20190722.vhd

Complete sample code

The following example shows the complete code of ECS SDK for Java:

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.profile.DefaultProfile;
import com.alibaba.fastjson.JSON;
import java.util.*;
import com.aliyuncs.ecs.model.v20140526.*;

public class DescribeImages {

    public static void main(String[] args) {
        // Make sure that the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables are configured in the code runtime environment. 
        // If the project code is leaked, the AccessKey pair may be leaked and the security of all resources in your account may be compromised. The following sample code shows how to use environment variables to obtain an AccessKey pair and use the AccessKey pair to call API operations. We recommend that you use Security Token Service (STS) tokens, which provide higher security. 
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou",System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"), System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));
        IAcsClient client = new DefaultAcsClient(profile);

        DescribeImagesRequest request = new DescribeImagesRequest();
        request.setRegionId("cn-hangzhou");
        request.setImageOwnerAlias("system");
        request.setPageNumber(1);
        request.setPageSize(1);

        try {
            DescribeImagesResponse response = client.getAcsResponse(request);
            System.out.println(JSON.toJSONString(response));
            for(DescribeImagesResponse.Image image:response.getImages())
            {
                System.out.println(image.getImageId());
                System.out.println(image.getImageName());
            }
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            System.out.println("ErrCode:" + e.getErrCode());
            System.out.println("ErrMsg:" + e.getErrMsg());
            System.out.println("RequestId:" + e.getRequestId());
        }

    }
}