示例#1
0
 public void close() {
   if (term != null) {
     term.close();
   } else {
     jobController.close(ar -> closedFuture.complete());
   }
 }
示例#2
0
  @Override
  public void start(Future<Void> fut) {
    // Demo html for now
    String html =
        "<link rel=\"stylesheet\" href=\"https://goo.gl/fUS2lx\">'\n"
            + "    + '<h1 style=\"color:navy;position:relative;top:50%;transform:translateY(-50%);\"'\n"
            + "    + 'align=\"center\" class=\"animated infinite rubberBand\">Hello Chatty</h1>";

    Router router = Router.router(vertx);
    router
        .route("/")
        .handler(
            routingContext -> {
              HttpServerResponse response = routingContext.response();
              response.putHeader("content-type", "text/html").end(html);
            });

    vertx
        .createHttpServer()
        .requestHandler(router::accept)
        .listen(
            8080,
            result -> {
              if (result.succeeded()) {
                fut.complete();
                System.out.println("Successfull deployed server at port 8080");
              } else {
                fut.fail(result.cause());
              }
            });
  }
 @Override
 public JDBCClient getConnection(Handler<AsyncResult<SQLConnection>> handler) {
   Context ctx = vertx.getOrCreateContext();
   exec.execute(
       () -> {
         Future<SQLConnection> res = Future.future();
         try {
           /*
           This can block until a connection is free.
           We don't want to do that while running on a worker as we can enter a deadlock situation as the worker
           might have obtained a connection, and won't release it until it is run again
           There is a general principle here:
           *User code* should be executed on a worker and can potentially block, it's up to the *user* to deal with
           deadlocks that might occur there.
           If the *service code* internally blocks waiting for a resource that might be obtained by *user code*, then
           this can cause deadlock, so the service should ensure it never does this, by executing such code
           (e.g. getConnection) on a different thread to the worker pool.
           We don't want to use the vert.x internal pool for this as the threads might end up all blocked preventing
           other important operations from occurring (e.g. async file access)
           */
           Connection conn = ds.getConnection();
           SQLConnection sconn = new JDBCConnectionImpl(vertx, conn);
           res.complete(sconn);
         } catch (SQLException e) {
           res.fail(e);
         }
         ctx.runOnContext(v -> res.setHandler(handler));
       });
   return this;
 }
示例#4
0
  /**
   * Check if the configuration has already been loaded, and if so return that, otherwise attempt to
   * load the configuration from the filesystem and save the result
   *
   * @param path path to the configuration file
   * @return future that eventually contains the JsonObject representing the configuration
   */
  @SuppressFBWarnings("SIC_INNER_SHOULD_BE_STATIC_ANON")
  private Future<JsonObject> getOrLoadConfig(final String path) {
    final Future<JsonObject> configFuture = Future.future();

    if (loadedConfigs.containsKey(path)) {
      configFuture.complete(loadedConfigs.get(path));
    } else {
      final Future<JsonObject> loadedConfigFuture = loadAndParseConfigFromFilesystem(path);
      loadedConfigFuture.setHandler(
          new AsyncResultHandler<JsonObject>() {
            @Override
            public void handle(AsyncResult<JsonObject> result) {
              if (result.succeeded()) {
                JsonObject loadedConfig = result.result();
                loadedConfigs.put(path, loadedConfig);
                configFuture.complete(loadedConfig);
              } else {
                configFuture.fail(result.cause());
              }
            }
          });
    }

    return configFuture;
  }
  @Override
  public void start(final Future<Void> startFuture) throws Exception {
    LOGGER.info("starting {0}..", identifier());

    // start the HELLO slacker protocol
    final JsonObject helloMessage =
        new JsonObject().put("i", identifier()).put("d", description()).put("v", version());
    vertx
        .eventBus()
        .send(
            "reg.slacker-server",
            helloMessage,
            result -> {
              if (result.succeeded() && JsonObject.class.isInstance(result.result().body())) {
                final JsonObject response = (JsonObject) result.result().body();
                if (response.containsKey("a")) {
                  // everything went smoothly - register the listener and complete the startup
                  registerListener(response.getString("a"));
                  LOGGER.info("successfully registered {0} executor", identifier());
                  startFuture.complete();
                } else {
                  failStart(startFuture, "no address to bind was received");
                }
              } else {
                // something unexpected happened
                failStart(
                    startFuture,
                    Optional.ofNullable(result.cause())
                        .map(Throwable::getMessage)
                        .orElse("invalid response"));
              }
            });
  }
示例#6
0
 private void checkAndSetStatus(AsyncResult<String> result, Future<Void> start) {
   ctr--;
   if (result.failed()) {
     start.fail(result.cause());
     failed = true;
     printError(result.cause());
   } else if (ctr == 0) {
     start.complete();
   }
 }
 private static Handler<AsyncResult<HttpServer>> futureTreatment(Future<Void> fut) {
   return result -> {
     if (result.succeeded()) {
       System.out.println("You can work on : http://localhost:8989/");
       fut.complete();
     } else {
       fut.fail(result.cause());
     }
   };
 }
示例#8
0
  public Future<JsonObject> load(Object field) {
    Future<JsonObject> configFuture;

    if (field != null) {
      if (field instanceof String) {
        configFuture = getOrLoadConfig((String) field);
      } else if (field instanceof JsonObject) {
        configFuture = Future.future();
        configFuture.complete((JsonObject) field);
      } else {
        configFuture = Future.future();
        configFuture.fail(
            new IllegalStateException(
                "Field `config` must contain an object or a string (path to the JSON config file)"));
      }
    } else {
      configFuture = Future.future();
      configFuture.complete(new JsonObject());
    }

    return configFuture;
  }
  @Override
  protected void startOverride(Future<Void> startFuture) throws Exception {
    connector = new SpringVerticleConnector();
    final ClassPathXmlApplicationContext spring =
        new ClassPathXmlApplicationContext(createVertxContext(connector));
    spring.setId(contextName);
    spring.getEnvironment().setActiveProfiles("production");
    spring.setConfigLocation(contextName);

    spring.refresh();

    spring.start();
    this.spring = spring;
    connector.startFuture().compose(e -> startFuture.complete(), startFuture);
  }
 public void start(Future<Void> fut) {
   Arrays.asList(publishers)
       .forEach(
           s ->
               vertx.setPeriodic(
                   sampleFrequence,
                   event -> {
                     System.out.println("sending message to kafka:" + kafkaPort);
                     executor.submit(
                         () -> {
                           producer.send(
                               topic, "message", createJson(s, 1, 15).getJsonObject(0).encode());
                         });
                   }));
   fut.complete();
 }
示例#11
0
  public ShellImpl init() {

    term.interruptHandler(key -> jobController().foregroundJob().interrupt());

    term.suspendHandler(
        key -> {
          term.echo(Helper.fromCodePoints(new int[] {key, '\n'}));
          Job job = jobController.foregroundJob();
          term.echo(statusLine(job, ExecStatus.STOPPED) + "\n");
          job.suspend();
          return true;
        });

    term.closeHandler(v -> jobController.close(ar -> closedFuture.complete()));
    if (welcome != null && welcome.length() > 0) {
      term.write(welcome);
    }
    return this;
  }
  @Override
  public void start(Future<Void> startFuture) throws Exception {
    Router router = Router.router(vertx);
    router.route().handler(BodyHandler.create());

    router.get("/info").handler(this::checkMemory);

    vertx
        .createHttpServer()
        .requestHandler(router::accept)
        .listen(
            8888,
            result -> {
              if (result.succeeded()) {
                startFuture.complete();
              } else {
                startFuture.fail(result.cause());
              }
            });
  }
  /**
   * Start the deployer.
   *
   * @param startFuture
   */
  @Override
  public void start(final Future<Void> startFuture) {

    // load the deployer.json when available
    JsonObject configuration = this.loadConfiguration();

    if (configuration != null) {

      deployed = new JsonArray();

      // assign loopback to this handler
      vertx.eventBus().localConsumer(LOOPBACK, this::deployVerticle);

      // copy the current verticle configuration
      workingCopy = configuration.getJsonObject(VERTICLES, new JsonObject()).copy();

      // set the global configuration
      globalConfig = configuration.getJsonObject(CONFIG, new JsonObject());

      // start iterations
      vertx
          .eventBus()
          .send(
              LOOPBACK,
              null,
              (AsyncResult<Message<Boolean>> event) -> {
                if (event.succeeded() && event.result().body()) {
                  LOG.log(
                      Level.INFO,
                      "Deployed {0} Verticles: {1}",
                      new Object[] {this.deployed.size(), deployed});
                  startFuture.complete();
                } else {
                  LOG.log(Level.SEVERE, "Deployment stopped: {0}", event.cause().getMessage());
                  startFuture.fail(event.cause());
                }
              });
    } else {
      LOG.info("No deployer.json found on the classpath.");
    }
  }
 @Override
 public void start(Future<Void> future) throws Exception {
   StompClient.create(vertx)
       .connect(
           ar -> {
             if (ar.failed()) {
               future.fail(ar.cause());
               return;
             }
             final StompClientConnection connection = ar.result();
             connection
                 .receivedFrameHandler(frame -> System.out.println("Client receiving:\n" + frame))
                 .writingFrameHandler(frame -> System.out.println("Client sending:\n" + frame))
                 .subscribe(
                     "/queue",
                     FRAMES::add,
                     frame -> {
                       if (!future.isComplete()) {
                         future.complete();
                       }
                     });
           });
 }
 @Override
 public void stop(final Future<Void> stopFuture) throws Exception {
   LOGGER.info("stopping {0}..", identifier());
   consumer.ifPresent(MessageConsumer::unregister);
   stopFuture.complete();
 }
 @Override
 protected void stopOverride(Future<Void> stopFuture) throws Exception {
   spring.destroy();
   connector.stopFuture().compose(e -> stopFuture.complete(), stopFuture);
 }
 @Override
 public void stop(Future<Void> stopFuture) throws Exception {
   producer.shutdown();
   stopFuture.complete();
 }