@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();
 }
 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());
 }
 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);
 }
 @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());
 }
 @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());
 }
  @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));
    }
  }
 private void notifyHandler(ChannelFuture future) {
   if (future.isSuccess()) {
     handler.handle(Future.succeededFuture(result));
   } else {
     handler.handle(Future.failedFuture(future.cause()));
   }
 }
 @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();
 }
 @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();
 }
 @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();
 }
 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());
             }
           });
 }
Exemple #12
0
 @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;
 }
 @Override
 public RedisClient eval(
     String script, List<String> keys, List<String> args, Handler<AsyncResult<Void>> handler) {
   keys = (keys != null) ? keys : Collections.emptyList();
   args = (args != null) ? args : Collections.emptyList();
   if (keys.size() != args.size()) {
     handler.handle(
         Future.failedFuture(
             new IllegalArgumentException("Key list, and argument list are not the same size")));
   } else {
     sendVoid(EVAL, RedisCommandUtils.toPayload(script, keys.size(), keys, args), handler);
   }
   return this;
 }
  private <T> void executeWithTimeout(
      Consumer<IgniteCache<K, V>> cacheOp, Handler<AsyncResult<T>> handler, long timeout) {
    try {
      IgniteCache<K, V> cache = this.cache.withAsync();
      cacheOp.accept(cache);
      IgniteFuture<T> future = cache.future();

      if (timeout >= 0) {
        vertx.executeBlocking(f -> future.get(timeout), handler);
      } else {
        future.listen(fut -> vertx.executeBlocking(f -> f.complete(future.get()), handler));
      }
    } catch (Exception e) {
      handler.handle(Future.failedFuture(e));
    }
  }
 private void getRegistry(
     Lock lock, Handler resultHandler, Handler<Map<String, JsonObject>> next) {
   vertx.<Map<String, JsonObject>>executeBlocking(
       future -> {
         Map<String, JsonObject> map =
             ((VertxInternal) vertx).getClusterManager().getSyncMap("service.registry");
         future.complete(map);
       },
       map -> {
         if (map.succeeded()) {
           next.handle(map.result());
         } else {
           resultHandler.handle(Future.failedFuture(map.cause()));
           lock.release();
         }
       });
 }
  private void sendEmail(final MailgunSendRequest sendRequest) {
    sendRequest.incrementAttempts();
    final HttpClientRequest clientRequest =
        client
            .post("/messages")
            .handler(new HttpResponseHandler(sendRequest))
            .exceptionHandler(throwable -> failure(sendRequest, throwable))
            .setChunked(true);
    clientRequest.putHeader(HttpHeaders.AUTHORIZATION, "api:" + apiKey);
    clientRequest.putHeader(
        HttpHeaders.CONTENT_TYPE,
        ContentType.MULTIPART_FORM_DATA.getMimeType() + "; boundary=" + MultiPartUtility.BOUNDARY);
    writeBodyObservable(clientRequest, sendRequest)
        .doOnError(
            throwable -> {
              if (sendRequest.getCompletionHandler() != null) {
                sendRequest.getCompletionHandler().handle(Future.failedFuture(throwable));
              }
            })
        .doOnNext(
            aVoid -> {
              if (sendRequest.getEmailEntity().isAttachments()) {
                getAttachmentEntitiesObservable(sendRequest.getEmailEntity())
                    .doOnError(throwable -> failure(sendRequest, throwable))
                    .doOnNext(
                        attachmentEntities ->
                            new FilePipeIterator(
                                    clientRequest,
                                    attachmentEntities.iterator(),
                                    new FileGetPipeHandler() {
                                      @Override
                                      public void onComplete() {
                                        clientRequest.end();
                                      }

                                      @Override
                                      public void onFailure(Throwable throwable) {
                                        failure(sendRequest, throwable);
                                      }
                                    })
                                .start());
              } else {
                clientRequest.end();
              }
            });
  }