Skip to main content

apiV1JobJobIdGet()

Get current task status:
import org.openapitools.client.ApiClient;
import org.openapitools.client.api.VideoApi;
import org.openapitools.client.ApiException;

ApiClient apiClient = new ApiClient();
apiClient.setBasePath("https://api.legnext.ai");
VideoApi videoApi = new VideoApi(apiClient);

String apiKey = "your-api-key-here";
String jobId = "job-123";

try {
    var task = videoApi.apiV1JobJobIdGet(jobId, apiKey);
    System.out.println("Status: " + task.getStatus());
    System.out.println("Progress: " + task.getProgress() + "%");

    if ("completed".equals(task.getStatus())) {
        System.out.println("Result: " + task.getOutput());
    }
} catch (ApiException e) {
    System.err.println("Error: " + e.getResponseBody());
}

Polling for Completion

Wait for task completion with polling:
public class TaskPoller {
    public static void waitForCompletion(
        VideoApi api,
        String jobId,
        String apiKey,
        int timeoutSeconds,
        int pollIntervalSeconds
    ) throws ApiException, InterruptedException {
        long startTime = System.currentTimeMillis();
        long timeout = timeoutSeconds * 1000;

        while (true) {
            var task = api.apiV1JobJobIdGet(jobId, apiKey);
            String status = task.getStatus();

            System.out.println("Current status: " + status);

            if ("completed".equals(status)) {
                System.out.println("Task completed successfully!");
                System.out.println("Output: " + task.getOutput());
                return;
            } else if ("failed".equals(status)) {
                throw new RuntimeException("Task failed: " + task.getError());
            }

            // Check timeout
            if (System.currentTimeMillis() - startTime > timeout) {
                throw new RuntimeException("Task timeout after " + timeoutSeconds + " seconds");
            }

            // Wait before next poll
            Thread.sleep(pollIntervalSeconds * 1000);
        }
    }
}
Usage:
try {
    TaskPoller.waitForCompletion(imageApi, jobId, apiKey, 300, 3);
} catch (Exception e) {
    System.err.println("Error: " + e.getMessage());
}

Complete Example with Error Handling

import org.openapitools.client.ApiClient;
import org.openapitools.client.api.VideoApi;
import org.openapitools.client.ApiException;
import java.util.HashMap;
import java.util.Map;

public class ImageGenerationWithPolling {
    public static void main(String[] args) {
        ApiClient apiClient = new ApiClient();
        apiClient.setBasePath("https://api.legnext.ai");
        VideoApi videoApi = new VideoApi(apiClient);

        String apiKey = System.getenv("LEGNEXT_API_KEY");

        try {
            // Step 1: Start generation
            Map<String, Object> body = new HashMap<>();
            body.put("text", "a beautiful sunset over mountains");

            var response = imageApi.apiV1DiffusionPost(apiKey, body);
            String jobId = response.getJobId();
            System.out.println("Job started: " + jobId);

            // Step 2: Poll for completion
            TaskPoller.waitForCompletion(imageApi, jobId, apiKey, 600, 3);

            // Step 3: Get final result
            var result = videoApi.apiV1JobJobIdGet(jobId, apiKey);
            System.out.println("Image URLs: " + result.getOutput().getImageUrls());

        } catch (ApiException e) {
            handleApiException(e);
        } catch (InterruptedException e) {
            System.err.println("Polling interrupted: " + e.getMessage());
        } catch (Exception e) {
            System.err.println("Unexpected error: " + e.getMessage());
            e.printStackTrace();
        }
    }

    private static void handleApiException(ApiException e) {
        int statusCode = e.getCode();
        String responseBody = e.getResponseBody();

        switch (statusCode) {
            case 400:
                System.err.println("Validation error: " + responseBody);
                break;
            case 401:
                System.err.println("Authentication error: Invalid API key");
                break;
            case 404:
                System.err.println("Resource not found: " + responseBody);
                break;
            case 429:
                System.err.println("Rate limit exceeded. Please retry later.");
                break;
            case 500:
            case 502:
            case 503:
                System.err.println("Server error: " + responseBody);
                break;
            default:
                System.err.println("API error (" + statusCode + "): " + responseBody);
        }
    }
}

Error Handling

Common HTTP Status Codes:
Status CodeDescriptionAction
400Invalid request parametersCheck request body format
401Invalid API keyVerify API key is correct
404Resource not foundCheck job ID exists
429Rate limit exceededWait and retry with backoff
500/502/503Server errorRetry with exponential backoff
Handling Different Error Scenarios:
try {
    var response = imageApi.apiV1DiffusionPost(apiKey, body);
} catch (ApiException e) {
    if (e.getCode() == 429) {
        // Rate limited - implement backoff
        Thread.sleep(5000);
        // Retry request
    } else if (e.getCode() >= 500) {
        // Server error - retry with exponential backoff
        for (int i = 0; i < 3; i++) {
            Thread.sleep((long) Math.pow(2, i) * 1000);
            try {
                var response = imageApi.apiV1DiffusionPost(apiKey, body);
                break; // Success
            } catch (ApiException retryEx) {
                if (i == 2) throw retryEx; // Last retry failed
            }
        }
    } else {
        // Other errors - log and handle
        System.err.println("API Error: " + e.getResponseBody());
        throw e;
    }
}

Async Operations with CompletableFuture

For non-blocking operations:
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class AsyncExample {
    private static final ExecutorService executor = Executors.newFixedThreadPool(5);

    public static CompletableFuture<String> generateImageAsync(
        VideoApi api,
        String apiKey,
        String prompt
    ) {
        return CompletableFuture.supplyAsync(() -> {
            try {
                Map<String, Object> body = new HashMap<>();
                body.put("text", prompt);

                var response = api.apiV1DiffusionPost(apiKey, body);
                String jobId = response.getJobId();

                // Poll for completion
                TaskPoller.waitForCompletion(api, jobId, apiKey, 600, 3);

                var result = api.apiV1JobJobIdGet(jobId, apiKey);
                return result.getOutput().getImageUrls().get(0);

            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }, executor);
    }

    public static void main(String[] args) {
        ApiClient apiClient = new ApiClient();
        apiClient.setBasePath("https://api.legnext.ai");
        VideoApi videoApi = new VideoApi(apiClient);
        String apiKey = System.getenv("LEGNEXT_API_KEY");

        // Generate multiple images concurrently
        CompletableFuture<String> future1 = generateImageAsync(api, apiKey, "sunset");
        CompletableFuture<String> future2 = generateImageAsync(api, apiKey, "mountains");
        CompletableFuture<String> future3 = generateImageAsync(api, apiKey, "ocean");

        CompletableFuture.allOf(future1, future2, future3).join();

        try {
            System.out.println("Image 1: " + future1.get());
            System.out.println("Image 2: " + future2.get());
            System.out.println("Image 3: " + future3.get());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            executor.shutdown();
        }
    }
}

Learn More