Asynchronous calls with Google App Engine
I am trying to use the Java client library for Google Maps API Web Services in a Google App Engine (Version 0.1.20).
Here is my code:
public class GetLocation {
static Logger Log = Logger.getLogger("GetLocation");
static final String APIKEY = "My Key";
static final GeoApiContext context = new GeoApiContext(new GaeRequestHandler()).setApiKey(APIKEY);
public GetLocation() {
Log.info("First synch request");
try {
GeocodingResult[] results = GeocodingApi.geocode(context,
"1600 Amphitheatre Parkway Mountain View, CA 94043").await();
System.out.println(results[0].formattedAddress);
} catch (Exception e){
}
Log.info("Second synch request");
GeocodingApiRequest req = GeocodingApi.newRequest(context).address("Sydney");
// Synchronous
try {
req.await();
// Handle successful request.
} catch (Exception e) {
// Handle error
Log.info ("Req Error:"+e);
}
Log.info("Asynch request");
// Async
req.setCallback(new PendingResult.Callback<GeocodingResult[]>() {
@Override
public void onResult(GeocodingResult[] result) {
Log.info ("Location returned: "+result[0]);
// Handle successful request.
}
@Override
public void onFailure(Throwable e) {
// Handle error.
}
});
}
}
When I run the code, the first call works successfully and the formatted address is returned.
Nothing happens with the Second synch request.
An error occurs on setting the asynchronous setCallback.
Here is the error log:
Apr 27, 2017 10:34:32 PM GetLocation
Can anyone point me in the right direction please?
A request can only be used once, and as per the error log, you first call await() and then call setCallback(...) on the same request. Pick one or the other. Preferably not the await(), as that'll lock up the web server's threads.
Thanks - I have sorted that out, but when I try to run the following code (on Google App Engine):
GeocodingApiRequest req = GeocodingApi.newRequest(context).address("Sydney");
// Async
req.setCallback(new GaePendingResult.Callback<GeocodingResult[]>() {
@Override
public void onResult(GeocodingResult[] result) {
Log.info ("Location returned: "+result[0]);
// Handle successful request.
}
@Override
public void onFailure(Throwable e) {
// Handle error.
}
});
I get the following error:
Exception in thread "Thread-16" java.lang.RuntimeException: setCallback not implemented for Google App Engine
How do I make asynchronous calls in Google App Engine?
Oh dear, it's been so long since I used AppEngine for Java I'd forgotten the large number of restrictions. I'm guessing await() is your only path forward. Alternatively, you can use the new style AppEngine managed containers, and get access to a full Java implementation.