private Verticle createVerticleFromBean(String beanName) { if (!beanFactory.containsBean(beanName)) { throw new IllegalArgumentException("No such bean: " + beanName); } if (!beanFactory.isTypeMatch(beanName, Verticle.class)) { throw new IllegalArgumentException("Bean \"" + beanName + "\" is not of type Verticle"); } if (beanFactory.isSingleton(beanName)) { throw new IllegalArgumentException("Verticle bean \"" + beanName + "\" is a singleton bean"); } logger.debug("Creating verticle from bean \"{}\"", beanName); return beanFactory.getBean(beanName, Verticle.class); }
@Override public Verticle createVerticle(String verticleName, ClassLoader classLoader) throws Exception { verticleName = VerticleFactory.removePrefix(verticleName); Class clazz; if (verticleName.endsWith(".java")) { CompilingClassLoader compilingLoader = new CompilingClassLoader(classLoader, verticleName); String className = compilingLoader.resolveMainClassName(); clazz = compilingLoader.loadClass(className); } else { clazz = classLoader.loadClass(verticleName); } Verticle instance = (Verticle)clazz.newInstance(); ConfigurationInjection.getConfigurationInjector().configure(instance); return instance; }
@Reference(unbind = "removeVerticle", policy=ReferencePolicy.DYNAMIC, cardinality = ReferenceCardinality.MULTIPLE) public void addVerticle(Verticle verticle) { LOGGER.info("Deploying verticle " + verticle); verticles.add(verticle); if (verticle == null) return; if (vertxService != null) vertxService.deployVerticle(verticle, deploy -> { if (deploy.succeeded()) { LOGGER.info("Deployment of verticle succeeded"); String id = deploy.result(); deployedVerticles.put(verticle, id); } else { LOGGER.log(Level.SEVERE, "Deployment of verticle failed", deploy.cause()); } }); }
@Test public void installExtendedBundle() throws Exception { logger.info("testing extender ... "); String bundlePath = "mvn:de.nierbeck.example.vertx/Vertx-Extended-Verticles/0.1.0-SNAPSHOT"; logger.info("installing bundle with url: {}", bundlePath); Bundle bundle = bc.installBundle(bundlePath); bundle.start(); int count = 0; while (bundle.getState() != Bundle.ACTIVE && count < 50) { Thread.sleep(1000); count = count++; } assertTrue (bundle.getState() == Bundle.ACTIVE); logger.info("Bundle is active"); Thread.sleep(1000); //wait a second so the service is registered. Collection<ServiceReference<Verticle>> serviceReferences = bc.getServiceReferences(Verticle.class, null); logger.info("found {} services", serviceReferences.size()); List<ServiceReference<Verticle>> collect = serviceReferences.stream().filter(serviceReference -> serviceReference.getBundle() == bundle).collect(Collectors.toList()); assertTrue(collect.size() > 0); }
public static void main(String[] args) { Vertx vertx = Vertx.vertx(); Verticle todoVerticle = new TodoVerticle(); final int port = Integer.getInteger("http.port", 8082); DeploymentOptions options = new DeploymentOptions() .setConfig(new JsonObject().put("http.port", port) ); vertx.deployVerticle(todoVerticle, options, res -> { if (res.succeeded()) System.out.println("Todo service is running at " + port + " port..."); else res.cause().printStackTrace(); }); }
@Inject public BootstrapVerticle(@Nullable @Named("bootstrap.filter") final String filterString, final Map<String, Verticle> verticleMap) { this.filter = filterFromString(filterString); this.verticles = verticleMap.entrySet().stream() .filter(e -> !NAME.equals(e.getKey()) && filter.test(e.getKey())) .collect(Collectors.toMap(Entry::getKey, Entry::getValue)); if (verticles.isEmpty()) { log.warn("No verticle participates in bootstrap? (are they discoverable, or filter '" + filter + "' filtered out all of them?)"); } else { log.debug("Bootstrap verticle(filter='" + filterString + "', verticles=" + verticles.keySet() + ")"); } }
@Override public void start(final Future<Void> startFuture) throws Exception { log.debug("Starting bootstrap verticle"); List<Future> futures = new ArrayList<>(verticles.size()); for (Verticle verticle : verticles.values()) { Future<Void> f = Future.future(); verticle.start(f); futures.add(f); } CompositeFuture.all(futures).setHandler(ar -> { if (ar.succeeded()) { startFuture.complete(); } else { startFuture.fail(ar.cause()); } }); }
@Override public void stop(final Future<Void> stopFuture) throws Exception { log.debug("Stopping bootstrap verticle"); List<Future> futures = new ArrayList<>(verticles.size()); for (Verticle verticle : verticles.values()) { Future<Void> f = Future.future(); verticle.stop(f); futures.add(f); } CompositeFuture.all(futures).setHandler(ar -> { if (ar.succeeded()) { stopFuture.complete(); } else { stopFuture.fail(ar.cause()); } }); }
public AMQPServiceImpl(Vertx vertx, AmqpServiceConfig config, Verticle parent) throws MessagingException { _vertx = vertx; _parent = parent; _eb = _vertx.eventBus(); _config = config; _msgTranslator = new MessageTranslator(); _msgBasedRouter = new MessageRouter(_config); _linkBasedRouter = new LinkRouter(); _linkManager = new LinkManager(vertx, _config, this); _replyToAddressPrefix = "amqp://" + _config.getInboundHost() + ":" + _config.getInboundPort(); _eb.consumer(config.getDefaultHandlerAddress(), this); for (String handlerAddress : config.getHandlerAddressList()) { _consumers.add(_eb.consumer(handlerAddress, this)); } // TODO _config.print() // prints the current config at start time. }
/** * @return the Java {@link Verticle} adapter for this Groovy Verticle */ public Verticle asJavaVerticle() { return new AbstractVerticle() { @Override public void start(Future<Void> startFuture) throws Exception { GroovyVerticle.this.vertx = super.vertx; GroovyVerticle.this.context = super.context; GroovyVerticle.this.start(startFuture); } @Override public void stop(Future<Void> stopFuture) throws Exception { GroovyVerticle.this.stop(stopFuture); } }; }
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()); }
@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()); }
public static void main(String[] args) { VertxOptions options = new VertxOptions(); options.setMaxEventLoopExecuteTime(Long.MAX_VALUE); final Vertx vertx = Vertx.factory.vertx(options); ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfiguration.class); Verticle serverVerticle = (Verticle) context.getBean("serverVerticle"); Verticle userDatabaseVerticle = (Verticle) context.getBean("userDatabaseVerticle"); Verticle blogServiceVerticle = (Verticle) context.getBean("blogServiceVerticle"); vertx.deployVerticle(serverVerticle); vertx.deployVerticle(userDatabaseVerticle, new DeploymentOptions().setWorker(true)); vertx.deployVerticle(blogServiceVerticle, new DeploymentOptions().setWorker(true)); }
private boolean isVerticleBeanDefinition(String beanName, BeanDefinition beanDefinition) { Class<?> beanClass = getBeanClass(beanName, beanDefinition); if (beanClass != null) { if (Verticle.class.isAssignableFrom(beanClass)) { return true; } if (FactoryBean.class.isAssignableFrom(beanClass) && beanDefinition instanceof AnnotatedBeanDefinition) { MethodMetadata factoryMethodMetadata = ((AnnotatedBeanDefinition) beanDefinition).getFactoryMethodMetadata(); if (factoryMethodMetadata != null && factoryMethodMetadata.isAnnotated(VerticleDeployment.class.getName())) { return true; } } } return false; }
/** * Loads a Verticle by instantiating the Java class first needed when * objects need to be handed over * * @param bc * the Base configuration * @return a future that resolves after loading */ private Future<Void> loadVerticleByClass(final BaseConfig bc) { final Future<Void> result = Future.future(); final String verticleId = bc.getVerticleName(); final DeploymentOptions options = this.getDeploymentOptions(bc); try { @SuppressWarnings("unchecked") final Class<Verticle> vClass = (Class<Verticle>) Class.forName(verticleId); final Verticle v = vClass.newInstance(); /* * This is the magic: we hand over the router to the verticle to be * used only sparingly */ if (v instanceof SFDCRouterExtension) { ((SFDCRouterExtension) v).addRoutes(this.router); } this.getVertx().deployVerticle(v, options, r -> { if (r.succeeded()) { final String vid = r.result(); this.logger.trace(verticleId + "started as " + vid); this.loadedVerticles.add(vid); result.complete(); } else { this.logger.fatal(r.cause()); result.fail(r.cause()); } }); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) { this.logger.fatal(e.getMessage(), e); result.fail(e); } return result; }
@Override public Verticle createVerticle(String verticleName, ClassLoader classLoader) throws Exception { verticleName = VerticleFactory.removePrefix(verticleName); // Use the provided class loader to create an instance of GuiceVerticleLoader. This is necessary when working with vert.x IsolatingClassLoader @SuppressWarnings("unchecked") Class<Verticle> loader = (Class<Verticle>) classLoader.loadClass(GuiceVerticleLoader.class.getName()); Constructor<Verticle> ctor = loader.getConstructor(String.class, ClassLoader.class, Injector.class); if (ctor == null) { throw new IllegalStateException("Could not find GuiceVerticleLoader constructor"); } return ctor.newInstance(verticleName, classLoader, getInjector()); }
public void removeVerticle(Verticle verticle) { LOGGER.info("Undeploying verticle " + verticle); verticles.remove(verticle); if (verticle == null) return; if (vertxService != null && deployedVerticles.get(verticle) != null) { String verticleId = deployedVerticles.get(verticle); if (vertxService.deploymentIDs().contains(verticleId)) { vertxService.undeploy(verticleId); } deployedVerticles.remove(verticle); } }
private void deploy(Verticle v, JsonObject conf, 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)); } }); }
private Future<String> deployAuthenticationService() { Future<String> result = Future.future(); if (!Verticle.class.isInstance(authenticationService)) { result.fail("authentication service is not a verticle"); } else { log.info("Starting authentication service {}", authenticationService); getVertx().deployVerticle((Verticle) authenticationService, result.completer()); } return result; }
private Future<String> deployAuthenticationService() { Future<String> result = Future.future(); if (!Verticle.class.isInstance(authenticationService)) { result.fail("authentication service is not a verticle"); } else { LOG.info("Starting authentication service {}", authenticationService); getVertx().deployVerticle((Verticle) authenticationService, result.completer()); } return result; }
/** * Deploy a new verticle with the standard configuration of this instance * @param cls the class of the verticle class to deploy * @return a single that will carry the verticle's deployment id */ protected Single<String> deployVerticle(Class<? extends Verticle> cls) { ObservableFuture<String> observable = RxHelper.observableFuture(); DeploymentOptions options = new DeploymentOptions().setConfig(config()); vertx.deployVerticle(cls.getName(), options, observable.toHandler()); return observable.toSingle(); }
public static void deployVerticle(Vertx vertx, Verticle verticle) throws InterruptedException { CountDownLatch latch = new CountDownLatch(1); vertx.deployVerticle(verticle, r -> { latch.countDown(); }); latch.await(1, TimeUnit.MINUTES); }
@DocAnnotation$annotation$(description = " When you add a new route with a regular expression, you can add named capture groups for parameters. <br/>\n However, if you need more complex parameters names (like \"param_name\"), you can add parameters names with\n this function. You have to name capture groups in regex with names: \"p0\", \"p1\", \"p2\", ... <br/>\n <br/>\n For example: If you declare route with regex \\/(?<p0>[a-z]*)\\/(?<p1>[a-z]*) and group names ") @Override public void start(Future<Void> startFuture) throws Exception { ClassLoader loader = module.runner.getModuleClassLoader(); Method introspector = loader.loadClass("io.vertx.ceylon.core.impl.resolveVerticles_").getDeclaredMethod("resolveVerticles", String.class, String.class); Map<String, Callable<?>> moduleFactories = (Map<String, Callable<?>>) introspector.invoke(null, module.name, null); Callable<?> factory = moduleFactories.values().iterator().next(); verticle = (Verticle) factory.call(); verticle.init(vertx, context); verticle.start(startFuture); }
@Override public Verticle createVerticle(final String identifierStr, final ClassLoader classLoader) throws Exception { final Identifier identifier = parseIdentifier(identifierStr); final Injector verticleInjector = injectorsByIdentifier.get(identifier); final BeanLocator beanLocator = verticleInjector.getInstance(BeanLocator.class); final Class clazz = tryToLoadClass(classLoader, identifier.getVerticleName()); if (clazz != null) { // try by class return lookup(beanLocator, Key.get(clazz)); } else { // try by name return lookup(beanLocator, Key.get(Verticle.class, Names.named(identifier.getVerticleName()))); } }
private static Verticle lookup(final BeanLocator beanLocator, final Key<Verticle> key) { Iterator<? extends BeanEntry<Annotation, Verticle>> iterator = beanLocator.locate(key).iterator(); if (iterator.hasNext()) { return iterator.next().getProvider().get(); // using provider to support non-singleton pattern } else { return null; } }
@Override public void verticleDeployed(Verticle verticle) { VerticleMetricsSupplier supplier = (VerticleMetricsSupplier) metricSuppliers.get(VERTICLES); if (supplier != null) { supplier.verticleDeployed(verticle); } }
@Override public void verticleUndeployed(Verticle verticle) { VerticleMetricsSupplier supplier = (VerticleMetricsSupplier) metricSuppliers.get(VERTICLES); if (supplier != null) { supplier.verticleUndeployed(verticle); } }
public void deployVerticle(Vertx vertx, Verticle verticle) { Observable<String> deployment = RxHelper.deployVerticle(vertx, verticle); deployment.subscribe(id -> { // Deployed }, err -> { // Could not deploy }); }
public void deployVerticle(Vertx vertx, Verticle verticle) { Single<String> deployment = RxHelper.deployVerticle(vertx, verticle); deployment.subscribe(id -> { // Deployed }, err -> { // Could not deploy }); }
@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); }
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; }
@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); }
@Override public void verticleDeployed(Verticle verticle) { Context context = Vertx.currentContext(); dispatch("verticleDeployed", listener -> listener.verticleDeployed(verticle, context)); }
@Override public void verticleUndeployed(Verticle verticle) { Context context = Vertx.currentContext(); dispatch("verticleUndeployed", listener -> listener.verticleUndeployed(verticle, context)); }
@Override default void verticleDeployed(Verticle verticle) { }
@Override default void verticleUndeployed(Verticle verticle) { }
@Override public void verticleDeployed(Verticle verticle) { dispatch(m -> m.verticleDeployed(verticle)); }
@Override public void verticleUndeployed(Verticle verticle) { dispatch(m -> m.verticleUndeployed(verticle)); }
@Override public Verticle createVerticle(String verticleName, ClassLoader classLoader) throws Exception { String beanName = getBeanNameFromVerticleName(verticleName); return createVerticleFromBean(beanName); }
public VerticleDeployedEvent(Verticle verticle, Context context) { super(verticle, context); }