user1699450
user1699450

Reputation: 41

Amazon Spot Price History - Java Code

It should be possible to get the AWS Spot Price history for the past 90 days. When using the Java SDK it's possible to create a query to get some of the history, but because this list is so long they split it up. Using a token you should be able to get the next part of the list, en this until you have received the whole list.

The problem is that using the given token I was not yet able to retrieve more then the first part of the list. While searching the internet it became clear that my understanding of this token is right.

    // Create the AmazonEC2Client object so we can call various APIs.
    AmazonEC2 ec2 = new AmazonEC2Client(credentials);

    // Get the spot price history
    DescribeSpotPriceHistoryResult result = ec2.describeSpotPriceHistory();

    // Print first part of list
    for (int i = 0; i < result.getSpotPriceHistory().size(); i++) {
        System.out.println(result.getSpotPriceHistory().get(i));
    }

    result = result.withNextToken(result.getNextToken());

    // Print second part of list
    for (int i = 0; i < result.getSpotPriceHistory().size(); i++) {
            System.out.println(result.getSpotPriceHistory().get(i));
    }

The "nextToken" of the result is not changing. Any ideas what I'm doing wrong? Is there a bug in the SDK? I installed it via Eclipse.

Thanks in advance!

Upvotes: 4

Views: 1399

Answers (1)

Steffen Opel
Steffen Opel

Reputation: 64751

You are indeed not using the API as expected - you need to resubmit the DescribeSpotPriceHistoryRequest with the nextToken retrieved from the DescribeSpotPriceHistoryResult (admittedly it is slightly confusing that you can set nextToken on the latter as well, guess it should ideally be an internal method only), e.g:

// Create the AmazonEC2Client object so we can call various APIs.
AmazonEC2 ec2 = new AmazonEC2Client(credentials);

// Get the spot price history
String nextToken = "";
do {
    // Prepare request (include nextToken if available from previous result)
    DescribeSpotPriceHistoryRequest request = new DescribeSpotPriceHistoryRequest()
            .withNextToken(nextToken);

    // Perform request
    DescribeSpotPriceHistoryResult result = ec2
            .describeSpotPriceHistory(request);
    for (int i = 0; i < result.getSpotPriceHistory().size(); i++) {
        System.out.println(result.getSpotPriceHistory().get(i));
    }

    // 'nextToken' is the string marking the next set of results returned (if any), 
    // it will be empty if there are no more results to be returned.            
    nextToken = result.getNextToken();

} while (!nextToken.isEmpty());

Upvotes: 2

Related Questions