Updated on 2024-05-09 GMT+08:00

Prerequisites

This section describes how to quickly integrate Java SDKs for development.

Prerequisites

  • You have registered with Huawei Cloud and completed real-name authentication.

    If you are a Huawei Cloud (International) user, you need to complete real-name authentication when you:

    • Purchase and use cloud services on Huawei Cloud nodes in the Chinese mainland. In this case, real-name authentication is required by the laws and regulations of the Chinese mainland.
    • Select the Chinese mainland region for MPC.
  • The development environment (Java JDK 1.8 or later) is available.
  • You have obtained the access key ID (AK) and secret access key (SK) of the account. You can create and view your AK/SK on the My Credentials > Access Keys page of the console. For details, see Access Keys.
  • You have obtained the project ID of the corresponding region of MPC. You can view the project ID on the My Credentials > API Credentials page of the console. For details, see API Credentials.
  • You have uploaded the media asset files to an OBS bucket in the region of MPC, and authorized MPC to access the OBS bucket. For details, see Uploading Media Files and Authorizing Access to Cloud Resources.

Procedure

  1. Import the dependent module.

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    // User authentication
    import com.huaweicloud.sdk.core.auth.BasicCredentials;
    // Request exceptions
    import com.huaweicloud.sdk.core.exception.ClientRequestException;
    import com.huaweicloud.sdk.core.exception.ServerResponseException;
    // Configure HTTP.
    import com.huaweicloud.sdk.core.http.HttpConfig;
    // Import an MPC client.
    import com.huaweicloud.sdk.mpc.v1.MpcClient;
    // Import the request and response classes of an API.
    import com.huaweicloud.sdk.mpc.v1.model.ListTranscodingTaskRequest;
    import com.huaweicloud.sdk.mpc.v1.model.ListTranscodingTaskResponse;
    // Print logs.
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    

  2. Configure client attributes.

    1. Use the default configuration.
      1
      2
      // Use the default configuration.
      HttpConfig config = HttpConfig.getDefaultHttpConfig();
      
    2. (Optional) Configure the proxy.
      1
      2
      3
      4
      5
      // (Optional) Use a proxy server.
      config.withProxyHost("http://proxy.myhuaweicloud.com")
          .withProxyPort(8080)
          .withProxyUsername("test")
          .withProxyPassword("test");
      
    3. (Optional) Configure the connection.
      1
      2
      // (Optional) Configure the connection timeout interval.
      config.withTimeout(3);
      
    4. (Optional) Configure SSL.
      1
      2
      // (Optional) Configure whether to skip server certificate verification.
      config.withIgnoreSSLVerification(true);
      

  3. Initialize authentication information.

    You can use one of the following two authentication modes:

    The related parameters are as follows:
    • ak: access key of an account.
    • sk: secret access key of an account.
    • projectId: project ID of the region where MPC is provided. Select a project ID based on the region of the project.
    • securityToken: security token used for temporary AK/SK authentication

  4. Initialize the client.

    1
    2
    3
    4
    5
    6
    // Initialize the MPC client.
    MpcClient MpcClient = MpcClient.newBuilder()
        .withHttpConfig(config)
        .withCredential(credentials)
        .withEndpoint(endpoint)
        .build();
    

    endpoint: regions where MPC is used and endpoints of each service. For details, see Regions and Endpoints.

  5. Send a request and view the response.

    1
    2
    3
    4
    5
    // Initialize the request. The following uses the API for querying transcoding templates as an example.
    ListTranscodingTaskResponse response = mpcClient.
    listTranscodingTask(new ListTranscodingTaskRequest().withTaskId(Collections.singletonList(1900293L))
    ));
    logger.info(response.toString());
    

  6. Perform troubleshooting.

    Table 1 Troubleshooting

    Level 1

    Description

    Level 2

    Description

    ConnectionException

    Connection exception

    HostUnreachableException

    The network is unreachable or access is rejected.

    SslHandShakeException

    SSL authentication is abnormal.

    RequestTimeoutException

    Response timeout exception

    CallTimeoutException

    The server fails to respond to a single request before timeout.

    RetryOutageException

    No valid response is returned after the maximum number of retries specified in the retry policy is reached.

    ServiceResponseException

    Server response exception

    ServerResponseException

    Internal server error. HTTP response code: [500,].

    ClientRequestException

    Invalid request parameter. HTTP response code: [400, 500).

    1
    2
    3
    4
    5
    6
    7
    8
    9
    // Troubleshooting
    try {
    ListTranscodingTaskResponse  response= mpcClient.listTranscodingTask(new ListTranscodingTaskRequest().withTaskId(Collections.singletonList(1900293L)));
    } catch(ServiceResponseException e) {
        logger.error("HttpStatusCode: " + e.getHttpStatusCode());
        logger.error("RequestId: " + e.getRequestId());
        logger.error("ErrorCode: " + e.getErrorCode());
        logger.error("ErrorMsg: " + e.getErrorMsg());
    }
    

  7. Use an asynchronous client.

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    // Initialize an asynchronous client.
    MpcAsyncClient mpcAsyncClient = 
    MpcAsyncClient.newBuilder()
        .withHttpConfig(config)
        .withCredential(credentials)
        .withEndpoint(endpoint)
        .build();
    
    // Send an asynchronous request.
    CompletableFuture<ListTranscodingTaskResponse> future = mpcAsyncClient.listTranscodingTaskAsync(new ListTranscodingTaskRequest().withTaskId(Collections.singletonList(1900293L)));
    
    // Obtain the asynchronous response.
    ListTranscodingTaskResponse response = future.get();
    logger.info(response.toString());
    

  8. Print access logs.

    The running SDK uses Simple Logging Facade for Java (SLF4J) to print logs. If the logging library is not configured when the code instance is run, the following information is displayed:

    1
    2
    3
    SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
    SLF4J: Defaulting to no-operation (NOP) logger implementation
    SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
    

    You can introduce the logging library dependencies to the pom.xml file of the target project, as shown in the following examples.

    • SLF4J
       1
       2
       3
       4
       5
       6
       7
       8
       9
      10
      11
      12
      13
      14
      15
      16
      17
       <dependency>
           <groupId>org.slf4j</groupId>
           <artifactId>slf4j-simple</artifactId>
           <version>1.7.21</version>
       </dependency>
      logback
      
      <dependency>
          <groupId>ch.qos.logback</groupId>
          <artifactId>logback-classic</artifactId>
          <version>1.2.3</version>
      </dependency>
      <dependency>
          <groupId>ch.qos.logback</groupId>
          <artifactId>logback-core</artifactId>
          <version>1.2.3</version>
      </dependency>
      
    • Log4j
      1
      2
      3
      4
      5
      <dependency>
          <groupId>log4j</groupId>
          <artifactId>log4j</artifactId>
          <version>1.2.17</version>
      </dependency>
      

    By default, the SDK prints access logs. Each request has a record named huaweiCloud-SDK-Access. The log format is as follows:

    "{httpMethod} {uri}" {httpStatusCode} {responseContentLength} {requestId}

    requestId indicates the request ID returned by API Gateway, which can be used for issue tracking.

    You can disable access logs in the corresponding log configuration file or record access logs in an independent file. For example, you can disable access logs in the Logback framework by adding the following configuration:
    1
    <logger name="huaweiCloud-SDK-Access" level="OFF"> </logger>
    

  9. Use the listener to obtain original HTTP requests and responses.

    The original HTTP requests and responses are required for debugging HTTP requests sent by the service side. The SDK provides the listener to obtain the original and encrypted HTTP requests and responses.

    Original information is printed only during debugging. Do not print the header and body of an original HTTP request in the production system because this information contains sensitive data but is not encrypted. If the request body is binary, that is, Content-Type is set to binary, the body will be displayed as *** without the detailed content.

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    HttpConfig config = new HttpConfig().addHttpListener(HttpListener.forRequestListener(requestListener ->
        // After the listener is registered, the original information about the HTTP requests is printed. Do not print the original information in the production system.
        logger.debug("REQUEST: {} {} {} {}",
            requestListener.httpMethod(),
            requestListener.uri(),
            requestListener.headers().entrySet().stream().flatMap(entry ->
                entry.getValue().stream().map(value -> entry.getKey() + " : " + value))
                .collect(Collectors.joining(";")),
            requestListener.body().orElse(""))));
        .addHttpListener(HttpListener.forResponseListener(responseListener ->
        // After the listener is registered, the original information about the HTTP requests is printed. Do not print the original information in the production system.
        logger.debug("RESPONSE: {} {} {} {} {}",
            responseListener.httpMethod(),
            responseListener.uri(),
            responseListener.statusCode(),
            responseListener.headers().entrySet().stream().flatMap(entry ->
                entry.getValue().stream().map(value -> entry.getKey() + " : " + value))
                .collect(Collectors.joining(";")),
            responseListener.body().orElse(""))));
    
    MpcClient mpcClient = MpcClient.newBuilder()
        .withHttpConfig(config)
        .withCredential(auth)
        .withEndpoint(endpoint)
        .build();
    

Sample Code: Initializing the MPC Client

Before calling this API, replace {your ak string}, {your sk string}, {your endpoint string}, and {your project id} with the actual values.
package com.huaweicloud.sdk.test;

import com.huaweicloud.sdk.core.auth.BasicCredentials;
import com.huaweicloud.sdk.core.http.HttpConfig;
import com.huaweicloud.sdk.mpc.v1.MpcClient;

public class InitMpc {
    private static HttpConfig httpConfig;
    private static BasicCredentials auth;
    private static String endpoint;
    private static MpcClient mpcClient;

    public static MpcClient getMpcClient() {
        httpConfig = HttpConfig.getDefaultHttpConfig().withIgnoreSSLVerification(true).withTimeout(3);
        // Configure the HTTP proxy.
        //httpConfig.withProxyHost("xxxxx").withProxyPort(xxxxx).withProxyUsername("xxxxx").
        //        withProxyPassword("xxxxx");

        String ak = "xxxxx";
        String sk = "xxxxx";
        String projectId = "xxxxx";
        endpoint = "https://mpc.region01.myhuaweicloud.com";
        auth = new BasicCredentials().withAk(ak).withSk(sk).withProjectId(projectId);
        mpcClient = MpcClient.newBuilder()
                .withHttpConfig(httpConfig)
                .withCredential(auth)
                .withEndpoint(endpoint)
                .build();
        return mpcClient;
    }
}