コード例 #1
0
  @Override
  public void render(
      RoutingContext context, String templateFileName, Handler<AsyncResult<Buffer>> handler) {
    try {
      Template template = cache.get(templateFileName);
      if (template == null) {
        // real compile
        synchronized (this) {
          loader.setVertx(context.vertx());
          // Compile
          template = config.getTemplate(adjustLocation(templateFileName));
        }
        cache.put(templateFileName, template);
      }

      Map<String, RoutingContext> variables = new HashMap<>(1);
      variables.put("context", context);

      try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
        template.process(variables, new OutputStreamWriter(baos));
        handler.handle(Future.succeededFuture(Buffer.buffer(baos.toByteArray())));
      }

    } catch (Exception ex) {
      handler.handle(Future.failedFuture(ex));
    }
  }
コード例 #2
0
 private void notifyHandler(ChannelFuture future) {
   if (future.isSuccess()) {
     handler.handle(Future.succeededFuture(result));
   } else {
     handler.handle(Future.failedFuture(future.cause()));
   }
 }
コード例 #3
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());
              }
            });
  }
コード例 #4
0
ファイル: ConfigLoader.java プロジェクト: groupon/vertx-utils
  /**
   * 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;
  }
コード例 #5
0
 @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;
 }
コード例 #6
0
 @Test
 public void testCompleteTwice() {
   ObservableFuture<String> o = RxHelper.observableFuture();
   MySubscriber<String> subscriber = new MySubscriber<>();
   o.subscribe(subscriber);
   o.toHandler().handle(Future.succeededFuture("abc"));
   o.toHandler().handle(Future.succeededFuture("def"));
   subscriber.assertItem("abc").assertCompleted().assertEmpty();
 }
コード例 #7
0
 @Test
 public void testFailTwice() {
   ObservableFuture<String> o = RxHelper.observableFuture();
   MySubscriber<String> subscriber = new MySubscriber<>();
   o.subscribe(subscriber);
   Throwable failure = new Throwable();
   o.toHandler().handle(Future.failedFuture(failure));
   o.toHandler().handle(Future.failedFuture(new Throwable()));
   subscriber.assertError(failure).assertEmpty();
 }
コード例 #8
0
ファイル: InitVerticle.java プロジェクト: outofcoffee/apiman
 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();
   }
 }
コード例 #9
0
 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());
     }
   };
 }
コード例 #10
0
 private void writeBody(
     HttpClientRequest clientRequest,
     MailgunSendRequest sendRequest,
     Handler<AsyncResult<Void>> completionHandler) {
   EmailEntity emailEntity = sendRequest.getEmailEntity();
   if (emailEntity == null) {
     if (completionHandler != null) {
       completionHandler.handle(Future.failedFuture(new Exception("Null Email Entity.")));
     }
     return;
   }
   if (emailEntity.getFrom() == null || emailEntity.getFrom().isEmpty()) {
     if (completionHandler != null) {
       completionHandler.handle(Future.failedFuture(new Exception("Null or Empty From Field.")));
     }
     return;
   }
   if (emailEntity.getTo() == null || emailEntity.getTo().isEmpty()) {
     if (completionHandler != null) {
       completionHandler.handle(Future.failedFuture(new Exception("Null or Empty To Field.")));
     }
     return;
   }
   MultiPartUtility mpu = new MultiPartUtility();
   // from
   mpu.formField("from", emailEntity.getFrom());
   // to
   String[] toList = emailEntity.getTo().split(";|,|\\s");
   for (String to : toList) {
     mpu.formField("to", to);
   }
   // cc
   if (emailEntity.getCc() != null && !emailEntity.getCc().isEmpty()) {
     String[] ccList = emailEntity.getCc().split(";|,|\\s");
     for (String cc : ccList) {
       mpu.formField("cc", cc);
     }
   }
   // subject
   mpu.formField(
       "subject",
       (emailEntity.getSubject() == null ? "" : sendRequest.getEmailEntity().getSubject()));
   // text
   if (emailEntity.getTextBody() != null && !emailEntity.getTextBody().isEmpty()) {
     mpu.formField("text", emailEntity.getTextBody());
   }
   // html
   if (emailEntity.getHtmlBody() != null && !emailEntity.getHtmlBody().isEmpty()) {
     mpu.formField("html", emailEntity.getHtmlBody());
   }
   // write to client
   clientRequest.write(mpu.get());
 }
コード例 #11
0
    public void doUndeploy(
        ContextImpl undeployingContext, Handler<AsyncResult<Void>> completionHandler) {

      if (!children.isEmpty()) {
        final int size = children.size();
        AtomicInteger childCount = new AtomicInteger();
        for (Deployment childDeployment : new HashSet<>(children)) {
          childDeployment.doUndeploy(
              undeployingContext,
              ar -> {
                children.remove(childDeployment);
                if (ar.failed()) {
                  reportFailure(ar.cause(), undeployingContext, completionHandler);
                } else if (childCount.incrementAndGet() == size) {
                  // All children undeployed
                  doUndeploy(undeployingContext, completionHandler);
                }
              });
        }
      } else {
        undeployed = true;
        context.runOnContext(
            v -> {
              Future<Void> stopFuture = new FutureResultImpl<>();
              stopFuture.setHandler(
                  ar -> {
                    deployments.remove(id);
                    context.runCloseHooks(
                        ar2 -> {
                          if (ar2.failed()) {
                            // Log error but we report success anyway
                            log.error("Failed to run close hook", ar2.cause());
                          }
                          if (ar.succeeded()) {
                            reportSuccess(null, undeployingContext, completionHandler);
                          } else {
                            reportFailure(ar.cause(), undeployingContext, completionHandler);
                          }
                        });
                  });
              try {
                verticle.stop(stopFuture);
              } catch (Throwable t) {
                stopFuture.setFailure(t);
              }
            });
      }
    }
コード例 #12
0
 @Test
 public void testFulfillAdaptedFunctions2() {
   MySubscriber<String> subscriber = new MySubscriber<>();
   Handler<AsyncResult<String>> o = RxHelper.toFuture(subscriber::onNext, subscriber::onError);
   o.handle(Future.succeededFuture("abc"));
   subscriber.assertItem("abc").assertEmpty();
 }
コード例 #13
0
ファイル: FileResolver.java プロジェクト: ljie-PI/vert.x
 private void deleteCacheDir(Handler<AsyncResult<Void>> handler) {
   if (cacheDir != null && cacheDir.exists()) {
     vertx.fileSystem().deleteRecursive(cacheDir.getAbsolutePath(), true, handler);
   } else {
     handler.handle(Future.succeededFuture());
   }
 }
コード例 #14
0
 @Test
 public void testFulfillAdaptedSubscriber() {
   MySubscriber<String> subscriber = new MySubscriber<>();
   Handler<AsyncResult<String>> o = RxHelper.toFuture(subscriber);
   o.handle(Future.succeededFuture("abc"));
   subscriber.assertItem("abc").assertCompleted().assertEmpty();
 }
コード例 #15
0
ファイル: ShellImpl.java プロジェクト: vert-x3/vertx-shell
 public void close() {
   if (term != null) {
     term.close();
   } else {
     jobController.close(ar -> closedFuture.complete());
   }
 }
コード例 #16
0
 @Test
 public void testAssertAsyncFailureHandlerThrowsFailure() throws Exception {
   RuntimeException cause = new RuntimeException();
   BlockingQueue<Handler<AsyncResult<String>>> handlerQueue = new ArrayBlockingQueue<>(1);
   TestSuite suite =
       TestSuite.create("my_suite")
           .test(
               "my_test",
               context -> {
                 handlerQueue.add(
                     context.<String>asyncAssertFailure(
                         r -> {
                           throw cause;
                         }));
               });
   TestReporter reporter = new TestReporter();
   run(suite, reporter);
   Handler<AsyncResult<String>> handler = handlerQueue.poll(2, TimeUnit.SECONDS);
   handler.handle(Future.failedFuture(new Throwable()));
   reporter.await();
   assertEquals(0, reporter.exceptions.size());
   assertEquals(1, reporter.results.size());
   assertTrue(reporter.results.get(0).failed());
   assertSame(cause, reporter.results.get(0).failure().cause());
 }
コード例 #17
0
  @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"));
              }
            });
  }
コード例 #18
0
 @Test
 public void testAssertAsyncFailureFailed() throws Exception {
   BlockingQueue<Handler<AsyncResult<String>>> handlerQueue = new ArrayBlockingQueue<>(1);
   AtomicBoolean called = new AtomicBoolean();
   TestSuite suite =
       TestSuite.create("my_suite")
           .test(
               "my_test",
               context -> {
                 handlerQueue.add(
                     context.<String>asyncAssertFailure(
                         r -> {
                           called.set(true);
                         }));
               });
   TestReporter reporter = new TestReporter();
   run(suite, reporter);
   Handler<AsyncResult<String>> handler = handlerQueue.poll(2, TimeUnit.SECONDS);
   handler.handle(Future.succeededFuture("foo"));
   reporter.await();
   assertFalse(called.get());
   assertEquals(0, reporter.exceptions.size());
   assertEquals(1, reporter.results.size());
   assertEquals("my_test", reporter.results.get(0).name());
   assertTrue(reporter.results.get(0).failed());
 }
コード例 #19
0
ファイル: ConfigLoader.java プロジェクト: groupon/vertx-utils
  /**
   * Load configuration from the filesystem and parse it into a JsonObject
   *
   * @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> loadAndParseConfigFromFilesystem(final String path) {
    final Future<JsonObject> configFuture = Future.future();

    fileSystem.readFile(
        path,
        new AsyncResultHandler<Buffer>() {
          @Override
          @SuppressFBWarnings("REC_CATCH_EXCEPTION")
          public void handle(AsyncResult<Buffer> result) {
            if (result.succeeded()) {
              try {
                final ConfigParser configParser = getConfigParser();
                JsonObject loadedConfig = configParser.parse(result.result().toString());
                configFuture.complete(loadedConfig);
              } catch (Exception e) {
                configFuture.fail(e);
              }
            } else {
              configFuture.fail(result.cause());
            }
          }
        });

    return configFuture;
  }
コード例 #20
0
 private static void executeErrorState(
     String methodId,
     Vertx vertx,
     Consumer<Throwable> errorMethodHandler,
     RoutingContext context,
     Map<String, String> headers,
     Encoder encoder,
     Consumer<Throwable> errorHandler,
     ThrowableErrorConsumer<Throwable, String> onFailureRespond,
     int httpStatusCode,
     int retryCount,
     long timeout,
     long circuitBreakerTimeout,
     Lock lock) {
   final Throwable cause = Future.failedFuture("circuit open").cause();
   handleError(
       methodId,
       vertx,
       errorMethodHandler,
       context,
       headers,
       encoder,
       errorHandler,
       onFailureRespond,
       httpStatusCode,
       retryCount,
       timeout,
       circuitBreakerTimeout,
       lock,
       cause);
 }
コード例 #21
0
 @Test
 public void testAssertAsyncFailureHandlerSucceededAsync() throws Exception {
   BlockingQueue<Handler<AsyncResult<String>>> handlerQueue = new ArrayBlockingQueue<>(1);
   BlockingQueue<Async> resultQueue = new ArrayBlockingQueue<>(1);
   TestSuite suite =
       TestSuite.create("my_suite")
           .test(
               "my_test",
               context -> {
                 handlerQueue.add(
                     context.<String>asyncAssertFailure(
                         r -> {
                           resultQueue.add(context.async());
                         }));
               });
   TestReporter reporter = new TestReporter();
   run(suite, reporter);
   Handler<AsyncResult<String>> handler = handlerQueue.poll(2, TimeUnit.SECONDS);
   handler.handle(Future.failedFuture(new Throwable()));
   Async result = resultQueue.poll(2, TimeUnit.SECONDS);
   assertFalse(reporter.completed());
   result.complete();
   reporter.await();
   assertEquals(0, reporter.exceptions.size());
   assertEquals(1, reporter.results.size());
   assertEquals("my_test", reporter.results.get(0).name());
   assertFalse(reporter.results.get(0).failed());
 }
コード例 #22
0
 @Test
 public void testRejectAdaptedFunctions2() {
   MySubscriber<String> subscriber = new MySubscriber<>();
   Handler<AsyncResult<String>> o = RxHelper.toFuture(subscriber::onNext, subscriber::onError);
   Exception cause = new Exception();
   o.handle(Future.failedFuture(cause));
   subscriber.assertError(cause).assertEmpty();
 }
コード例 #23
0
 @Test
 public void testRejectAdaptedSubscriber() {
   MySubscriber<String> subscriber = new MySubscriber<>();
   Handler<AsyncResult<String>> o = RxHelper.toFuture(subscriber);
   Exception e = new Exception();
   o.handle(Future.failedFuture(e));
   subscriber.assertError(e).assertEmpty();
 }
コード例 #24
0
 private void doDeploy(
     Verticle verticle,
     DeploymentOptions options,
     ContextImpl currentContext,
     Handler<AsyncResult<String>> completionHandler) {
   if (options.isMultiThreaded() && !options.isWorker()) {
     throw new IllegalArgumentException("If multi-threaded then must be worker too");
   }
   ContextImpl context =
       options.isWorker()
           ? vertx.createWorkerContext(options.isMultiThreaded())
           : vertx.createEventLoopContext();
   String deploymentID = UUID.randomUUID().toString();
   DeploymentImpl deployment = new DeploymentImpl(deploymentID, context, verticle);
   context.setDeployment(deployment);
   Deployment parent = currentContext.getDeployment();
   if (parent != null) {
     parent.addChild(deployment);
   }
   JsonObject conf = options.getConfig() == null ? null : options.getConfig().copy(); // Copy it
   context.runOnContext(
       v -> {
         try {
           verticle.setVertx(vertx);
           verticle.setConfig(conf);
           verticle.setDeploymentID(deploymentID);
           Future<Void> startFuture = new FutureResultImpl<>();
           verticle.start(startFuture);
           startFuture.setHandler(
               ar -> {
                 if (ar.succeeded()) {
                   deployments.put(deploymentID, deployment);
                   reportSuccess(deploymentID, currentContext, completionHandler);
                 } else {
                   reportFailure(ar.cause(), currentContext, completionHandler);
                 }
               });
         } catch (Throwable t) {
           reportFailure(t, currentContext, completionHandler);
         }
       });
 }
コード例 #25
0
  @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());
              }
            });
  }
コード例 #26
0
  /**
   * 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.");
    }
  }
コード例 #27
0
 @Test
 public void testRejectAdaptedFunctions1() {
   MySubscriber<String> subscriber = new MySubscriber<>();
   Handler<AsyncResult<String>> o = RxHelper.toFuture(subscriber::onNext);
   Exception cause = new Exception();
   try {
     o.handle(Future.failedFuture(cause));
   } catch (OnErrorNotImplementedException e) {
     assertSame(cause, e.getCause());
   }
   subscriber.assertEmpty();
 }
コード例 #28
0
 private void acquireLock(Handler resultHandler, Handler<Lock> next) {
   vertx
       .sharedData()
       .getLock(
           "service.registry.lock",
           maybeLock -> {
             if (maybeLock.failed()) {
               resultHandler.handle(Future.failedFuture("Cannot acquire registry lock"));
             } else {
               next.handle(maybeLock.result());
             }
           });
 }
コード例 #29
0
ファイル: NetSocketImpl.java プロジェクト: karianna/vert.x
 @Override
 public NetSocket sendFile(
     String filename, long offset, long length, final Handler<AsyncResult<Void>> resultHandler) {
   File f = vertx.resolveFile(filename);
   if (f.isDirectory()) {
     throw new IllegalArgumentException("filename must point to a file and not to a directory");
   }
   RandomAccessFile raf = null;
   try {
     raf = new RandomAccessFile(f, "r");
     ChannelFuture future =
         super.sendFile(raf, Math.min(offset, f.length()), Math.min(length, f.length() - offset));
     if (resultHandler != null) {
       future.addListener(
           fut -> {
             final AsyncResult<Void> res;
             if (future.isSuccess()) {
               res = Future.succeededFuture();
             } else {
               res = Future.failedFuture(future.cause());
             }
             vertx.runOnContext(v -> resultHandler.handle(res));
           });
     }
   } catch (IOException e) {
     try {
       if (raf != null) {
         raf.close();
       }
     } catch (IOException ignore) {
     }
     if (resultHandler != null) {
       vertx.runOnContext(v -> resultHandler.handle(Future.failedFuture(e)));
     } else {
       log.error("Failed to send file", e);
     }
   }
   return this;
 }
コード例 #30
0
 @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();
                       }
                     });
           });
 }