package io.vertx.service;
import io.vertx.core.DeploymentOptions;
import io.vertx.core.Future;
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;
public class ServiceVerticleFactory implements VerticleFactory {
@Override
public boolean requiresResolve() {
return true;
}
@Override
public void resolve(String identifier, DeploymentOptions deploymentOptions, ClassLoader classLoader, Promise<String> resolution) {
identifier = VerticleFactory.removePrefix(identifier);
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 depOptions = deploymentOptions.toJson();
JsonObject depConfig = depOptions.getJsonObject("config", new JsonObject());
JsonObject serviceOptions = descriptor.getJsonObject("options", new JsonObject());
JsonObject serviceConfig = serviceOptions.getJsonObject("config", new JsonObject());
depOptions.mergeIn(serviceOptions);
serviceConfig.mergeIn(depConfig);
depOptions.put("config", serviceConfig);
deploymentOptions.fromJson(depOptions);
resolution.complete(main);
} catch (Exception e) {
resolution.fail(e);
}
}
@Override
public String prefix() {
return "service";
}
@Override
public Verticle createVerticle(String verticleName, ClassLoader classLoader) throws Exception {
throw new IllegalStateException("Shouldn't be called");
}
}