package io.vertx.service;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.DeploymentOptions;
import io.vertx.core.Promise;
import io.vertx.core.Verticle;
import io.vertx.core.json.DecodeException;
import io.vertx.core.json.JsonObject;
import io.vertx.core.spi.VerticleFactory;
import java.io.InputStream;
import java.util.NoSuchElementException;
import java.util.Scanner;
import java.util.concurrent.Callable;
public class ServiceVerticleFactory implements VerticleFactory {
@Override
public String prefix() {
return "service";
}
@Override
public void createVerticle(String verticleName, ClassLoader classLoader, Promise<Callable<Verticle>> promise) {
createVerticle(verticleName, new DeploymentOptions(), classLoader, promise);
}
protected void createVerticle(String verticleName, DeploymentOptions deploymentOptions, ClassLoader classLoader, Promise<Callable<Verticle>> promise) {
String identifier = VerticleFactory.removePrefix(verticleName);
String descriptorFile = identifier + ".json";
try {
JsonObject descriptor;
String main;
try (InputStream is = classLoader.getResourceAsStream(descriptorFile)) {
if (is == null) {
throw new IllegalArgumentException("Cannot find service descriptor file " + descriptorFile + " on classpath");
}
try (Scanner scanner = new Scanner(is, "UTF-8").useDelimiter("\\A")) {
String conf = scanner.next();
descriptor = new JsonObject(conf);
} catch (NoSuchElementException e) {
throw new IllegalArgumentException(descriptorFile + " is empty");
} catch (DecodeException e) {
throw new IllegalArgumentException(descriptorFile + " contains invalid json");
}
}
main = descriptor.getString("main");
if (main == null) {
throw new IllegalArgumentException(descriptorFile + " does not contain a main field");
}
;
JsonObject serviceOptions = descriptor.getJsonObject("options", new JsonObject());
serviceOptions.mergeIn(deploymentOptions.toJson());
promise.complete(() -> new AbstractVerticle() {
@Override
public void start(Promise<Void> startPromise) {
DeploymentOptions dopt = new DeploymentOptions(serviceOptions);
if (dopt.getConfig() == null) {
dopt.setConfig(new JsonObject());
}
dopt.getConfig().mergeIn(context.config());
vertx.deployVerticle(main, dopt, ar -> {
if (ar.succeeded()) {
startPromise.complete();
} else {
startPromise.fail(ar.cause());
}
});
}
});
} catch (Exception e) {
promise.fail(e);
}
}
}