### Describe VPCs using Volcengine Java SDK Source: https://github.com/volcengine/volcengine-java-sdk/blob/master/README.EN.MD Example demonstrating how to initialize the SDK, set credentials and region, and call the describeVpcs API. ```java import com.volcengine.ApiClient; import com.volcengine.ApiException; import com.volcengine.sign.Credentials; import com.volcengine.vpc.VpcApi; import com.volcengine.vpc.model.DescribeVpcsRequest; import com.volcengine.vpc.model.DescribeVpcsResponse; import java.util.ArrayList; import java.util.List; public class TestVpc { public static void main(String[] args) throws Exception { String ak = "your ak"; String sk = "your sk"; String region = "cn-beijing"; ApiClient apiClient = new ApiClient() .setCredentials(Credentials.getCredentials(ak, sk)) .setRegion(region); VpcApi vpcApi = new VpcApi(apiClient); DescribeVpcsRequest request = new DescribeVpcsRequest(); List list = new ArrayList<>(); list.add("vpc-13fpdgwk7rxfk3n6nu44wisg7"); request.setVpcIds(list); try { DescribeVpcsResponse response = vpcApi.describeVpcs(request); System.out.println(response); } catch (ApiException e) { System.out.println(e.getResponseBody()); } } } ``` -------------------------------- ### Configure API Client with AK/SK Credentials Source: https://github.com/volcengine/volcengine-java-sdk/blob/master/SDK_Integration.md Use static AK/SK for initial setup, but avoid in production. For production, read credentials from environment variables. ```java import com.volcengine.ApiClient; import com.volcengine.sign.Credentials; public class SampleCode { public static void main(String[] args) { String ak = "Your AK"; String sk = "Your SK"; String region = "cn-beijing"; // 1. Using static AK/SK may leak credentials; do not use in production. Credentials akSkCredential = Credentials.getCredentials(ak, sk); // 2. Recommended in production: read from env vars: VOLCENGINE_ACCESS_KEY / VOLCENGINE_SECRET_KEY // Credentials akSkCredential = Credentials.getEnvCredentials(); ApiClient apiClient = new ApiClient() .setCredentials(akSkCredential) .setRegion(region); } } ``` -------------------------------- ### Manage ECS Instance Lifecycle Source: https://context7.com/volcengine/volcengine-java-sdk/llms.txt Demonstrates how to stop, start, and reboot an ECS instance using the Volcengine Java SDK. Ensure proper error handling and consider using polling mechanisms for production environments instead of fixed delays. ```java import com.volcengine.ApiClient; import com.volcengine.ApiException; import com.volcengine.sign.Credentials; import com.volcengine.ecs.EcsApi; import com.volcengine.ecs.model.*; import java.util.Arrays; public class InstanceLifecycleExample { public static void main(String[] args) { ApiClient apiClient = new ApiClient() .setCredentials(Credentials.getEnvCredentials()) .setRegion("cn-beijing"); EcsApi ecsApi = new EcsApi(apiClient); String instanceId = "i-3tiefm4fgk5s0sxxxx"; try { // Stop instance StopInstanceRequest stopRequest = new StopInstanceRequest(); stopRequest.setInstanceId(instanceId); stopRequest.setForceStop(false); // Graceful shutdown stopRequest.setStoppedMode("KeepCharging"); // or "StopCharging" StopInstanceResponse stopResponse = ecsApi.stopInstance(stopRequest); System.out.println("Stop initiated, Request ID: " + stopResponse.getRequestId()); // Wait for instance to stop (in production, use proper polling) Thread.sleep(30000); // Start instance StartInstanceRequest startRequest = new StartInstanceRequest(); startRequest.setInstanceId(instanceId); StartInstanceResponse startResponse = ecsApi.startInstance(startRequest); System.out.println("Start initiated, Request ID: " + startResponse.getRequestId()); // Reboot instance (alternative) RebootInstanceRequest rebootRequest = new RebootInstanceRequest(); rebootRequest.setInstanceId(instanceId); rebootRequest.setForceStop(false); RebootInstanceResponse rebootResponse = ecsApi.rebootInstance(rebootRequest); System.out.println("Reboot initiated, Request ID: " + rebootResponse.getRequestId()); } catch (ApiException e) { System.err.println("Error: " + e.getResponseBody()); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } } ``` -------------------------------- ### Allocate, Associate, Describe, Disassociate, and Release EIP Source: https://context7.com/volcengine/volcengine-java-sdk/llms.txt This example demonstrates the full lifecycle of an Elastic IP address: allocating a new EIP, associating it with an ECS instance, describing its details, disassociating it, and finally releasing it. Ensure you have valid credentials and instance IDs. ```java import com.volcengine.ApiClient; import com.volcengine.ApiException; import com.volcengine.sign.Credentials; import com.volcengine.vpc.VpcApi; import com.volcengine.vpc.model.*; public class EIPManagementExample { public static void main(String[] args) { ApiClient apiClient = new ApiClient() .setCredentials(Credentials.getEnvCredentials()) .setRegion("cn-beijing"); VpcApi vpcApi = new VpcApi(apiClient); try { // Allocate a new EIP AllocateEipAddressRequest allocateRequest = new AllocateEipAddressRequest(); allocateRequest.setName("web-server-eip"); allocateRequest.setBillingType(2); // 2 = Pay-by-bandwidth allocateRequest.setBandwidth(10); // 10 Mbps allocateRequest.setDescription("EIP for web server"); AllocateEipAddressResponse allocateResponse = vpcApi.allocateEipAddress(allocateRequest); String allocationId = allocateResponse.getAllocationId(); String eipAddress = allocateResponse.getEipAddress(); System.out.println("EIP Allocated: " + eipAddress + " (ID: " + allocationId + ")"); // Associate EIP with an ECS instance AssociateEipAddressRequest associateRequest = new AssociateEipAddressRequest(); associateRequest.setAllocationId(allocationId); associateRequest.setInstanceId("i-3tiefm4fgk5s0sxxxx"); associateRequest.setInstanceType("EcsInstance"); vpcApi.associateEipAddress(associateRequest); System.out.println("EIP associated with instance"); // Describe EIP addresses DescribeEipAddressesRequest describeRequest = new DescribeEipAddressesRequest(); describeRequest.setAllocationIds(java.util.Arrays.asList(allocationId)); DescribeEipAddressesResponse describeResponse = vpcApi.describeEipAddresses(describeRequest); describeResponse.getEipAddresses().forEach(eip -> { System.out.println("EIP: " + eip.getEipAddress()); System.out.println("Status: " + eip.getStatus()); System.out.println("Instance: " + eip.getInstanceId()); }); // Disassociate EIP (when needed) DisassociateEipAddressRequest disassociateRequest = new DisassociateEipAddressRequest(); disassociateRequest.setAllocationId(allocationId); vpcApi.disassociateEipAddress(disassociateRequest); System.out.println("EIP disassociated"); // Release EIP (when no longer needed) ReleaseEipAddressRequest releaseRequest = new ReleaseEipAddressRequest(); releaseRequest.setAllocationId(allocationId); vpcApi.releaseEipAddress(releaseRequest); System.out.println("EIP released"); } catch (ApiException e) { System.err.println("Error: " + e.getResponseBody()); } } } ``` -------------------------------- ### Handle API Exceptions in Java Source: https://context7.com/volcengine/volcengine-java-sdk/llms.txt Catch `ApiException` to gracefully handle errors from API calls. Inspect the exception for status codes, response bodies, headers, and messages to diagnose issues. This example demonstrates handling common HTTP error codes. ```java import com.volcengine.ApiClient; import com.volcengine.ApiException; import com.volcengine.sign.Credentials; import com.volcengine.vpc.VpcApi; import com.volcengine.vpc.model.*; public class ErrorHandlingExample { public static void main(String[] args) { ApiClient apiClient = new ApiClient() .setCredentials(Credentials.getEnvCredentials()) .setRegion("cn-beijing"); VpcApi vpcApi = new VpcApi(apiClient); DescribeVpcsRequest request = new DescribeVpcsRequest(); request.setVpcIds(java.util.Arrays.asList("vpc-nonexistent")); try { DescribeVpcsResponse response = vpcApi.describeVpcs(request); System.out.println("VPCs found: " + response.getTotalCount()); } catch (ApiException e) { // HTTP status code System.err.println("HTTP Status Code: " + e.getCode()); // Error response body (JSON) System.err.println("Response Body: " + e.getResponseBody()); // Response headers System.err.println("Response Headers: " + e.getResponseHeaders()); // Error message System.err.println("Message: " + e.getMessage()); // Handle specific error codes if (e.getCode() == 400) { System.err.println("Bad Request - Check your parameters"); } else if (e.getCode() == 401) { System.err.println("Authentication failed - Check your credentials"); } else if (e.getCode() == 403) { System.err.println("Access denied - Check your permissions"); } else if (e.getCode() == 404) { System.err.println("Resource not found"); } else if (e.getCode() == 429) { System.err.println("Rate limited - Implement backoff"); } else if (e.getCode() >= 500) { System.err.println("Server error - Retry with backoff"); } } } } // Example error output: // HTTP Status Code: 400 // Response Body: {"ResponseMetadata":{"RequestId":"2024xxxxx","Action":"DescribeVpcs","Version":"2020-04-01","Service":"vpc","Region":"cn-beijing","Error":{"Code":"InvalidVpcId.NotFound","Message":"The specified VpcId does not exist."}}} // Response Headers: {X-Request-Id=[2024xxxxx], Content-Type=[application/json]} // Message: Bad Request ``` -------------------------------- ### Configure Credentials in Code Source: https://github.com/volcengine/volcengine-java-sdk/blob/master/README.EN.MD Instantiate Credentials using access key, secret key, and optionally a session token. ```java Credentials credentials = Credentials.getCredentials(ak, sk); // If using token Credentials credentials = Credentials.getCredentials(ak, sk, token); ``` -------------------------------- ### Launch ECS Instances with Detailed Configuration Source: https://context7.com/volcengine/volcengine-java-sdk/llms.txt Use this to launch ECS instances with specific configurations for system and data disks, networking, and key pairs. Ensure you have valid credentials and region set in the ApiClient. ```java import com.volcengine.ApiClient; import com.volcengine.ApiException; import com.volcengine.sign.Credentials; import com.volcengine.ecs.EcsApi; import com.volcengine.ecs.model.*; import java.util.Arrays; public class RunInstancesExample { public static void main(String[] args) { ApiClient apiClient = new ApiClient() .setCredentials(Credentials.getEnvCredentials()) .setRegion("cn-beijing"); EcsApi ecsApi = new EcsApi(apiClient); RunInstancesRequest request = new RunInstancesRequest(); request.setZoneId("cn-beijing-a"); request.setInstanceTypeId("ecs.g3i.large"); // 2 vCPU, 8GB RAM request.setImageId("image-ybqi99s7yq8rx7mnk44b"); // CentOS 7.9 request.setInstanceName("web-server-01"); request.setDescription("Production web server"); request.setInstanceChargeType("PostPaid"); // Pay-as-you-go // Network configuration request.setVpcId("vpc-13fpdgwk7rxfk3n6nu44wisg7"); request.setSubnetId("subnet-2fe1x7u4k3ls058ozfd3zoyj7"); request.setSecurityGroupIds(Arrays.asList("sg-2fepsx9k0c3ls058ozfezqmqw")); // System disk configuration SystemVolumeForRunInstancesInput systemVolume = new SystemVolumeForRunInstancesInput(); systemVolume.setVolumeType("ESSD_PL0"); systemVolume.setSize(40); // 40GB request.setSystemVolume(systemVolume); // Data disk configuration DataVolumesForRunInstancesInput dataVolume = new DataVolumesForRunInstancesInput(); dataVolume.setVolumeType("ESSD_PL1"); dataVolume.setSize(100); // 100GB dataVolume.setDeleteWithInstance(true); request.setDataVolumes(Arrays.asList(dataVolume)); // Key pair for SSH access request.setKeyPairName("my-ssh-keypair"); // Number of instances to launch request.setCount(1); try { RunInstancesResponse response = ecsApi.runInstances(request); System.out.println("Instances launched successfully!"); response.getInstanceIds().forEach(id -> System.out.println("Instance ID: " + id) ); } catch (ApiException e) { System.err.println("Failed to launch instances: " + e.getResponseBody()); } } } ``` -------------------------------- ### Manage IAM Users and Access Keys Source: https://context7.com/volcengine/volcengine-java-sdk/llms.txt Shows how to create an IAM user, generate access keys for them, and list existing users using the Volcengine Java SDK. Remember to securely store the secret access key as it will not be displayed again. ```java import com.volcengine.ApiClient; import com.volcengine.ApiException; import com.volcengine.sign.Credentials; import com.volcengine.iam.IamApi; import com.volcengine.iam.model.*; public class IAMUserExample { public static void main(String[] args) { // IAM is a global service ApiClient apiClient = new ApiClient() .setCredentials(Credentials.getEnvCredentials()) .setEndpoint("iam.volcengineapi.com"); IamApi iamApi = new IamApi(apiClient); try { // Create IAM User CreateUserRequest createUserRequest = new CreateUserRequest(); createUserRequest.setUserName("app-service-account"); createUserRequest.setDisplayName("Application Service Account"); createUserRequest.setDescription("Service account for application access"); CreateUserResponse createUserResponse = iamApi.createUser(createUserRequest); System.out.println("User created: " + createUserResponse.getUser().getUserName()); // Create Access Key for the user CreateAccessKeyRequest accessKeyRequest = new CreateAccessKeyRequest(); accessKeyRequest.setUserName("app-service-account"); CreateAccessKeyResponse accessKeyResponse = iamApi.createAccessKey(accessKeyRequest); System.out.println("Access Key ID: " + accessKeyResponse.getAccessKey().getAccessKeyId()); System.out.println("Secret Access Key: " + accessKeyResponse.getAccessKey().getSecretAccessKey()); // Important: Store the secret key securely - it won't be shown again! // List users ListUsersRequest listRequest = new ListUsersRequest(); listRequest.setLimit(100); ListUsersResponse listResponse = iamApi.listUsers(listRequest); listResponse.getUsers().forEach(user -> System.out.println("User: " + user.getUserName() + " - " + user.getDisplayName()) ); } catch (ApiException e) { System.err.println("IAM Error: " + e.getResponseBody()); } } } ``` -------------------------------- ### Configure AK/SK Credentials for Volcengine SDK Source: https://github.com/volcengine/volcengine-java-sdk/blob/master/SDK_Integration_zh.md Use this method to configure static AK/SK credentials. Avoid hardcoding in production; prefer environment variables. ```java import com.volcengine.ApiClient; import com.volcengine.sign.Credentials; public class SampleCode { public static void main(String[] args) { String ak = "Your AK"; String sk = "Your SK"; String region = "cn-beijing"; // 1. 输入静态ak和sk可能泄漏会导致AK/SK泄漏,生产环境不能这样使用 Credentials akSkCredential = Credentials.getCredentials(ak, sk); // 2. 推荐使用环境变量获取AK/SK,避免代码泄漏;会读取环境变量中:VOLCENGINE_ACCESS_KEY、VOLCENGINE_SECRET_KEY //Credentials akSkCredential = Credentials.getEnvCredentials(); ApiClient apiClient = new ApiClient() .setCredentials(akSkCredential) .setRegion(region); } } ``` -------------------------------- ### Set Environment Variables (Linux) Source: https://github.com/volcengine/volcengine-java-sdk/blob/master/SDK_Integration.md Configure access keys and session tokens as environment variables for SDK authentication. These settings are session-specific and should be added to shell startup scripts for persistence. ```bash export VOLCENGINE_ACCESS_KEY=yourAccessKeyID ``` ```bash export VOLCENGINE_SECRET_KEY=yourSecretAccessKey ``` ```bash export VOLCENGINE_SESSION_TOKEN=yourSessionToken ``` -------------------------------- ### Set Environment Variables (Windows Command Line) Source: https://github.com/volcengine/volcengine-java-sdk/blob/master/SDK_Integration.md Configure access keys and session tokens as system-level environment variables using the `setx` command in Windows Command Prompt. Ensure Command Prompt is run as Administrator. ```batch setx VOLCENGINE_ACCESS_KEY yourAccessKeyID /M ``` ```batch setx VOLCENGINE_SECRET_KEY yourAccessKeySecret /M ``` ```batch setx VOLCENGINE_SESSION_TOKEN yourSessionToken /M ``` -------------------------------- ### Authenticate with AK/SK Credentials Source: https://context7.com/volcengine/volcengine-java-sdk/llms.txt Configure authentication using Access Key and Secret Key. The recommended method is to load credentials from environment variables. ```java import com.volcengine.ApiClient; import com.volcengine.sign.Credentials; public class AuthenticationExample { public static void main(String[] args) { // Option 1: Recommended - Load credentials from environment variables // Set these environment variables before running: // export VOLCENGINE_ACCESS_KEY=your_access_key // export VOLCENGINE_SECRET_KEY=your_secret_key Credentials envCredentials = Credentials.getEnvCredentials(); ApiClient apiClient = new ApiClient() .setCredentials(envCredentials) .setRegion("cn-beijing"); // Option 2: Direct credentials (NOT recommended for production) String ak = "AKLTYourAccessKeyId"; String sk = "WVdGaVkyUmxZbUZqWkdWaVlXTmtaV0poWTJSbFltRmpa"; Credentials directCredentials = Credentials.getCredentials(ak, sk); ApiClient directClient = new ApiClient() .setCredentials(directCredentials) .setRegion("cn-beijing"); } } ``` -------------------------------- ### Create a New Virtual Private Cloud Source: https://context7.com/volcengine/volcengine-java-sdk/llms.txt Create a new Virtual Private Cloud with a specified name, CIDR block, description, and DNS servers. Handles API exceptions during creation. ```java import com.volcengine.ApiClient; import com.volcengine.ApiException; import com.volcengine.sign.Credentials; import com.volcengine.vpc.VpcApi; import com.volcengine.vpc.model.CreateVpcRequest; import com.volcengine.vpc.model.CreateVpcResponse; public class CreateVpcExample { public static void main(String[] args) { ApiClient apiClient = new ApiClient() .setCredentials(Credentials.getEnvCredentials()) .setRegion("cn-beijing"); VpcApi vpcApi = new VpcApi(apiClient); CreateVpcRequest request = new CreateVpcRequest(); request.setVpcName("my-production-vpc"); request.setCidrBlock("172.16.0.0/16"); request.setDescription("Production environment VPC"); request.setDnsServers(java.util.Arrays.asList("100.96.0.2", "100.96.0.3")); try { CreateVpcResponse response = vpcApi.createVpc(request); System.out.println("VPC Created Successfully!"); System.out.println("VPC ID: " + response.getVpcId()); System.out.println("Request ID: " + response.getRequestId()); } catch (ApiException e) { System.err.println("Failed to create VPC: " + e.getResponseBody()); } } } ``` -------------------------------- ### Configure HTTP(S) Proxy Source: https://github.com/volcengine/volcengine-java-sdk/blob/master/SDK_Integration.md Sets up HTTP and HTTPS proxy configurations for the API client. This can be done via code or environment variables, with code configuration taking precedence. ```java import com.volcengine.ApiClient; import com.volcengine.sign.Credentials; public static void main(String[] args) { String regionId = "cn-beijing"; ApiClient apiClient = new ApiClient() .setCredentials(Credentials.getEnvCredentials()) .setRegion(regionId) .setHttpProxy("http://your_http_proxy:proxy_port") .setHttpsProxy("http://your_https_proxy:proxy_port"); } ``` -------------------------------- ### Configure Custom Endpoints for Volcengine SDK Source: https://context7.com/volcengine/volcengine-java-sdk/llms.txt Use this to set custom endpoints for specific regions, global services, or to enable DualStack support. It also shows how to configure custom bootstrap regions and use a standard endpoint resolver. ```java import com.volcengine.ApiClient; import com.volcengine.sign.Credentials; import com.volcengine.endpoint.StandardEndpointProvider; import java.util.HashSet; public class EndpointConfigurationExample { public static void main(String[] args) { // Standard regional endpoint ApiClient regionalClient = new ApiClient() .setCredentials(Credentials.getEnvCredentials()) .setRegion("cn-beijing"); // Endpoint automatically resolves to: ecs.cn-beijing.volcengineapi.com // Custom endpoint (e.g., for specific region) ApiClient customEndpointClient = new ApiClient() .setCredentials(Credentials.getEnvCredentials()) .setRegion("cn-beijing-autodriving") .setEndpoint("ecs.cn-beijing-autodriving.volcengineapi.com"); // Global service (IAM, STS) ApiClient globalClient = new ApiClient() .setCredentials(Credentials.getEnvCredentials()) .setEndpoint("iam.volcengineapi.com"); // DualStack (IPv6) support ApiClient dualStackClient = new ApiClient() .setCredentials(Credentials.getEnvCredentials()) .setRegion("cn-beijing") .setUseDualStack(true); // Endpoint becomes: ecs.cn-beijing.volcengine-api.com // Custom bootstrap regions ApiClient customRegionClient = new ApiClient() .setCredentials(Credentials.getEnvCredentials()) .setRegion("custom-region-1") .setCustomBootstrapRegion(new HashSet() { { add("custom-region-1"); add("custom-region-2"); } }); // Standard endpoint resolver ApiClient standardClient = new ApiClient() .setCredentials(Credentials.getEnvCredentials()) .setEndpointResolver(new StandardEndpointProvider()) .setRegion("cn-beijing"); } } ``` -------------------------------- ### Configure API Client with AssumeRole Dynamic Credentials Source: https://github.com/volcengine/volcengine-java-sdk/blob/master/SDK_Integration.md Implement dynamic credentials with auto-refresh using AssumeRole. Choose a reasonable TTL, with a maximum of 12 hours, and apply fine-grained roles and policies. ```java import com.volcengine.auth.CredentialProvider; import com.volcengine.auth.StsAssumeRoleProvider; public class SampleCode { public static void main(String[] args) { String region = "cn-beijing"; StsAssumeRoleProvider stsAssumeRoleProvider = new StsAssumeRoleProvider( "YourAccessKey", "YourSecretKey", "YourRoleName", "YourAccountId"); // Optional fields stsAssumeRoleProvider.setHost("sts.volcengineapi.com"); stsAssumeRoleProvider.setRegion("cn-north-1"); stsAssumeRoleProvider.setTimeout(30); stsAssumeRoleProvider.setDurationSeconds(3600); stsAssumeRoleProvider.setExpireBufferSeconds(60); stsAssumeRoleProvider.setSchema("https"); CredentialProvider credentialProvider = new CredentialProvider(stsAssumeRoleProvider); ApiClient apiClient = new ApiClient() .setCredentialProvider(credentialProvider) .setRegion(region); } } ``` -------------------------------- ### Add Volcengine SDK Module Dependencies Source: https://github.com/volcengine/volcengine-java-sdk/blob/master/README.EN.MD Include dependencies for specific Volcengine SDK modules like VPC or ECS. ```xml com.volcengine volcengine-java-sdk-vpc 1.0.12 com.volcengine volcengine-java-sdk-ecs 1.0.12 ``` -------------------------------- ### Add Volcengine Java SDK to Maven Project Source: https://context7.com/volcengine/volcengine-java-sdk/llms.txt Include the SDK BOM for dependency management and add specific service modules as needed. For Java 9+, include javax.annotation-api. ```xml com.volcengine volcengine-java-sdk-bom 2.0.1 pom import com.volcengine volcengine-java-sdk-vpc com.volcengine volcengine-java-sdk-ecs com.volcengine volcengine-java-sdk-iam javax.annotation javax.annotation-api 1.3.2 ``` -------------------------------- ### Configure Client Timeouts in Java Source: https://github.com/volcengine/volcengine-java-sdk/blob/master/SDK_Integration.md Set custom connect, read, and write timeouts for the ApiClient. Defaults are 10 seconds for each. ```java import com.volcengine.ApiClient; import com.volcengine.sign.Credentials; public class SampleCode { public static void main(String[] args) { String regionId = "cn-beijing"; ApiClient apiClient = new ApiClient() .setCredentials(Credentials.getEnvCredentials()) .setRegion(regionId) .setConnectTimeout(10 * 1000) .setReadTimeout(15 * 1000) .setWriteTimeout(15 * 1000); } } ``` -------------------------------- ### Describe VPCs with Filtering and Pagination Source: https://context7.com/volcengine/volcengine-java-sdk/llms.txt Query Virtual Private Cloud resources using the VpcApi. Supports filtering by VPC IDs and pagination with PageNumber and PageSize. Handles API exceptions. ```java import com.volcengine.ApiClient; import com.volcengine.ApiException; import com.volcengine.sign.Credentials; import com.volcengine.vpc.VpcApi; import com.volcengine.vpc.model.DescribeVpcsRequest; import com.volcengine.vpc.model.DescribeVpcsResponse; import java.util.Arrays; public class DescribeVpcsExample { public static void main(String[] args) { ApiClient apiClient = new ApiClient() .setCredentials(Credentials.getEnvCredentials()) .setRegion("cn-beijing"); VpcApi vpcApi = new VpcApi(apiClient); DescribeVpcsRequest request = new DescribeVpcsRequest(); // Filter by specific VPC IDs request.setVpcIds(Arrays.asList( "vpc-13fpdgwk7rxfk3n6nu44wisg7", "vpc-2fez9xa0h2zk858oz7f4tq2i1" )); // Pagination request.setPageNumber(1); request.setPageSize(20); try { DescribeVpcsResponse response = vpcApi.describeVpcs(request); System.out.println("Total VPCs: " + response.getTotalCount()); response.getVpcs().forEach(vpc -> { System.out.println("VPC ID: " + vpc.getVpcId()); System.out.println("CIDR Block: " + vpc.getCidrBlock()); System.out.println("Status: " + vpc.getStatus()); System.out.println("---"); }); } catch (ApiException e) { System.err.println("Error Code: " + e.getCode()); System.err.println("Error Message: " + e.getResponseBody()); } } } ``` -------------------------------- ### Configure STS Token Credentials for Volcengine SDK Source: https://github.com/volcengine/volcengine-java-sdk/blob/master/SDK_Integration_zh.md Configure STS temporary credentials for secure access. It's recommended to fetch these from environment variables in production. ```java import com.volcengine.ApiClient; import com.volcengine.sign.Credentials; public class SampleCode { public static void main(String[] args) { String ak = "Your AK"; String sk = "Your SK"; String sessionToken = "Your Session Token"; String region = "cn-beijing"; // 1. 输入静态AK/SK、Session Token可能泄漏会导致AK/SK、Session Token泄漏,生产环境不能这样使用 Credentials sessionTokenCredential = Credentials.getCredentials(ak, sk, sessionToken); // 2. 推荐使用环境变量获取AK/SK、Session Token避免代码泄漏;会读取环境变量中:VOLCENGINE_ACCESS_KEY、VOLCENGINE_SECRET_KEY和VOLCENGINE_SESSION_TOKEN //Credentials sessionTokenCredential = Credentials.getEnvCredentials(); ApiClient apiClient = new ApiClient() .setCredentials(sessionTokenCredential) .setRegion(region); } } ``` -------------------------------- ### Import Volcengine SDK BOM Source: https://github.com/volcengine/volcengine-java-sdk/blob/master/README.EN.MD Import the Bill of Materials (BOM) to manage versions of Volcengine SDK modules. ```xml com.volcengine volcengine-java-sdk-bom 1.0.12 pom import ``` -------------------------------- ### Configure HTTP Connection Pool and Timeouts for Volcengine SDK Source: https://context7.com/volcengine/volcengine-java-sdk/llms.txt Optimize production workloads by configuring connection pooling, timeouts, and retry behavior. This includes settings for max idle connections, keep-alive duration, connection/read/write timeouts, SSL verification, and automatic retries with custom error codes. ```java import com.volcengine.ApiClient; import com.volcengine.sign.Credentials; import com.volcengine.retryer.DefaultRetryCondition; import com.volcengine.retryer.ExponentialBackoffStrategy; public class HttpConfigurationExample { public static void main(String[] args) { ApiClient apiClient = new ApiClient() .setCredentials(Credentials.getEnvCredentials()) .setRegion("cn-beijing") // Connection pool settings .setMaxIdleConns(10) // Max idle connections .setKeepAliveDurationMs(5 * 60 * 1000) // Keep-alive duration (5 minutes) // Timeout settings (in milliseconds) .setConnectTimeout(10 * 1000) // Connection timeout: 10s .setReadTimeout(30 * 1000) // Read timeout: 30s .setWriteTimeout(30 * 1000) // Write timeout: 30s // SSL settings .setDisableSSL(false) // Use HTTPS (default) .setVerifyingSsl(true) // Verify SSL certificates // Retry configuration .setAutoRetry(true) // Enable automatic retries .setNumMaxRetries(3) // Maximum retry attempts .setMinRetryDelayMs(1000) // Minimum retry delay: 1s .setMaxRetryDelayMs(30 * 1000) // Maximum retry delay: 30s .setRetryCondition(new DefaultRetryCondition()) .setBackoffStrategy(new ExponentialBackoffStrategy()) .addRetryErrorCode("Throttling") // Retry on throttling errors .addRetryErrorCode("ServiceUnavailable"); // Retry on service unavailable } } ``` -------------------------------- ### Configure Retries and Backoff Strategy in Java Source: https://github.com/volcengine/volcengine-java-sdk/blob/master/SDK_Integration.md Enable automatic retries, set retry delay bounds, and specify retry conditions and backoff strategies. The SDK retries on network errors and throttling by default. ```java import com.volcengine.ApiClient; import com.volcengine.retryer.DefaultRetryCondition; import com.volcengine.retryer.ExponentialBackoffStrategy; import com.volcengine.sign.Credentials; public class SampleCode { public static void main(String[] args) { String region = "cn-beijing"; ApiClient apiClient = new ApiClient() .setCredentials(Credentials.getEnvCredentials()) .setRegion(region) .setDebugging(true) .setAutoRetry(true) .setNumMaxRetries(3) .setMinRetryDelayMs(1000) .setMaxRetryDelayMs(3000) .setRetryCondition(new DefaultRetryCondition()) .setBackoffStrategy(new ExponentialBackoffStrategy()) .addRetryErrorCode("InvalidAuthorization"); } } ``` -------------------------------- ### Configure ByteDance Maven Repository Mirror Source: https://github.com/volcengine/volcengine-java-sdk/blob/master/README.EN.MD Add this mirror configuration to your Maven settings.xml if using SDK versions 0.1.27 or earlier. ```xml bytedanceMaven my-repo-id ByteDance Maven Repository https://artifact.bytedance.com/repository/releases/ ``` -------------------------------- ### Configure HTTP Proxy in Java Code Source: https://context7.com/volcengine/volcengine-java-sdk/llms.txt Set HTTP and HTTPS proxy details directly within your Java code when initializing the ApiClient. Ensure the proxy URL and port are correct. ```java import com.volcengine.ApiClient; import com.volcengine.sign.Credentials; public class ProxyConfigurationExample { public static void main(String[] args) { // Option 1: Configure proxy in code ApiClient apiClient = new ApiClient() .setCredentials(Credentials.getEnvCredentials()) .setRegion("cn-beijing") .setHttpProxy("http://proxy.example.com:8080") .setHttpsProxy("http://proxy.example.com:8080"); // Option 2: Configure via environment variables (auto-detected) // export http_proxy=http://proxy.example.com:8080 // export https_proxy=http://proxy.example.com:8080 // or // export HTTP_PROXY=http://proxy.example.com:8080 // export HTTPS_PROXY=http://proxy.example.com:8080 ApiClient envProxyClient = new ApiClient() .setCredentials(Credentials.getEnvCredentials()) .setRegion("cn-beijing"); // Proxy settings are automatically detected from environment } } ``` -------------------------------- ### Configure API Client with STS Token Credentials Source: https://github.com/volcengine/volcengine-java-sdk/blob/master/SDK_Integration.md Utilize STS tokens for temporary credentials. Ensure a reasonable Time To Live (TTL), preferably not exceeding 1 hour. ```java import com.volcengine.ApiClient; import com.volcengine.sign.Credentials; public class SampleCode { public static void main(String[] args) { String ak = "Your AK"; String sk = "Your SK"; String sessionToken = "Your Session Token"; String region = "cn-beijing"; Credentials sessionTokenCredential = Credentials.getCredentials(ak, sk, sessionToken); // Credentials sessionTokenCredential = Credentials.getEnvCredentials(); ApiClient apiClient = new ApiClient() .setCredentials(sessionTokenCredential) .setRegion(region); } } ``` -------------------------------- ### Configure Default Endpoint Resolution with Custom Regions Source: https://github.com/volcengine/volcengine-java-sdk/blob/master/SDK_Integration.md Sets up the API client with custom bootstrap regions for default endpoint resolution. Ensure the region is valid or it will fall back to the default endpoint. ```java import com.volcengine.ApiClient; import com.volcengine.sign.Credentials; import java.util.HashSet; public class SampleCode { public static void main(String[] args) { String regionId = "cn-beijing"; ApiClient apiClient = new ApiClient() .setCredentials(Credentials.getEnvCredentials()) .setRegion(regionId) .setUseDualStack(true) .setCustomBootstrapRegion(new HashSet() {{ add("custom_example_region1"); add("custom_example_region2"); }}); } } ``` -------------------------------- ### Add javax.annotation-api Dependency Source: https://github.com/volcengine/volcengine-java-sdk/blob/master/README.EN.MD Include this dependency if using Java 9 or later, as javax.annotation was removed from the JDK. ```xml javax.annotation javax.annotation-api 1.3.2 ``` -------------------------------- ### Manage VPC Security Groups and Ingress Rules Source: https://context7.com/volcengine/volcengine-java-sdk/llms.txt Creates a security group and adds ingress rules for HTTP and HTTPS traffic. Requires a valid VPC ID. Ensure the protocol and port ranges are correctly set. ```java import com.volcengine.ApiClient; import com.volcengine.ApiException; import com.volcengine.sign.Credentials; import com.volcengine.vpc.VpcApi; import com.volcengine.vpc.model.*; public class SecurityGroupExample { public static void main(String[] args) { ApiClient apiClient = new ApiClient() .setCredentials(Credentials.getEnvCredentials()) .setRegion("cn-beijing"); VpcApi vpcApi = new VpcApi(apiClient); // Create Security Group CreateSecurityGroupRequest createRequest = new CreateSecurityGroupRequest(); createRequest.setVpcId("vpc-13fpdgwk7rxfk3n6nu44wisg7"); createRequest.setSecurityGroupName("web-server-sg"); createRequest.setDescription("Security group for web servers"); try { CreateSecurityGroupResponse createResponse = vpcApi.createSecurityGroup(createRequest); String sgId = createResponse.getSecurityGroupId(); System.out.println("Security Group Created: " + sgId); // Add Ingress Rule (Allow HTTP) AuthorizeSecurityGroupIngressRequest ingressRequest = new AuthorizeSecurityGroupIngressRequest(); ingressRequest.setSecurityGroupId(sgId); ingressRequest.setProtocol("TCP"); ingressRequest.setPortStart(80); ingressRequest.setPortEnd(80); ingressRequest.setCidrIp("0.0.0.0/0"); ingressRequest.setDescription("Allow HTTP traffic"); vpcApi.authorizeSecurityGroupIngress(ingressRequest); System.out.println("HTTP ingress rule added"); // Add Ingress Rule (Allow HTTPS) ingressRequest.setPortStart(443); ingressRequest.setPortEnd(443); ingressRequest.setDescription("Allow HTTPS traffic"); vpcApi.authorizeSecurityGroupIngress(ingressRequest); System.out.println("HTTPS ingress rule added"); } catch (ApiException e) { System.err.println("Error: " + e.getResponseBody()); } } } ``` -------------------------------- ### Configure Standard Endpoint Resolution Source: https://github.com/volcengine/volcengine-java-sdk/blob/master/SDK_Integration.md Initializes the API client using a standard endpoint resolver. This is useful for services that follow a predictable endpoint pattern based on region and dual-stack support. ```java import com.volcengine.ApiClient; import com.volcengine.sign.Credentials; import com.volcengine.endpoint.StandardEndpointProvider; public class SampleCode { public static void main(String[] args) { String regionId = "cn-beijing"; ApiClient apiClient = new ApiClient() .setCredentials(Credentials.getEnvCredentials()) .setEndpointResolver(new StandardEndpointProvider()) .setRegion(regionId) .setUseDualStack(true); } } ``` -------------------------------- ### Enable Debug Logging in Java SDK Source: https://github.com/volcengine/volcengine-java-sdk/blob/master/SDK_Integration.md Configure SLF4J to enable debug logs for the SDK core components. Ensure your logging framework is properly set up. ```xml ``` -------------------------------- ### Create VPC Subnet Source: https://context7.com/volcengine/volcengine-java-sdk/llms.txt Creates a new subnet within an existing VPC. Ensure the VPC ID, subnet name, CIDR block, and zone ID are correctly specified. ```java import com.volcengine.ApiClient; import com.volcengine.ApiException; import com.volcengine.sign.Credentials; import com.volcengine.vpc.VpcApi; import com.volcengine.vpc.model.CreateSubnetRequest; import com.volcengine.vpc.model.CreateSubnetResponse; public class CreateSubnetExample { public static void main(String[] args) { ApiClient apiClient = new ApiClient() .setCredentials(Credentials.getEnvCredentials()) .setRegion("cn-beijing"); VpcApi vpcApi = new VpcApi(apiClient); CreateSubnetRequest request = new CreateSubnetRequest(); request.setVpcId("vpc-13fpdgwk7rxfk3n6nu44wisg7"); request.setSubnetName("web-tier-subnet"); request.setCidrBlock("172.16.1.0/24"); request.setZoneId("cn-beijing-a"); request.setDescription("Web application tier subnet"); try { CreateSubnetResponse response = vpcApi.createSubnet(request); System.out.println("Subnet Created: " + response.getSubnetId()); } catch (ApiException e) { System.err.println("Failed to create subnet: " + e.getResponseBody()); } } } ``` -------------------------------- ### Configure HTTPS Request Scheme Source: https://github.com/volcengine/volcengine-java-sdk/blob/master/SDK_Integration.md Sets the SSL configuration for HTTPS requests. By default, SSL is enabled (`disableSSL=false`). Set `disableSSL=true` to use HTTP. ```java import com.volcengine.ApiClient; import com.volcengine.sign.Credentials; public class SampleCode { public static void main(String[] args) { String regionId = "cn-beijing"; ApiClient apiClient = new ApiClient() .setCredentials(Credentials.getEnvCredentials()) .setRegion(regionId) .setDisableSSL(false); } } ``` -------------------------------- ### Configure API Client with Custom Endpoint Source: https://github.com/volcengine/volcengine-java-sdk/blob/master/SDK_Integration.md Set a custom endpoint for the API client. If not specified, the SDK uses Automatic Endpoint Resolution. ```java import com.volcengine.ApiClient; import com.volcengine.sign.Credentials; public class SampleCode { public static void main(String[] args) { String region = "cn-beijing"; ApiClient apiClient = new ApiClient() .setCredentials(Credentials.getEnvCredentials()) .setRegion(region) .setEndpoint("..volcengineapi.com"); } } ``` -------------------------------- ### Configure SSL Verification Source: https://github.com/volcengine/volcengine-java-sdk/blob/master/SDK_Integration.md Controls SSL certificate verification for HTTPS requests. By default, verification is enabled (`verifyingSsl=true`). Set `verifyingSsl=false` to skip verification. ```java import com.volcengine.ApiClient; import com.volcengine.sign.Credentials; public class SampleCode { public static void main(String[] args) { String regionId = "cn-beijing"; ApiClient apiClient = new ApiClient() .setCredentials(Credentials.getEnvCredentials()) .setRegion(regionId) .setVerifyingSsl(false); } } ``` -------------------------------- ### Query ECS Instance Details Source: https://context7.com/volcengine/volcengine-java-sdk/llms.txt Use this to retrieve details of ECS instances, filtering by instance IDs or status. It also supports pagination for large result sets. Ensure the ApiClient is configured with credentials and region. ```java import com.volcengine.ApiClient; import com.volcengine.ApiException; import com.volcengine.sign.Credentials; import com.volcengine.ecs.EcsApi; import com.volcengine.ecs.model.*; import java.util.Arrays; public class DescribeInstancesExample { public static void main(String[] args) { ApiClient apiClient = new ApiClient() .setCredentials(Credentials.getEnvCredentials()) .setRegion("cn-beijing"); EcsApi ecsApi = new EcsApi(apiClient); DescribeInstancesRequest request = new DescribeInstancesRequest(); // Filter by instance IDs request.setInstanceIds(Arrays.asList("i-3tiefm4fgk5s0sxxxx")); // Or filter by status request.setStatus("RUNNING"); // Pagination request.setMaxResults(100); try { DescribeInstancesResponse response = ecsApi.describeInstances(request); System.out.println("Total Instances: " + response.getTotalCount()); response.getInstances().forEach(instance -> { System.out.println("Instance ID: " + instance.getInstanceId()); System.out.println("Name: " + instance.getInstanceName()); System.out.println("Type: " + instance.getInstanceTypeId()); System.out.println("Status: " + instance.getStatus()); System.out.println("Private IP: " + instance.getPrivateIpAddress()); System.out.println("Public IP: " + instance.getEipAddress()); System.out.println("vCPUs: " + instance.getCpus()); System.out.println("Memory: " + instance.getMemorySize() + " MB"); System.out.println("---"); }); } catch (ApiException e) { System.err.println("Error: " + e.getResponseBody()); } } } ```