Created
April 3, 2012 00:27
-
-
Save arschles/2288251 to your computer and use it in GitHub Desktop.
Making the StackMob Java Client SDK do a synchronous get call
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package my.package | |
import java.util.concurrent.CountDownLatch; | |
import java.util.concurrent.atomic.AtomicReference; | |
import java.util.concurrent.TimeUnit; | |
import java.util.Map; | |
import java.util.HashMap; | |
long requestTimeout = 5; | |
TimeUnit requestTimeoutUnit = TimeUnit.SECONDS;//wait max 5 seconds for StackMob requests to return. if longer, fail | |
CountDownLatch latch = new CountDownLatch(1); | |
AtomicReference<String> successBody = new AtomicReference<String>(); | |
AtomicReference<StackMobException> failedException = new AtomicReference<StackMobException>(); | |
Map<String, String> args = new HashMap<String, String>(); | |
args.put("username", "johndoe"); | |
//the success or failure function gets executed in a background thread. | |
//the CountDownLatch is what allows the background thread to communicate with | |
//the main thread | |
stackmob.get("user", args, new StackMobCallback() { | |
@Override | |
public void success(String responseBody) { | |
successBody.set(responseBody); | |
latch.countDown(); | |
} | |
@Override | |
public void failure(StackMobException e) { | |
failedException.set(e); | |
latch.countDown(); | |
} | |
}); | |
//this line waits for the background thread (which executes the methods inside the StackMobCallback) | |
//to complete | |
if(latch.await(requestTimeout, requestTimeoutUnit)) { | |
//the request came back in time | |
if(successBody.get() != null) { | |
//do something with the success response. successBody.get() will return the response body from StackMob, as a String. | |
doSomething(successBody.get()); | |
} else if(failedException.get() != null) { | |
//if failedException.get() was set, then something in the request failed. | |
throw failedException.get(); | |
} else { | |
//neither the success or failure methods were called in the StackMobCallback above. | |
//this should never happen. if it does, it is a bug in the StackMob Java Client SDK. | |
//please tell us about it at support@stackmob.com. | |
throw new Exception("bug in StackMob Java client SDK found - neither success nor failure were called in StackMobCallback"); | |
} | |
} else { | |
//the request did not come back in time | |
throw new Exception(String.format("the request to StackMob did not return within %d %s", requestTimeout, requestTimeoutUnit.toString.toLowerCase)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment