Creating a timeout for Java RMI client is important since LocateRegistry.getRegistry would make your application unresponsive when the Java RMI server is not available. To create a timeout at the client-side, I suggest you to use ExecutorService. The following codes is an example how to use it:
Suppose you have your localhost listening on port 1099 for RMI and your server serve an interface
public interface RMIService() {
public String sayHello throws RemoteException;
}
Then at your client app, you do this
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<String> future = executor.submit(new Callable<Object>() {
@Override
public Object call() throws Exception {
String host = "localhost";
int port = 1099;
RMIService service = (RMIService) LocateRegistry
.getRegistry(host, port).lookup("RMIService");
System.err.println(service.sayHello());
return null;
}
});
try {
future.get(5, TimeUnit.SECONDS);
} catch (InterruptedException | TimeoutException |
ExecutionException e) {
System.err.println(e.getMessage());
}
The above code will try executing the remote method and will throw exception if the lookup time exceeds 5 seconds.
Hope this helps. :)
Showing posts with label java. Show all posts
Showing posts with label java. Show all posts
Monday, August 5, 2013
Tuesday, February 5, 2013
Java: Base64 Encode
I used this function to encode a string using base64 encoding for my java card applet.
public static String base64Encode(String s) {
String table="ABCDEFGHIJKLMNOPQRSTUVWXYZ";
+ "abcdefghijklmnopqrstuvwxyz0123456789+/";
String b="";
String r="";
int pad;
for (int c : s.toCharArray()) {
b+=rjust(Integer.toBinaryString(c), 8, "0");
}
for (int i=0; i<b.length(); i+=6) {
r+=table.charAt(Integer.parseInt(ljust(b.substring(i, i+6), 6, "0"), 2));
pad=6-b.substring(i, i+6).length();
switch (pad) {
case 0: r+=""; break;
case 4: r+="=="; break;
case 2: r+="="; break; }
}
return r;
}
Both rjust and ljust that you can find in the function above are custom functions similar to python's rjust and ljust.
public static String base64Encode(String s) {
String table="ABCDEFGHIJKLMNOPQRSTUVWXYZ";
+ "abcdefghijklmnopqrstuvwxyz0123456789+/";
String b="";
String r="";
int pad;
for (int c : s.toCharArray()) {
b+=rjust(Integer.toBinaryString(c), 8, "0");
}
for (int i=0; i<b.length(); i+=6) {
r+=table.charAt(Integer.parseInt(ljust(b.substring(i, i+6), 6, "0"), 2));
pad=6-b.substring(i, i+6).length();
switch (pad) {
case 0: r+=""; break;
case 4: r+="=="; break;
case 2: r+="="; break; }
}
return r;
}
Both rjust and ljust that you can find in the function above are custom functions similar to python's rjust and ljust.
Subscribe to:
Posts (Atom)