io.vertx.core.Verticle Java Examples

The following examples show how to use io.vertx.core.Verticle. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AbstractApplicationTest.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
void testDeploySupportsMultipleServiceInstances(final VertxTestContext ctx) {

    final ObjectFactory<AbstractServiceBase<ServiceConfigProperties>> factory = mock(ObjectFactory.class);
    when(factory.getObject()).thenReturn(newServiceInstance());

    final ApplicationConfigProperties props = new ApplicationConfigProperties();
    props.setMaxInstances(2);
    application.setApplicationConfiguration(props);
    application.addServiceFactories(Set.of(factory));
    application.deployVerticles()
    .onComplete(ctx.succeeding(ok -> {
        verify(factory, times(2)).getObject();
        verify(vertx, times(2)).deployVerticle(any(Verticle.class), any(Handler.class));
        ctx.completeNow();
    }));
}
 
Example #2
Source File: Application.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
@Override
protected final Future<?> deployVerticles() {

    return super.deployVerticles().compose(ok -> {

        @SuppressWarnings("rawtypes")
        final List<Future> futures = new LinkedList<>();

        for (final Verticle verticle : this.verticles) {
            log.info("deploying verticle: {}", verticle);
            final Promise<String> result = Promise.promise();
            getVertx().deployVerticle(verticle, result);
            futures.add(result.future());
        }

        return CompositeFuture.all(futures);

    });

}
 
Example #3
Source File: Application.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
private Future<String> deployVerticle(final Object component) {

        if (component instanceof Verticle) {
            final Promise<String> result = Promise.promise();
            log.info("deploying component [{}]", component.getClass().getName());
            getVertx().deployVerticle((Verticle) component, result);
            return result.future().map(id -> {
                registerHealthCheckProvider(component);
                return id;
            });
        } else {
            return Future.failedFuture(String.format(
                    "cannot deploy component [%s]: not a Verticle",
                    serviceImplementation.getClass().getName()));
        }
    }
 
Example #4
Source File: SpringVerticleFactoryTest.java    From spring-vertx-ext with Apache License 2.0 6 votes vote down vote up
@Test
    public void testIsolatedContext() throws Exception {
        SpringVerticleFactory springVerticleFactory = createCleanSpringVerticleFactory();
        Vertx vertx = mock(Vertx.class);
        springVerticleFactory.init(vertx);
        Verticle verticle1 = springVerticleFactory.createVerticle(SpringTestVerticle.class.getName(), Thread.currentThread().getContextClassLoader());
        assertNotNull(verticle1);
        Verticle verticle2 = springVerticleFactory.createVerticle(SpringTestVerticle.class.getName(), Thread.currentThread().getContextClassLoader());
        assertNotNull(verticle2);
//        SpringTestVerticle v1 = SpringTestVerticle.class.cast(verticle1);
//        SpringTestVerticle v2 = SpringTestVerticle.class.cast(verticle2);
//        assertFalse(v1.equals(v2));
//        assertFalse(v1.getBean().equals(v2.getBean()));
//        assertEquals(v1.getBean().getClass().getCanonicalName(),v2.getBean().getClass().getCanonicalName());
//        assertFalse(v1.getSpringContext().equals(v2.getSpringContext()));
//        assertEquals(v1.getSpringContext().getClass().getCanonicalName(),v2.getSpringContext().getClass().getCanonicalName());
    }
 
Example #5
Source File: Application.java    From hono with Eclipse Public License 2.0 6 votes vote down vote up
@Override
protected final Future<?> deployVerticles() {

    return super.deployVerticles().compose(ok -> {

        @SuppressWarnings("rawtypes")
        final List<Future> futures = new LinkedList<>();

        for (final Verticle verticle : this.verticles) {
            log.info("deploying verticle: {}", verticle);
            final Promise<String> result = Promise.promise();
            getVertx().deployVerticle(verticle, result);
            futures.add(result.future());
        }

        return CompositeFuture.all(futures);

    });

}
 
Example #6
Source File: VertxUtils.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
public static <VERTICLE extends Verticle> boolean blockDeploy(Vertx vertx,
    Class<VERTICLE> cls,
    DeploymentOptions options) throws InterruptedException {
  Holder<Boolean> result = new Holder<>();

  CountDownLatch latch = new CountDownLatch(1);
  vertx.deployVerticle(cls.getName(), options, ar -> {
    result.value = ar.succeeded();

    if (ar.failed()) {
      LOGGER.error("deploy vertx failed, cause ", ar.cause());
    }

    latch.countDown();
  });

  latch.await();

  return result.value;
}
 
Example #7
Source File: Application.java    From enmasse with Apache License 2.0 6 votes vote down vote up
@Override
protected final Future<?> deployVerticles() {

    return super.deployVerticles().compose(ok -> {

        @SuppressWarnings("rawtypes")
        final List<Future> futures = new LinkedList<>();

        for (final Verticle verticle : this.verticles) {
            log.info("Deploying: {}", verticle);
            final Promise<String> result = Promise.promise();
            getVertx().deployVerticle(verticle, result);
            futures.add(result.future());
        }

        return CompositeFuture.all(futures);

    });

}
 
Example #8
Source File: SpringVerticleFactory.java    From spring-vertx-ext with Apache License 2.0 6 votes vote down vote up
private Verticle createSpringVerticle(final Class<?> currentVerticleClass, ClassLoader classLoader) {
    final SpringVerticle annotation = currentVerticleClass.getAnnotation(SpringVerticle.class);
    final Class<?> springConfigClass = annotation.springConfig();
    
    // Create the parent context  
    final GenericApplicationContext genericApplicationContext = getGenericApplicationContext(
        classLoader);

    // 1. Create a new context for each verticle and use the specified spring configuration class if possible
    AnnotationConfigApplicationContext annotationConfigApplicationContext = getAnnotationConfigApplicationContext(
        springConfigClass, genericApplicationContext);

    // 2. Register the Vertx instance as a singleton in spring context
    annotationConfigApplicationContext.getBeanFactory().registerSingleton(vertx.getClass().getSimpleName(), vertx);

    // 3. Register a bean definition for this verticle
    annotationConfigApplicationContext.registerBeanDefinition(currentVerticleClass.getSimpleName(), new VerticleBeanDefinition(currentVerticleClass));
    
    // 4. Add a bean factory post processor to avoid configuration issues
    addPostprocessorAndUpdateContext(currentVerticleClass, annotationConfigApplicationContext);
    
    // 5. Return the verticle by fetching the bean from the context
    return (Verticle) annotationConfigApplicationContext.getBeanFactory().getBean(currentVerticleClass.getSimpleName());
}
 
Example #9
Source File: RxifiedExamples.java    From vertx-rx with Apache License 2.0 5 votes vote down vote up
public void deployVerticle(Vertx vertx, Verticle verticle) {
  Single<String> deployment = RxHelper.deployVerticle(vertx, verticle);

  deployment.subscribe(id -> {
    // Deployed
  }, err -> {
    // Could not deploy
  });
}
 
Example #10
Source File: AbstractApplicationTest.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@BeforeEach
public void setUp() {
    vertx = mock(Vertx.class);
    doAnswer(invocation -> {
        final Handler<AsyncResult<String>> resultHandler = invocation.getArgument(1);
        resultHandler.handle(Future.succeededFuture("id"));
        return null;
    }).when(vertx).deployVerticle(any(Verticle.class), any(Handler.class));
    application = new AbstractApplication() {
    };
    application.setVertx(vertx);
}
 
Example #11
Source File: Application.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Sets the service to use for authenticating clients.
 *
 * @param service The service.
 * @throws NullPointerException if service is {@code null}.
 * @throws IllegalArgumentException if the given service is not a {@code Verticle}.
 */
@Autowired
public void setAuthenticationService(final AuthenticationService service) {
    Objects.requireNonNull(service);
    if (!(service instanceof Verticle)) {
        throw new IllegalArgumentException("authentication service must be a vert.x Verticle");
    }
    this.authService = service;
}
 
Example #12
Source File: DeploymentTest.java    From vertx-lang-groovy with Apache License 2.0 5 votes vote down vote up
@Test
public void testDeployVerticleClassInstance() throws Exception {
  Class clazz = assertScript("LifeCycleVerticleClass");
  Verticle verticle = (Verticle) clazz.newInstance();
  assertDeploy((vertx, onDeploy) ->
      vertx.deployVerticle(
          verticle,
          onDeploy));
  assertTrue(isStarted());
  assertTrue(isStopped());
}
 
Example #13
Source File: RxifiedExamples.java    From vertx-rx with Apache License 2.0 5 votes vote down vote up
public void deployVerticle(Vertx vertx, Verticle verticle) {
  Observable<String> deployment = RxHelper.deployVerticle(vertx, verticle);

  deployment.subscribe(id -> {
    // Deployed
  }, err -> {
    // Could not deploy
  });
}
 
Example #14
Source File: SpringVerticleFactory.java    From spring-vertx-ext with Apache License 2.0 5 votes vote down vote up
@Override
public synchronized Verticle createVerticle(final String verticleName, final ClassLoader classLoader) throws Exception {
    final String className = VerticleFactory.removePrefix(verticleName);
    Class<?> clazz;
    if (className.endsWith(SUFFIX)) {
        CompilingClassLoader compilingLoader = new CompilingClassLoader(classLoader, className);
        clazz = compilingLoader.loadClass(compilingLoader.resolveMainClassName());
    } else {
        clazz = classLoader.loadClass(className);
    }
    return createVerticle(clazz, classLoader);
}
 
Example #15
Source File: MainDeploy.java    From okapi with Apache License 2.0 5 votes vote down vote up
private void deploy(Verticle v, Vertx vertx, Handler<AsyncResult<Vertx>> fut) {
  DeploymentOptions opt = new DeploymentOptions().setConfig(conf);
  vertx.deployVerticle(v, opt, dep -> {
    if (dep.failed()) {
      fut.handle(Future.failedFuture(dep.cause()));
    } else {
      fut.handle(Future.succeededFuture(vertx));
    }
  });
}
 
Example #16
Source File: SpringVerticleFactory.java    From spring-vertx-ext with Apache License 2.0 5 votes vote down vote up
private Verticle createVerticle(final Class<?> clazz, ClassLoader classLoader) throws Exception {

        if (clazz.isAnnotationPresent(SpringVerticle.class)) {
            return createSpringVerticle(clazz, classLoader);
        } else if (Verticle.class.isAssignableFrom(clazz)) {
            // init a non spring verticle, but this should not happen
            final Verticle verticle = Verticle.class.cast(clazz.newInstance());
            verticle.init(vertx, vertx.getOrCreateContext());
            return verticle;
        }

        return null;
    }
 
Example #17
Source File: SpringVerticleFactoryTest.java    From spring-vertx-ext with Apache License 2.0 5 votes vote down vote up
@Test
    public void testDeployVerticle() throws Exception {
        SpringVerticleFactory springVerticleFactory = createCleanSpringVerticleFactory();
        Vertx vertx = mock(Vertx.class);
        springVerticleFactory.init(vertx);
        Verticle verticle = springVerticleFactory.createVerticle(SpringTestVerticle.class.getName(), Thread.currentThread().getContextClassLoader());
//        verticle.start(null);
        // note the verticle returned is an cglib enhanced class!!
//        assertEquals(SpringTestVerticle.class.getSimpleName(), verticle.getClass().getSuperclass().getSimpleName());
//        assertEquals(vertx, verticle.getVertx());
//        assertTrue(SpringTestVerticle.class.isAssignableFrom(verticle.getClass()));
//        SpringTestVerticle v1 = SpringTestVerticle.class.cast(verticle);
//        assertEquals(v1.getBean().getClass(), TestService.class);
    }
 
Example #18
Source File: NetworkDiscoveryTest.java    From orion with Apache License 2.0 5 votes vote down vote up
private AsyncCompletion deployVerticle(final Verticle verticle) {
  final CompletableAsyncCompletion completion = AsyncCompletion.incomplete();
  vertx.deployVerticle(verticle, result -> {
    if (result.succeeded()) {
      completion.complete();
    } else {
      completion.completeExceptionally(result.cause());
    }
  });
  return completion;
}
 
Example #19
Source File: FeatherVerticleFactory.java    From kyoko with MIT License 5 votes vote down vote up
@Override
public Verticle createVerticle(String s, ClassLoader classLoader) throws Exception {
    var className = VerticleFactory.removePrefix(s);
    Class<? extends Verticle> clazz;
    try {
        clazz = classLoader.loadClass(className).asSubclass(Verticle.class);
    } catch (ClassNotFoundException e) {
        var cls = (Class<?>) injector.instance(ModuleManager.class).findClass(className);
        clazz = cls.asSubclass(Verticle.class);
    }
    return injector.instance(clazz);
}
 
Example #20
Source File: MqttConsumerBootstrap.java    From spring-boot-protocol with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
    Verticle verticle = new AbstractVerticle() {
        @Override
        public void start() {
            MqttClient client = MqttClient.create(vertx, new MqttClientOptions()
                    //开启遗言
                    .setWillFlag(true)
                    .setWillTopic("willTopic")
                    .setWillMessage("hello")

                    .setUsername("admin")
                    .setPassword("123456")
                    .setMaxMessageSize(8192));

            client.connect(PORT,HOST,s -> {
                client.publishHandler(response -> {
                    String message = new String(response.payload().getBytes());
                    logger.info("接收到消息: {} from topic {}", message, response.topicName());
                });

                client.subscribe("#", MqttQoS.AT_LEAST_ONCE.value(), resp -> {
                    logger.info("subscribe {}", resp);
                });
            });
        }
    };
    Vertx.vertx().deployVerticle(verticle);
}
 
Example #21
Source File: MqttProducerBootstrap.java    From spring-boot-protocol with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) {
    Verticle verticle = new AbstractVerticle() {
        @Override
        public void start() {
            MqttClient client = MqttClient.create(vertx, new MqttClientOptions()
                    //开启遗言
                    .setWillFlag(true)
                    .setWillTopic("willTopic")
                    .setWillMessage("hello")

                    .setUsername("admin")
                    .setPassword("123456")
                    .setMaxMessageSize(8192));


            client.connect(PORT,HOST, asyncResult -> {
                Runnable publishTask = () -> {
                    Buffer buffer = Buffer.buffer("发布数据" + PUBLISH_COUNT.incrementAndGet());
                    client.publish("/hello",buffer,
                            MqttQoS.EXACTLY_ONCE, true, true,
                            asyncResult1 -> {
                                if (asyncResult1.succeeded()) {
                                    logger.info("publish {}", asyncResult1);
                                }
                            }
                    );
                };
                Executors.newScheduledThreadPool(1)
                        .scheduleAtFixedRate(publishTask, 0, 15, TimeUnit.MILLISECONDS);
            });
        }
    };
    Vertx.vertx().deployVerticle(verticle);
}
 
Example #22
Source File: WisdomInternalVerticleFactory.java    From wisdom with Apache License 2.0 4 votes vote down vote up
@Override
public Verticle createVerticle(String verticleName, ClassLoader classLoader) throws Exception {
    return new WisdomServiceVerticle(accessor, servers);
}
 
Example #23
Source File: TypeScriptVerticleFactory.java    From vertx-lang-typescript with Apache License 2.0 4 votes vote down vote up
@Override
public Verticle createVerticle(String verticleName, ClassLoader classLoader) throws Exception {
  Verticle v = delegateFactory.createVerticle(verticleName, classLoader);
  return new TypeScriptVerticle(v);
}
 
Example #24
Source File: Application.java    From enmasse with Apache License 2.0 4 votes vote down vote up
@Autowired
public void setVerticles(final List<Verticle> verticles) {
    this.verticles = verticles;
}
 
Example #25
Source File: Application.java    From enmasse with Apache License 2.0 4 votes vote down vote up
@Override
protected final Future<?> deployVerticles() {

    return super.deployVerticles()

            .compose(ok -> {

                @SuppressWarnings("rawtypes")
                final List<Future> futures = new LinkedList<>();

                for (final Verticle verticle : this.verticles) {
                    log.info("Deploying: {}", verticle);
                    final Promise<String> result = Promise.promise();
                    getVertx().deployVerticle(verticle, result);
                    futures.add(result.future());
                }

                return CompositeFuture.all(futures);

            });

}
 
Example #26
Source File: Application.java    From enmasse with Apache License 2.0 4 votes vote down vote up
@Autowired
public void setVerticles(final List<Verticle> verticles) {
    this.verticles = verticles;
}
 
Example #27
Source File: FactoryTest.java    From spring-vertx-ext with Apache License 2.0 4 votes vote down vote up
@Test
public void testCreateVerticle() throws Exception {
    String identifier = SpringVerticleFactory.PREFIX + ":" + SpringTestVerticle.class.getName();
    Verticle verticle = factory.createVerticle(identifier, Thread.currentThread().getContextClassLoader());
    assertNotNull(verticle);
}
 
Example #28
Source File: Application.java    From enmasse with Apache License 2.0 4 votes vote down vote up
@Override
protected final Future<?> deployVerticles() {

    return super.deployVerticles()

            .compose(ok -> {

                @SuppressWarnings("rawtypes")
                final List<Future> futures = new LinkedList<>();

                for (final Verticle verticle : this.verticles) {
                    log.info("Deploying: {}", verticle);
                    final Promise<String> result = Promise.promise();
                    getVertx().deployVerticle(verticle, result);
                    futures.add(result.future());
                }

                return CompositeFuture.all(futures);

            });

}
 
Example #29
Source File: KonduitServlet.java    From konduit-serving with Apache License 2.0 4 votes vote down vote up
@Override
public void init(ServletConfig config) throws ServletException {
    super.init(config);
    vertx = Vertx.vertx();
    httpClient = vertx.createHttpClient();

    String configStorePath = System.getProperty(CONFIG_JSON);
    JsonObject config1 = new JsonObject();
    config1.put("path", configStorePath);
    ConfigStoreOptions httpStore = new ConfigStoreOptions()
            .setType("file")
            .setOptional(true)
            .setConfig(config1);

    CountDownLatch countDownLatch = new CountDownLatch(2);
    ConfigRetrieverOptions options = new ConfigRetrieverOptions()
            .addStore(httpStore);
    ConfigRetriever retriever = ConfigRetriever.create(vertx, options);
    String verticleClassName = System.getProperty(CLASS_NAME);
    retriever.getConfig(ar -> {
        if (ar.failed() || !new File(configStorePath).exists()) {
            log("Unable to find configuration. Continuing without.");
            log.debug("Unable to find configuration. Continuing without.");
            vertxConfig = new JsonObject().put("httpPort", DEFAULT_HTTP_PORT);
        } else {
            JsonObject config2 = ar.result();
            vertxConfig = config2;

        }

        log.debug("Attempting to deploy verticle " + verticleClassName);
        log("Attempting to deploy verticle " + verticleClassName);
        DeploymentOptions deploymentOptions = new DeploymentOptions()
                .setConfig(vertxConfig).setWorker(true)
                .setHa(false).setInstances(1)
                .setWorkerPoolSize(1);

        String[] split = verticleClassName.split("\\.");
        vertx.registerVerticleFactory(new VerticleFactory() {
            @Override
            public String prefix() {
                return split[split.length - 1];
            }

            @Override
            public Verticle createVerticle(String s, ClassLoader classLoader) throws Exception {
                Object verticle = classLoader.loadClass(verticleClassName).newInstance();
                Verticle syntaxNetVerticle = (Verticle) verticle;
                countDownLatch.countDown();
                return syntaxNetVerticle;
            }
        });


        vertx.deployVerticle(verticleClassName, deploymentOptions, handler -> {
            if (handler.failed()) {
                log.error("Unable to deploy verticle", handler.cause());
                log("Unable to deploy verticle", handler.cause());
            } else {
                log.debug("Deployed verticle");
                log("Deployed verticle");
                countDownLatch.countDown();

            }

        });

    });

    log("Initializing server");
    log.debug("Initializing server");
    try {
        countDownLatch.await();
    } catch (InterruptedException e) {
        log("Interrupting await call for servlet start", e.getCause());
        Thread.currentThread().interrupt();
    }

    log("Initialized server");
    log.debug("Initialized server");

}
 
Example #30
Source File: Application.java    From hono with Eclipse Public License 2.0 4 votes vote down vote up
@Autowired
public void setVerticles(final List<Verticle> verticles) {
    this.verticles = verticles;
}