package com.davfx.ninio.script.util;
import java.io.IOException;
import com.davfx.ninio.ping.PingClientHandler;
import com.davfx.ninio.ping.PingableAddress;
import com.davfx.ninio.ping.util.PingClientCache;
import com.davfx.ninio.script.RegisteredFunctionsScriptRunner;
import com.davfx.ninio.script.ScriptFunction;
import com.davfx.util.ConfigUtils;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;
public final class PingAvailable {
public static final String CALL_FUNCTION_NAME = ConfigUtils.load(PingAvailable.class).getString("script.functions.ping");
private final PingClientCache client;
public PingAvailable(PingClientCache client) {
this.client = client;
}
public RegisteredFunctionsScriptRunner register(RegisteredFunctionsScriptRunner runner) {
runner.register(CALL_FUNCTION_NAME, new ScriptFunction<JsonElement>() {
private String getString(JsonObject r, String key, String defaultValue) {
JsonElement e = r.get(key);
if (e == null) {
return defaultValue;
}
return e.getAsString();
}
private Double getDouble(JsonObject r, String key, Double defaultValue) {
JsonElement e = r.get(key);
if (e == null) {
return defaultValue;
}
return e.getAsDouble();
}
@Override
public void call(JsonElement request, ScriptFunction.Callback<JsonElement> userCallback) {
JsonObject r = request.getAsJsonObject();
String host = getString(r, "host", "localhost");
PingClientCache.Connectable c = client.get(host);
double timeBetweenRetries = getDouble(r, "retry", 1d);
double retryTimeout = getDouble(r, "timeout", 10d);
PingableAddress address;
try {
address = PingableAddress.from(host);
} catch (IOException e) {
JsonObject rr = new JsonObject();
rr.add("error", new JsonPrimitive(e.getMessage()));
userCallback.handle(rr);
return;
}
c.connect(new PingClientHandler() {
@Override
public void failed(IOException e) {
JsonObject r = new JsonObject();
r.add("error", new JsonPrimitive(e.getMessage()));
userCallback.handle(r);
}
@Override
public void close() {
}
@Override
public void launched(Callback callback) {
callback.ping(address, 1, timeBetweenRetries, retryTimeout, new PingClientHandler.Callback.PingCallback() {
@Override
public void failed(IOException e) {
JsonObject r = new JsonObject();
r.add("error", new JsonPrimitive(e.getMessage()));
userCallback.handle(r);
}
@Override
public void pong(int[] statuses, double[] times) {
JsonObject r = new JsonObject();
if (statuses[0] == PingClientHandler.VALID_STATUS) {
r.add("time", new JsonPrimitive(times[0]));
} else {
r.add("status", new JsonPrimitive(statuses[0]));
}
userCallback.handle(r);
}
});
}
});
}
});
return runner;
}
}