use of org.nustaq.kontraktor.IPromise in project kontraktor by RuedigerMoeller.
the class RESTActor method getBooks.
// curl -i -X GET http://localhost:8080/api/books/234234
public IPromise getBooks(int id) {
Promise res = promise();
// simulate blocking operation (e.g. database query)
execInThreadPool(() -> new Book().title("Title " + id).id("" + id).author("kontraktor")).then(res);
return res;
}
use of org.nustaq.kontraktor.IPromise in project kontraktor by RuedigerMoeller.
the class UndertowRESTHandler method parseAndDispatch.
private void parseAndDispatch(HttpServerExchange exchange, String[] split, String rawPath, Method m, byte[] postData) {
try {
Class<?>[] parameterTypes = m.getParameterTypes();
Annotation[][] parameterAnnotations = m.getParameterAnnotations();
Object[] args = new Object[parameterTypes.length];
int splitIndex = 1;
try {
for (int i = 0; i < parameterTypes.length; i++) {
Class<?> parameterType = parameterTypes[i];
Annotation[] parameterAnnotation = parameterAnnotations[i];
if (parameterAnnotation != null && parameterAnnotation.length > 0) {
if (parameterAnnotation[0].annotationType() == FromQuery.class) {
String value = ((FromQuery) parameterAnnotation[0]).value();
Deque<String> strings = exchange.getQueryParameters().get(value);
if (strings != null) {
args[i] = inferValue(parameterType, strings.getFirst());
}
continue;
} else if (parameterAnnotation[0].annotationType() == RequestPath.class) {
args[i] = rawPath;
continue;
}
}
if (splitIndex < split.length) {
String stringVal = split[splitIndex];
Object val = inferValue(parameterType, stringVal);
if (val != NOVAL) {
args[i] = val;
splitIndex++;
continue;
}
}
// specials
if (parameterType == HeaderMap.class) {
args[i] = exchange.getRequestHeaders();
} else if (parameterType == String[].class) {
args[i] = split;
} else if (parameterType == JsonObject.class || parameterType == JsonValue.class) {
args[i] = Json.parse(new String(postData, "UTF-8"));
} else if (parameterType == byte[].class) {
args[i] = postData;
} else if (parameterType == Map.class) {
args[i] = exchange.getQueryParameters();
} else {
System.out.println("unsupported parameter type " + parameterType.getName());
}
}
} catch (Throwable th) {
th.printStackTrace();
Log.Warn(this, th, postData != null ? new String(postData, 0) : "");
exchange.setStatusCode(400);
exchange.getResponseSender().send("" + th + "\n");
return;
}
// change: allow incomplete parameters
// if ( splitIndex != split.length ) {
// exchange.setResponseCode(400);
// exchange.endExchange();
// return;
// }
Object invoke = m.invoke(facade.getActorRef(), args);
if (invoke instanceof IPromise) {
checkExchangeState(exchange);
((IPromise) invoke).then((r, e) -> {
if (e != null) {
exchange.setStatusCode(500);
exchange.getResponseSender().send("" + e);
} else {
checkExchangeState(exchange);
if (r instanceof String) {
exchange.setStatusCode(400);
exchange.getResponseSender().send("" + e);
} else if (r instanceof Integer) {
exchange.setStatusCode((Integer) r);
exchange.endExchange();
} else if (r instanceof Pair) {
exchange.setStatusCode((Integer) ((Pair) r).car());
exchange.getResponseSender().send("" + ((Pair) r).cdr());
} else if (r instanceof JsonValue) {
exchange.getResponseSender().send(r.toString());
} else if (r instanceof Serializable) {
byte[] bytes = jsonConf.asByteArray(r);
exchange.getResponseSender().send(ByteBuffer.wrap(bytes));
}
}
});
} else if (invoke == null) {
exchange.setStatusCode(200);
exchange.endExchange();
}
} catch (Exception e) {
Log.Warn(this, e);
exchange.setStatusCode(500);
exchange.getResponseSender().send("" + e);
exchange.endExchange();
return;
}
}
use of org.nustaq.kontraktor.IPromise in project kontraktor by RuedigerMoeller.
the class AsyncHttpActor method post.
public IPromise<HttpResponse> post(String url, String postData, String... headers) {
Promise res = new Promise();
if (url == null) {
int debug = 1;
}
try {
HttpPost req = new HttpPost(url);
setHeaders(req, headers);
beChrome(req);
req.setEntity(new StringEntity(postData));
getClient().execute(req, new FutureCallback<HttpResponse>() {
@Override
public void completed(HttpResponse result) {
// switch to actor thread
execute(() -> res.resolve(result));
}
@Override
public void failed(Exception ex) {
// switch to actor thread
execute(() -> res.reject(ex));
}
@Override
public void cancelled() {
// switch to actor thread
execute(() -> res.reject("cancelled"));
}
});
} catch (Throwable th) {
Log.Warn(this, "get fail " + th + " " + url);
res.reject(th);
}
return res;
}
use of org.nustaq.kontraktor.IPromise in project kontraktor by RuedigerMoeller.
the class JNPM method npmInstall.
public IPromise<InstallResult> npmInstall(String module, String versionSpec, File importingModuleDir) {
if (versionSpec == null) {
versionSpec = "latest";
}
File nodeModule = new File(nodeModulesDir, module);
boolean installPrivate = false;
if (nodeModule.exists()) {
File targetDir = importingModuleDir.getName().equals("node_modules") ? nodeModulesDir : new File(importingModuleDir, "node_modules");
String moduleKey = createModuleKey(module, targetDir);
List<Promise> promises = packagesUnderway.get(moduleKey);
if (promises != null) {
int debug = 1;
}
String finalVersionSpec1 = versionSpec;
if (// timing: not unpacked
promises != null && promises.size() > 0) {
Log.Warn(this, "Delaying because in transfer:" + module + " " + targetDir.getAbsolutePath());
Promise p = new Promise();
delayed(1000, () -> npmInstall(module, finalVersionSpec1, importingModuleDir).then(p));
return p;
}
File pack = new File(nodeModule, "package.json");
if (pack.exists() && versionSpec.indexOf(".") > 0) {
String version = null;
String vspec = null;
try {
JsonObject pjson = Json.parse(new FileReader(pack)).asObject();
version = pjson.getString("version", null);
vspec = versionSpec;
if (!matches(version, vspec)) {
Log.Warn(this, "version mismatch for module '" + module + "'. requested:" + versionSpec + " from '" + importingModuleDir.getName() + "' installed:" + version + ". (delete module dir for update)");
if (config.getVersion(module) == null) {
installPrivate = true;
Log.Warn(this, " installing private " + module);
} else {
Log.Warn(this, " stick with mismatch because of jnpm.kson config entry for " + module);
}
}
} catch (Exception e) {
Log.Error(this, "can't parse package.json in " + module + " " + importingModuleDir.getAbsolutePath() + ". Retry");
Promise p = new Promise();
delayed(1000, () -> npmInstall(module, finalVersionSpec1, importingModuleDir).then(p));
return p;
}
} else
return resolve(InstallResult.EXISTS);
}
Promise p = new Promise();
// fire in parallel
IPromise<List<String>> versionProm = getVersions(module);
IPromise<JsonObject> distributionsProm = getDistributions(module);
String finalVersionSpec = versionSpec == null ? "latest" : versionSpec;
boolean finalInstallPrivate = installPrivate;
distributionsProm.then((dist, derr) -> {
if (dist == null) {
dist = new JsonObject();
Log.Error(this, "distribution is empty or error " + derr + " in module:" + module);
}
JsonObject finalDist = dist;
versionProm.then((versions, verr) -> {
if (versions == null) {
p.reject(verr);
return;
}
String resolvedVersion = getVersion(module, finalVersionSpec, versions, finalDist);
http.getContent(config.getRepo() + "/" + module + "/" + resolvedVersion).then((cont, err) -> {
if (cont != null) {
JsonObject pkg = Json.parse(cont).asObject();
String tarUrl = pkg.get("dist").asObject().get("tarball").asString();
JsonValue dependencies = pkg.get("dependencies");
if (dependencies == null)
dependencies = new JsonObject();
else
dependencies = dependencies.asObject();
JsonValue peerdependencies = pkg.get("peerDependencies");
if (peerdependencies != null) {
((JsonObject) dependencies).merge(peerdependencies.asObject());
}
File targetDir = finalInstallPrivate ? new File(importingModuleDir, "node_modules") : nodeModulesDir;
if (finalInstallPrivate)
targetDir.mkdirs();
IPromise depP = downLoadAndInstall(tarUrl, module, resolvedVersion, targetDir);
List deps = new ArrayList<>();
deps.add(depP);
File importingDir = new File(nodeModulesDir, module);
((JsonObject) dependencies).forEach(member -> {
deps.add(npmInstall(member.getName(), member.getValue().asString(), importingDir));
});
all(deps).then((r, e) -> {
p.resolve(InstallResult.INSTALLED);
});
} else {
p.reject("no such module");
}
});
});
});
return p;
}
use of org.nustaq.kontraktor.IPromise in project kontraktor by RuedigerMoeller.
the class JNPM method Install.
public static IPromise<InstallResult> Install(String module, String versionSpec, File modulesDir, JNPMConfig config) {
Promise p = new Promise();
JNPM unpkgCrawler = AsActor(JNPM.class, AsyncHttpActor.getSingleton().getScheduler());
unpkgCrawler.init(modulesDir, config);
unpkgCrawler.npmInstall(module, versionSpec, modulesDir).then((r, e) -> {
// Log.Info(JNPM.class,"DONE "+r+" "+e);
unpkgCrawler.stop();
p.complete(r, e);
});
return p;
}
Aggregations