Example usage for io.vertx.core DeploymentOptions setWorker

List of usage examples for io.vertx.core DeploymentOptions setWorker

Introduction

In this page you can find the example usage for io.vertx.core DeploymentOptions setWorker.

Prototype

public DeploymentOptions setWorker(boolean worker) 

Source Link

Document

Set whether the verticle(s) should be deployed as a worker verticle

Usage

From source file:io.silverware.microservices.utils.VertxUtils.java

License:Apache License

/**
 * Extracts the {@link DeploymentOptions} from {@link Deployment} annotation
 *
 * @param deploymentAnnotation {@link Deployment} annotation
 * @return {@link DeploymentOptions} for the given annotation
 *///from www.  j  a  v a 2s .  c  o  m
public static DeploymentOptions getDeploymentOptionsFromAnnotation(final Deployment deploymentAnnotation) {

    DeploymentOptions result = new DeploymentOptions();

    //if no deployment annotation is present return the default settings
    if (deploymentAnnotation == null) {
        return result;
    }

    //verticle type
    if (deploymentAnnotation.type() == VerticleType.WORKER) {
        result.setWorker(true);
    } else if (deploymentAnnotation.type() == VerticleType.MULTI_THREADED_WORKER) {
        result.setMultiThreaded(true);
    }

    //number of instances
    if (deploymentAnnotation.instances() > 1) {
        result.setInstances(deploymentAnnotation.instances());
    }

    //verticle isolation group
    if (!deploymentAnnotation.isolationGroup().isEmpty()) {
        result.setIsolationGroup(deploymentAnnotation.isolationGroup());
    }

    //verticle isolated classes
    if (deploymentAnnotation.isolatedClasses().length != 0) {
        result.setIsolatedClasses(Arrays.asList(deploymentAnnotation.isolatedClasses()));
    }

    //verticle extra classpath
    if (deploymentAnnotation.extraClasspath().length != 0) {
        result.setExtraClasspath(Arrays.asList(deploymentAnnotation.extraClasspath()));
    }

    //verticle high availability
    if (deploymentAnnotation.ha()) {
        result.setHa(true);
    }

    //verticle JSON config
    String jsonFileName = deploymentAnnotation.config();

    if (!jsonFileName.isEmpty()) {
        try (FileReader fileReader = new FileReader(jsonFileName)) {
            String jsonContent = IOUtils.toString(fileReader);
            result.setConfig(new JsonObject(jsonContent));
        } catch (Exception ex) {
            log.error("Invalid json config file: ", ex);
        }
    }

    return result;
}

From source file:io.silverware.microservices.utils.VertxUtils.java

License:Apache License

/**
 * Extracts the {@link DeploymentOptions} from the xml element
 *
 * @param verticleElement verticle element
 * @return the {@link DeploymentOptions} for the given verticle element
 *//* w  w w.ja v a  2 s .c  o  m*/
public static DeploymentOptions getDeploymentOptionsFromXml(final Node verticleElement) {

    DeploymentOptions result = new DeploymentOptions();
    NamedNodeMap attributes = verticleElement.getAttributes();

    for (int i = 0; i < attributes.getLength(); i++) {

        //verticle type
        if (attributes.getNamedItem(VertxConstants.TYPE) != null) {
            if (attributes.getNamedItem(VertxConstants.TYPE).getNodeValue()
                    .equals(VertxConstants.TYPE_WORKER)) {
                result.setWorker(true);
            } else if (attributes.getNamedItem(VertxConstants.TYPE).getNodeValue()
                    .equals(VertxConstants.TYPE_MULTI_THREADED_WORKER)) {
                result.setMultiThreaded(true);
            }
        }

        //number of instances
        if (attributes.getNamedItem(VertxConstants.INSTANCES) != null) {
            result.setInstances(
                    Integer.parseInt(attributes.getNamedItem(VertxConstants.INSTANCES).getNodeValue()));
        }

        //verticle isolation group
        if (attributes.getNamedItem(VertxConstants.ISOLATION_GROUP) != null) {
            result.setIsolationGroup(attributes.getNamedItem(VertxConstants.ISOLATION_GROUP).getNodeValue());
        }

        //verticle isolated classes
        if (attributes.getNamedItem(VertxConstants.ISOLATED_CLASSES) != null) {
            result.setIsolatedClasses(Arrays.asList(
                    attributes.getNamedItem(VertxConstants.ISOLATED_CLASSES).getNodeValue().split(" ")));
        }

        //verticle extra classpath
        if (attributes.getNamedItem(VertxConstants.EXTRA_CLASSPATH) != null) {
            result.setExtraClasspath(Arrays
                    .asList(attributes.getNamedItem(VertxConstants.EXTRA_CLASSPATH).getNodeValue().split(" ")));
        }

        //verticle high availability
        if (attributes.getNamedItem(VertxConstants.HA) != null) {
            result.setHa(Boolean.valueOf(attributes.getNamedItem(VertxConstants.HA).getNodeValue()));
        }

        //verticle JSON config
        if (attributes.getNamedItem(VertxConstants.CONFIG) != null) {
            try (FileReader fileReader = new FileReader(
                    attributes.getNamedItem(VertxConstants.CONFIG).getNodeValue())) {
                String jsonContent = IOUtils.toString(fileReader);
                result.setConfig(new JsonObject(jsonContent));
            } catch (Exception ex) {
                log.error("Invalid json config file: ", ex);
            }
        }
    }

    return result;
}

From source file:net.kuujo.vertigo.deployment.ComponentFactory.java

License:Apache License

@Override
public void resolve(String identifier, DeploymentOptions options, ClassLoader classLoader,
        Future<String> resolution) {

    identifier = VerticleFactory.removePrefix(identifier);
    JsonObject config = Configs.load(identifier);
    String main = config.getString("identifier");
    if (main == null) {
        throw new VertxException(identifier + " does not contain a identifier field");
    }//  w  w w  . j  a  v  a 2s. co m

    JsonObject deployment = config.getJsonObject("deployment");
    if (deployment != null) {
        if (deployment.containsKey("worker")) {
            options.setWorker(deployment.getBoolean("worker"));
        }
        if (deployment.containsKey("multi-threaded")) {
            options.setMultiThreaded(deployment.getBoolean("multi-threaded"));
        }
    }

    resolution.complete(main);
}

From source file:org.mustertech.webapp.vertxutils.VerticleDeployer.java

License:Open Source License

private static Promise<JsonObject, Exception, Double> deployWithOpts(JsonObject opt) {
    Deferred<JsonObject, Exception, Double> deffered = new DeferredObject<JsonObject, Exception, Double>();
    DeploymentOptions deployOpts = new DeploymentOptions();

    // Check and set Config option
    if (opt.containsKey("config")) {
        JsonObject vertCfg = opt.getJsonObject("config");
        deployOpts.setConfig(vertCfg);// w w  w.j a va 2  s  .c o m
    }

    // Check and set ExtraClasspath option
    if (opt.containsKey("extCps")) {
        JsonArray extCps = opt.getJsonArray("extCps");
        Iterator<Object> cpIter = extCps.iterator();

        ArrayList<String> extCpsList = new ArrayList<String>();
        while (cpIter.hasNext()) {
            extCpsList.add((String) cpIter.next());
        }

        deployOpts.setExtraClasspath(extCpsList);
    }

    // Check and set Isolated-Group option
    if (opt.containsKey("isolatedGrp")) {
        deployOpts.setIsolationGroup(opt.getString("isolatedGrp"));
    }

    // Check and set Isolated-Classes option
    if (opt.containsKey("isolatedCls")) {
        JsonArray isoCls = opt.getJsonArray("isolatedCls");
        Iterator<Object> clsIter = isoCls.iterator();

        ArrayList<String> isoClsList = new ArrayList<String>();
        while (clsIter.hasNext()) {
            isoClsList.add((String) clsIter.next());
        }

        deployOpts.setIsolatedClasses(isoClsList);
    }

    // Check and set HA option
    deployOpts.setHa(opt.containsKey("isHa") && opt.getBoolean("isHa"));

    // Check and set instances option
    deployOpts.setInstances(opt.containsKey("nInst") ? opt.getInteger("nInst").intValue() : 1);

    // Check and set Worker/MT option
    Boolean isWorker = (opt.containsKey("isWorker") && opt.getBoolean("isWorker"));
    if (isWorker) {
        deployOpts.setWorker(true);
        deployOpts.setMultiThreaded(opt.containsKey("isMt") && opt.getBoolean("isMt"));
    }

    String vertName = opt.getString("name");

    // Finally, deploy the verticle
    vertx.deployVerticle(vertName, deployOpts, ar -> {
        if (ar.succeeded()) {
            JsonObject resObj = new JsonObject();
            resObj.put("verticleName", vertName).put("deployId", ar.result());

            deffered.resolve(resObj);
        } else {
            Throwable thr = ar.cause();
            String defErr = vertName + " => Could not be deployed!";
            deffered.reject(
                    (null != thr.getMessage()) ? new Exception(thr.getMessage()) : new Exception(defErr));
        }
    });

    return deffered.promise();
}

From source file:se.liquidbytes.jel.JelStarter.java

License:Apache License

/**
 * Method that deploys the database verticle.
 *
 * @param future Future for reporting back success or failure of deployment
 * @param next Optional handler to call after a successfull deployment
 *///  w w  w  .  j  a  v a 2  s .  c  o  m
private static void deployDatabaseVerticle(Future<Void> future, Handler<Future<Void>> next) {
    DeploymentOptions deployOptions = new DeploymentOptions();
    deployOptions.setInstances(1);
    deployOptions.setWorker(true);
    JsonObject config = new JsonObject();
    config.put("storagepath", Settings.get("storagepath"));
    deployOptions.setConfig(config);

    vertx.deployVerticle(new DatabaseServiceVerticle(), deployOptions, res -> {
        if (res.failed()) {
            logger.error("Failed to deploy DatabaseService-verticle.", res.cause());
            future.fail(res.cause());
        } else {
            deploymentIds.push(res.result()); // Keep record on which verticles we successfully have deployed.
            logger.info("Successfully deployed DatabaseService-verticle.");
            if (next != null) {
                next.handle(future);
            } else {
                future.complete();
            }
        }
    });
}

From source file:se.liquidbytes.jel.JelStarter.java

License:Apache License

/**
 * Method that deploys the main JEL verticle.
 *
 * @param future Future for reporting back success or failure of deployment
 * @param next Optional handler to call after a successfull deployment
 *///from   www  . j  av  a  2 s.c  om
private static void deployMainJelVerticle(Future<Void> future, Handler<Future<Void>> next) {
    DeploymentOptions deployOptions = new DeploymentOptions();
    deployOptions.setInstances(1);
    deployOptions.setWorker(true);

    vertx.deployVerticle(new MainVerticle(), deployOptions, res -> {
        if (res.failed()) {
            logger.error("Failed to deploy MainJel-verticle.", res.cause());
            future.fail(res.cause());
        } else {
            deploymentIds.push(res.result()); // Keep record on which verticles we successfully have deployed.
            logger.info("Successfully deployed MainJel-verticle.");
            if (next != null) {
                next.handle(future);
            } else {
                future.complete();
            }
        }
    });
}

From source file:se.liquidbytes.jel.system.adapter.AdapterManager.java

License:Apache License

/**
 * Starts verticles for adaptertypes based upon the available adaptertypes and which adapters that should be running according to the adapters.json-file.
 *
 * @param adapterType if a adaptertype (plugin) has been registered, pass its plugin description to this method.
 *///from  ww  w.j a v  a  2s .co  m
private void startAdapters(PluginDesc adapterType) {
    if (adapterType != null && adapterTypes.containsKey(adapterType.getName())) {
        List<AdapterConfiguration> configurations = adaptersSettings.getAdapters();

        if (!adapters.containsKey(adapterType.getName())) {
            adapters.put(adapterType.getName(), new CopyOnWriteArrayList<>());
        }

        List<DeployedAdapter> adapterList = adapters.get(adapterType.getName());

        Promise promise = JelService.promiseFactory().create();

        for (AdapterConfiguration adapterConfig : configurations) {
            // Check that we only try to start adapters in config that are of our requested type.
            if (adapterConfig.getType().equals(adapterType.getName())) {
                promise.then((context, onResult) -> {
                    AdapterConfiguration adapterToStart = adapterConfig;

                    // Don't try to start the same adapter (same settings) multiple times.
                    for (DeployedAdapter adapter : adapterList) {
                        if (adapter.equals(adapterConfig)) {
                            adapterToStart = null; // An adapter with these settings are already running, so set this variable to not start.
                            break;
                        }
                    }

                    if (adapterToStart != null) {

                        try {
                            AbstractAdapter adapterInstance = (AbstractAdapter) JelService.pluginManager()
                                    .getPluginsInstance(adapterType, true);

                            JsonObject config = new JsonObject();
                            config.put("type", adapterToStart.getType()); // Name of adaptertype.
                            config.put("address", adapterToStart.getAddress()); // Address of adapter, could be a network TCP/IP address, but also the type of a physical port e.g. "/dev/ttyS0".
                            config.put("port", adapterToStart.getPort()); // Optional port of adapter, most commonly used by networked based adapter.
                            AdapterConfiguration deployedConfig = new AdapterConfiguration(config);

                            DeployedAdapter adapter = new DeployedAdapter();
                            adapter.config(deployedConfig);
                            adapter.setPluginDescription(adapterType);

                            // Stupid circular dependencies, but now we finally has the adapter id.
                            config.put("adapterId", adapter.Id());

                            DeploymentOptions deployOptions = new DeploymentOptions();
                            deployOptions.setConfig(config);
                            deployOptions.setInstances(1);
                            deployOptions.setWorker(true);

                            JelService.vertx().deployVerticle(adapterInstance, deployOptions, res -> {
                                if (res.succeeded()) {
                                    logger.info(
                                            "Successfully deployed verticle with id: {}, for adapter '{}' using address '{}' and port '{}'.",
                                            res.result(), deployedConfig.getType(), deployedConfig.getAddress(),
                                            deployedConfig.getPort());

                                    adapter.deploymentId(res.result());

                                    adapterList.add(adapter);

                                    JelService.vertx().eventBus().publish(InternalEvents.EVENTBUS_INTERNAL,
                                            adapter.toApi(), new DeliveryOptions().addHeader("action",
                                                    InternalEvents.EVENT_ADAPTER_STARTED));
                                    onResult.accept(true);
                                } else {
                                    logger.error(
                                            "Failed to deploy verticle for adapter '{}' using address '{}' and port '{}'.",
                                            deployedConfig.getType(), deployedConfig.getAddress(),
                                            deployedConfig.getPort(), res.cause());
                                    // Continue deploying other adapters.
                                    onResult.accept(true);
                                }
                            });
                        } catch (ClassCastException exception) {
                            logger.error(
                                    "Plugin, {}, is said to be a adapter but does not inheritage from AbstractAdapter-class, this must be fixed by plugin developer! Adapter will not be started.",
                                    adapterType.getName(), exception);
                            // Continue deploying other adapters.
                            onResult.accept(true);
                        }
                    } else {
                        // This adapter is already running so continue deploying other adapters.
                        onResult.accept(true);
                    }
                });
            }
        }
        // Start deploying adapters serially.
        promise.eval();
    }
}

From source file:se.liquidbytes.jel.system.adapter.AdapterManager.java

License:Apache License

/**
 * Starts verticle for adapter based upon which adapters that should be running according to the adapters.json-file.
 *
 * @param adapterConfig configuration of adapter.
 *//*  ww  w  .ja  v  a 2 s . com*/
private void startAdapter(AdapterConfiguration adapterConfig) {
    if (adapterConfig != null) {
        Optional<PluginDesc> plugin = JelService.pluginManager().getInstalledPlugins().stream()
                .filter(a -> a.getName().equals(adapterConfig.getType())).findFirst();
        if (!plugin.isPresent()) {
            logger.debug("No adaptertype with name '{}' registered yet, skipping this adapter.",
                    adapterConfig.getType());
        } else {
            try {
                AbstractAdapter adapterInstance = (AbstractAdapter) JelService.pluginManager()
                        .getPluginsInstance(plugin.get(), true);

                JsonObject config = new JsonObject();
                config.put("type", adapterConfig.getType()); // Name of adaptertype.
                config.put("address", adapterConfig.getAddress()); // Address of adapter, could be a network TCP/IP address, but also the type of a physical port e.g. "/dev/ttyS0".
                config.put("port", adapterConfig.getPort()); // Optional port of adapter, most commonly used by networked based adapter.
                AdapterConfiguration deployedConfig = new AdapterConfiguration(config);

                DeployedAdapter adapter = new DeployedAdapter();
                adapter.config(deployedConfig);
                adapter.setPluginDescription(plugin.get());

                // Stupid circular dependencies, but now we finally has the adapter id.
                config.put("adapterId", adapter.Id());

                DeploymentOptions deployOptions = new DeploymentOptions();
                deployOptions.setConfig(config);
                deployOptions.setInstances(1);
                deployOptions.setWorker(true);

                JelService.vertx().deployVerticle(adapterInstance, deployOptions, res -> {
                    if (res.succeeded()) {
                        logger.info(
                                "Successfully deployed verticle with id: {}, for adapter '{}' using address '{}' and port '{}'.",
                                res.result(), deployedConfig.getType(), deployedConfig.getAddress(),
                                deployedConfig.getPort());

                        if (!adapters.containsKey(deployedConfig.getType())) {
                            adapters.put(deployedConfig.getType(), new CopyOnWriteArrayList<>());
                        }

                        List<DeployedAdapter> adapterList = adapters.get(deployedConfig.getType());

                        adapter.deploymentId(res.result());

                        adapterList.add(adapter);

                        JelService.vertx().eventBus().publish(InternalEvents.EVENTBUS_INTERNAL, adapter.toApi(),
                                new DeliveryOptions().addHeader("action",
                                        InternalEvents.EVENT_ADAPTER_STARTED));
                    } else {
                        logger.error(
                                "Failed to deploy verticle for adapter '{}' using address '{}' and port '{}'.",
                                deployedConfig.getType(), deployedConfig.getAddress(), deployedConfig.getPort(),
                                res.cause());
                    }
                });
            } catch (ClassCastException exception) {
                logger.error(
                        "Plugin, {}, is said to be a adapter but does not inheritage from AbstractAdapter-class, this must be fixed by plugin developer! Adapter will not be started.",
                        plugin.get().getName(), exception);
            }
        }
    }
}