What is the best way to detect whether a java API call successfully completed or not

361 Views Asked by At

I'm using following code to add a target pool to Google compute engine in java using Google Compute Engine Java API.

Operation operation = compute.targetPools().insert(PROJECT_ID, REGION_NAME, targetPool).execute();

I need to make sure that target pool is successfully added or not before execute the next line. What is the best way to do this in Google Compute Engine API?

3

There are 3 best solutions below

1
On BEST ANSWER

You need to wait until operation will be in status DONE and then check if it has no errors. To do that you need to do polling on the operation using the compute."operations"().get() - I've put operations in quotation marks because there are three types of operations: global, regional and zonal and each of them has its own service: globalOperations(), regionOperations() and zoneOperations(). As targetPools are regional resource, operation created by insert is also regional so you need to use compute().regionOperations().get(). Code:

while (!operation.getStatus().equals("DONE")) {
   RegionOperations.Get getOperation = compute.regionOperations().get(
              PROJECT_ID, REGION_NAME, operation.getName());
   operation = getOperation.execute();
}
if (operation.getError() == null) {
  // targetPools has been successfully created
}
1
On

Have you tried using a try/catch block? You could do something like:

try
{
   Operation operation = compute.targetPools().insert(PROJECT_ID, REGION_NAME, targetPool).execute();
}
catch(Exception ex)
{
   //Error handling stuff
}

Hope that helps :)

3
On

One possibility is to check the status

while(!operation.getStatus().equals("DONE")) { 
  //wait
  System.out.println("Progress: " + operation.getProgress());
}
  // Check if Success
if(operation.getError() != null) {
  // Handle Error
} else {
  // Succeed with Program
}