Java Code Examples for io.vertx.core.AsyncResult

The following examples show how to use io.vertx.core.AsyncResult. These examples are extracted from open source projects. 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 Project: symbol-sdk-java   Author: nemtech   File: AbstractVertxRespositoryTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Mocks the api client telling that the next time there is remote call, an error should be
 * returned.
 *
 * @param statusCode the status code of the response (404 for example)
 * @param errorResponse the raw response, it may or may not be a json string.
 */
protected void mockErrorCodeRawResponse(int statusCode, String errorResponse) {
    String reasonPhrase = HttpStatus.valueOf(statusCode).getReasonPhrase();
    VertxHttpHeaders headers = new VertxHttpHeaders();
    ApiException exception = new ApiException(reasonPhrase, statusCode, headers,
        errorResponse);

    Mockito.doAnswer((Answer<Void>) invocationOnMock -> {

        Handler<AsyncResult<Object>> resultHandler = (Handler<AsyncResult<Object>>) invocationOnMock
            .getArguments()[invocationOnMock.getArguments().length - 1];
        resultHandler.handle(Future.failedFuture(exception));

        return null;
    }).when(apiClientMock)
        .invokeAPI(Mockito.anyString(), Mockito.anyString(), Mockito.anyList(), Mockito.any(),
            Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(),
            Mockito.any(), Mockito.any(), Mockito.any());
}
 
Example #2
Source Project: okapi   Author: folio-org   File: DockerModuleHandle.java    License: Apache License 2.0 6 votes vote down vote up
private void getContainerLog(Handler<AsyncResult<Void>> future) {
  final String url = "/containers/" + containerId
      + "/logs?stderr=1&stdout=1&follow=1";
  HttpClientRequest req = request(HttpMethod.GET, url, res -> {
    if (res.statusCode() == 200) {
      // stream OK. Continue other work but keep fetching!
      // remove 8 bytes of binary data and final newline
      res.handler(this::logHandler);
      tcpPortWaiting.waitReady(null, future);
    } else {
      String m = "getContainerLog HTTP error "
          + res.statusCode();
      logger.error(m);
      future.handle(Future.failedFuture(m));
    }
  });
  req.exceptionHandler(d -> future.handle(Future.failedFuture(d.getCause())));
  req.end();
}
 
Example #3
Source Project: quarkus-http   Author: quarkusio   File: VertxUndertowEngine.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void start(Future<Void> startFuture) throws Exception {

    server = vertx.createHttpServer(options);

    server.requestHandler(request -> {
        VertxHttpExchange delegate = new VertxHttpExchange(request, allocator, blockingExecutor, null, null);
        rootHandler.handle(delegate);
    });

    server.listen(port, host, new Handler<AsyncResult<HttpServer>>() {
        @Override
        public void handle(AsyncResult<HttpServer> event) {
            if (event.failed()) {
                startFuture.fail(event.cause());
            } else {
                startFuture.complete();
            }
        }
    });
}
 
Example #4
Source Project: vertx-blueprint-microservice   Author: sczyh30   File: ProductServiceVertxEBProxy.java    License: Apache License 2.0 6 votes vote down vote up
public ProductService retrieveProductPrice(String productId, Handler<AsyncResult<JsonObject>> resultHandler) {
  if (closed) {
    resultHandler.handle(Future.failedFuture(new IllegalStateException("Proxy is closed")));
    return this;
  }
  JsonObject _json = new JsonObject();
  _json.put("productId", productId);
  DeliveryOptions _deliveryOptions = (_options != null) ? new DeliveryOptions(_options) : new DeliveryOptions();
  _deliveryOptions.addHeader("action", "retrieveProductPrice");
  _vertx.eventBus().<JsonObject>send(_address, _json, _deliveryOptions, res -> {
    if (res.failed()) {
      resultHandler.handle(Future.failedFuture(res.cause()));
    } else {
      resultHandler.handle(Future.succeededFuture(res.result().body()));
    }
  });
  return this;
}
 
Example #5
Source Project: hono   Author: eclipse   File: HonoProtonHelper.java    License: Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Sets a handler on a link that is invoked when an AMQP <em>detach</em> frame
 * with its <em>close</em> property set to {@code false} is received from the peer.
 * <p>
 * The resources maintained for the link will be freed up after the given handler has
 * been invoked.
 *
 * @param <T> The type of link.
 * @param link The link to set the handler on.
 * @param handler The handler to invoke.
 * @return The wrapper that has been created around the given handler.
 * @throws NullPointerException if link or handler are {@code null}.
 */
public static <T extends ProtonLink<T>> Handler<AsyncResult<T>> setDetachHandler(
        final ProtonLink<T> link,
        final Handler<AsyncResult<T>> handler) {

    Objects.requireNonNull(link);
    Objects.requireNonNull(handler);

    final Handler<AsyncResult<T>> wrappedHandler = remoteDetach -> {
        try {
            handler.handle(remoteDetach);
        } catch (final Exception ex) {
            LOG.warn("error running detachHandler", ex);
        }
        link.free();
    };
    link.detachHandler(wrappedHandler);
    return wrappedHandler;
}
 
Example #6
Source Project: vertx-unit   Author: vert-x3   File: TestSuiteTestBase.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testAssertAsyncFailureHandlerSucceeded() throws Exception {
  BlockingQueue<Handler<AsyncResult<String>>> handlerQueue = new ArrayBlockingQueue<>(1);
  BlockingQueue<Throwable> resultQueue = new ArrayBlockingQueue<>(1);
  TestSuite suite = TestSuite.create("my_suite").test("my_test", context -> {
    handlerQueue.add(context.<String>asyncAssertFailure(resultQueue::add));
  });
  TestReporter reporter = new TestReporter();
  run(suite, reporter);
  Handler<AsyncResult<String>> handler = handlerQueue.poll(2, TimeUnit.SECONDS);
  Throwable expected = new Throwable();
  handler.handle(Future.failedFuture(expected));
  Throwable cause = resultQueue.poll(2, TimeUnit.SECONDS);
  assertSame(expected, cause);
  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());
}
 
Example #7
Source Project: xyz-hub   Author: heremaps   File: RpcClient.java    License: Apache License 2.0 6 votes vote down vote up
private void relocateAsync(Marker marker, byte[] bytes, Handler<AsyncResult<byte[]>> callback) {
  logger.info(marker, "Relocating event. Total event byte size: {}", bytes.length);
  Service.vertx.executeBlocking(future -> {
    try {
      future.complete(relocationClient.relocate(marker.getName(), bytes));
    }
    catch (Exception e) {
      logger.error("An error occurred when trying to relocate the event.", e);
      future.fail(new HttpException(BAD_GATEWAY, "Unable to relocate event.", e));
    }
  }, ar -> {
    if (ar.failed())
      callback.handle(Future.failedFuture(ar.cause()));
    else
      callback.handle(Future.succeededFuture((byte[]) ar.result()));
  });
}
 
Example #8
Source Project: vertx-shell   Author: vert-x3   File: ShellServiceImpl.java    License: Apache License 2.0 6 votes vote down vote up
private void startServer(List<CommandResolver> resolvers, Handler<AsyncResult<Void>> startHandler) {
  TelnetTermOptions telnetOptions = options.getTelnetOptions();
  SSHTermOptions sshOptions = options.getSSHOptions();
  HttpTermOptions webOptions = options.getHttpOptions();
  if (telnetOptions != null) {
    server.registerTermServer(new TelnetTermServer(vertx, telnetOptions));
  }
  if (sshOptions != null) {
    server.registerTermServer(new SSHServer(vertx, sshOptions));
  }
  if (webOptions != null) {
    server.registerTermServer(new HttpTermServer(vertx, webOptions));
  }
  resolvers.forEach(server::registerCommandResolver);
  server.listen(startHandler);
}
 
Example #9
Source Project: weld-vertx   Author: weld   File: EchoServiceVertxProxyHandler.java    License: Apache License 2.0 6 votes vote down vote up
private <T> Handler<AsyncResult<T>> createHandler(Message msg) {
  return res -> {
    if (res.failed()) {
      if (res.cause() instanceof ServiceException) {
        msg.reply(res.cause());
      } else {
        msg.reply(new ServiceException(-1, res.cause().getMessage()));
      }
    } else {
      if (res.result() != null  && res.result().getClass().isEnum()) {
        msg.reply(((Enum) res.result()).name());
      } else {
        msg.reply(res.result());
      }
    }
  };
}
 
Example #10
Source Project: raml-module-builder   Author: folio-org   File: RestVerticle.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * only one impl allowed
 * @param resultHandler
 * @throws Exception
 */
private void runShutdownHook(Handler<AsyncResult<Void>> resultHandler) throws Exception {
  try {
    ArrayList<Class<?>> aClass = InterfaceToImpl.convert2Impl(RTFConsts.PACKAGE_OF_IMPLEMENTATIONS, RTFConsts.PACKAGE_OF_HOOK_INTERFACES + ".ShutdownAPI", false);
    for (int i = 0; i < aClass.size(); i++) {
      Class<?>[] paramArray = new Class[] { Vertx.class, Context.class, Handler.class };
      Method method = aClass.get(i).getMethod("shutdown", paramArray);
      method.invoke(aClass.get(i).newInstance(), vertx, context, resultHandler);
      LogUtil.formatLogMessage(getClass().getName(), "runShutdownHook",
        "shutdown hook called with implemented class " + "named " + aClass.get(i).getName());
    }
  } catch (ClassNotFoundException e) {
    // no hook implemented, this is fine, just startup normally then
    LogUtil.formatLogMessage(getClass().getName(), "runShutdownHook", "no shutdown hook implementation found, continuing with shutdown");
    resultHandler.handle(io.vertx.core.Future.succeededFuture());
  }
}
 
Example #11
Source Project: raml-module-builder   Author: folio-org   File: AdminAPI.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void getAdminJstack(java.util.Map<String, String>okapiHeaders, Handler<AsyncResult<Response>> asyncResultHandler, Context vertxContext) {

  final StringBuilder dump = new StringBuilder();
  vertxContext.owner().executeBlocking(
    code -> {
      try {
        dump.append("<html><body>");
        final ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
        final ThreadInfo[] threadInfos = threadMXBean.getThreadInfo(
          threadMXBean.getAllThreadIds(), 100);
        for (ThreadInfo threadInfo : threadInfos) {
          dump.append(threadInfo.getThreadName());
          final Thread.State state = threadInfo.getThreadState();
          dump.append("</br>   java.lang.Thread.State: ");
          dump.append(state);
          final StackTraceElement[] stackTraceElements = threadInfo.getStackTrace();
          for (final StackTraceElement stackTraceElement : stackTraceElements) {
            dump.append("</br>        at ");
            dump.append(stackTraceElement);
          }
          dump.append("</br></br>");
        }
        dump.append("</body></html>");
        code.complete(dump);
      } catch (Exception e) {
        log.error(e.getMessage(), e);
        asyncResultHandler.handle(io.vertx.core.Future.succeededFuture(GetAdminJstackResponse.respond500WithTextPlain("ERROR"
            + e.getMessage())));
      }
    },
    result -> {
      asyncResultHandler.handle(io.vertx.core.Future.succeededFuture(GetAdminJstackResponse.respond200WithTextHtml(result.result().toString())));
    });
}
 
Example #12
Source Project: vertx-proton   Author: vert-x3   File: MockServer.java    License: Apache License 2.0 5 votes vote down vote up
public MockServer(Vertx vertx, Handler<ProtonConnection> connectionHandler) throws ExecutionException, InterruptedException {
  if(connectionHandler == null) {
    connectionHandler = (connection) -> processConnection(vertx, connection);
  }

  ProtonServerOptions protonServerOptions = new ProtonServerOptions();
  protonServerOptions.setReuseAddress(reuseAddress);
  server = ProtonServer.create(vertx, protonServerOptions);
  server.connectHandler(connectionHandler);
  FutureHandler<ProtonServer, AsyncResult<ProtonServer>> handler = FutureHandler.asyncResult();
  server.listen(bindPort, handler);
  handler.get();
}
 
Example #13
Source Project: xyz-hub   Author: heremaps   File: JWTURIHandler.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void parseCredentials(RoutingContext context, Handler<AsyncResult<JsonObject>> handler) {
  final List<String> access_token = Query.queryParam(Query.ACCESS_TOKEN, context);
  if (access_token != null && access_token.size() > 0) {
    handler.handle(Future.succeededFuture(new JsonObject().put("jwt", access_token.get(0)).put("options", options)));
    return;
  }
  handler.handle(Future.failedFuture(new HttpStatusException(UNAUTHORIZED.code(), "Missing auth credentials.")));
}
 
Example #14
Source Project: raml-module-builder   Author: folio-org   File: AdminAPI.java    License: Apache License 2.0 5 votes vote down vote up
@Validate
@Override
public void getAdminLoglevel(java.util.Map<String, String>okapiHeaders, Handler<AsyncResult<Response>> asyncResultHandler, Context vertxContext) {

  try {
    JsonObject loggers = LogUtil.getLogConfiguration();
    OutStream os = new OutStream();
    os.setData(loggers);
    asyncResultHandler.handle(io.vertx.core.Future.succeededFuture(PutAdminLoglevelResponse.respond200WithApplicationJson(os)));
  } catch (Exception e) {
    asyncResultHandler.handle(io.vertx.core.Future.succeededFuture(PutAdminLoglevelResponse.respond500WithTextPlain("ERROR"
        + e.getMessage())));
    log.error(e.getMessage(), e);
  }
}
 
Example #15
Source Project: graviteeio-access-management   Author: gravitee-io   File: SSOSessionHandler.java    License: Apache License 2.0 5 votes vote down vote up
private void checkAccountStatus(io.gravitee.am.model.User user, Handler<AsyncResult<Void>> handler) {
    userManager.get(user.getId())
            .subscribe(
                    user1 -> {
                        // if user is disabled, throw exception
                        if (!user1.isEnabled()) {
                            handler.handle(Future.failedFuture(new AccountDisabledException(user1.getId())));
                            return;
                        }
                        handler.handle(Future.succeededFuture());
                    },
                    error -> handler.handle(Future.failedFuture(error)),
                    () -> handler.handle(Future.succeededFuture()));
}
 
Example #16
Source Project: raml-module-builder   Author: folio-org   File: PostgresClient.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * streamGet with existing transaction/connection
 * @param <T>
 * @param connResult
 * @param table
 * @param clazz
 * @param fieldName
 * @param wrapper
 * @param returnIdField
 * @param distinctOn
 * @param facets
 * @param replyHandler
 */
@SuppressWarnings({"squid:S00107"})    // Method has >7 parameters
<T> void streamGet(AsyncResult<SQLConnection> connResult,
  String table, Class<T> clazz, String fieldName, CQLWrapper wrapper,
  boolean returnIdField, String distinctOn, List<FacetField> facets,
  Handler<AsyncResult<PostgresClientStreamResult<T>>> replyHandler) {

  if (connResult.failed()) {
    log.error(connResult.cause().getMessage(), connResult.cause());
    replyHandler.handle(Future.failedFuture(connResult.cause()));
    return;
  }
  doStreamGetCount(connResult.result(), table, clazz, fieldName, wrapper, returnIdField,
      distinctOn, facets, replyHandler);
}
 
Example #17
Source Project: hono   Author: eclipse   File: AbstractConsumer.java    License: Eclipse Public License 2.0 5 votes vote down vote up
@Override
public void close(final Handler<AsyncResult<Void>> closeHandler) {

    closeLinks(ok -> {
        if (localCloseHandler != null) {
            localCloseHandler.handle(receiver.getSource().getAddress());
        }
        if (closeHandler != null) {
            closeHandler.handle(Future.succeededFuture());
        }
    });
}
 
Example #18
Source Project: vertx-rabbitmq-client   Author: vert-x3   File: RabbitMQClientImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void basicAck(long deliveryTag, boolean multiple, Handler<AsyncResult<Void>> resultHandler) {
  Future<Void> fut = basicAck(deliveryTag, multiple);
  if (resultHandler != null) {
    fut.onComplete(resultHandler);
  }
}
 
Example #19
Source Project: vertx-vaadin   Author: mcollovati   File: NearCacheSessionStoreImpl.java    License: MIT License 5 votes vote down vote up
@Override
public void delete(String id, Handler<AsyncResult<Void>> resultHandler) {
    clusteredSessionStore.delete(id, res -> {
        if (res.succeeded()) {
            localMap.remove(id);
            resultHandler.handle(Future.succeededFuture());
        } else {
            resultHandler.handle(Future.failedFuture(res.cause()));
        }
    });
}
 
Example #20
Source Project: graviteeio-access-management   Author: gravitee-io   File: MFAEnrollEndpoint.java    License: Apache License 2.0 5 votes vote down vote up
private void load(Map<io.gravitee.am.model.Factor, FactorProvider> providers, User user, Handler<AsyncResult<List<Factor>>> handler) {
    Observable.fromIterable(providers.entrySet())
            .flatMapSingle(entry -> entry.getValue().enroll(user.getUsername())
                    .map(enrollment -> new Factor(entry.getKey(), enrollment))
            )
            .toList()
            .subscribe(
                    factors -> handler.handle(Future.succeededFuture(factors)),
                    error -> handler.handle(Future.failedFuture(error)));
}
 
Example #21
Source Project: vertx-kubernetes-workshop   Author: cescoffier   File: PortfolioServiceImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void sell(int amount, JsonObject quote, Handler<AsyncResult<Portfolio>> resultHandler) {
    if (amount <= 0) {
        resultHandler.handle(Future.failedFuture("Cannot sell " + quote.getString("name") + " - the amount must be " +
            "greater than 0"));
        return;
    }

    double price = amount * quote.getDouble("bid");
    String name = quote.getString("name");
    int current = portfolio.getAmount(name);
    // 1) do we have enough stocks
    if (current >= amount) {
        // Yes, sell it
        int newAmount = current - amount;
        if (newAmount == 0) {
            portfolio.getShares().remove(name);
        } else {
            portfolio.getShares().put(name, newAmount);
        }
        portfolio.setCash(portfolio.getCash() + price);
        sendActionOnTheEventBus("SELL", amount, quote, newAmount);
        resultHandler.handle(Future.succeededFuture(portfolio));
    } else {
        resultHandler.handle(Future.failedFuture("Cannot sell " + amount + " of " + name + " - " + "not enough stocks " +
            "in portfolio"));
    }

}
 
Example #22
Source Project: hono   Author: eclipse   File: HonoConnectionImplTest.java    License: Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Verifies that the attempt to create a sender succeeds when sender never gets credits.
 *
 * @param ctx The vert.x test context.
 */
@Test
public void testCreateSenderThatGetsNoCredits(final VertxTestContext ctx) {
    final ProtonSender sender = mock(ProtonSender.class);
    when(sender.isOpen()).thenReturn(Boolean.TRUE);
    when(con.createSender(anyString())).thenReturn(sender);
    final Target target = new Target();
    target.setAddress("someAddress");
    when(sender.getRemoteTarget()).thenReturn(target);
    when(sender.getCredit()).thenReturn(0);
    // just invoke openHandler with succeeded future
    doAnswer(AdditionalAnswers.answerVoid(
            (final Handler<AsyncResult<ProtonSender>> handler) -> handler.handle(Future.succeededFuture(sender))))
                    .when(sender).openHandler(VertxMockSupport.anyHandler());
    final Handler<String> remoteCloseHook = VertxMockSupport.mockHandler();

    // GIVEN an established connection
    honoConnection.connect()
        .compose(c -> honoConnection.createSender(
            "target", ProtonQoS.AT_LEAST_ONCE, remoteCloseHook))
        .onComplete(ctx.succeeding(s -> {
                ctx.verify(() -> {
                    assertThat(s).isEqualTo(sender);
                    // sendQueueDrainHandler gets unset
                    verify(sender).sendQueueDrainHandler(null);
                });
                ctx.completeNow();
            }));
}
 
Example #23
Source Project: graviteeio-access-management   Author: gravitee-io   File: ErrorEndpoint.java    License: Apache License 2.0 5 votes vote down vote up
private void resolveClient(String clientId, Handler<AsyncResult<Client>> handler) {
    clientSyncService.findByDomainAndClientId(domain, clientId)
            .subscribe(
                    client -> handler.handle(Future.succeededFuture(client)),
                    error -> handler.handle(Future.failedFuture(error)),
                    () -> handler.handle(Future.failedFuture(new ClientNotFoundException(clientId)))
            );
}
 
Example #24
Source Project: hono   Author: eclipse   File: AuthenticationServerClient.java    License: Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Verifies username/password credentials with a remote authentication server using SASL PLAIN.
 *
 * @param authzid The identity to act as.
 * @param authcid The username.
 * @param password The password.
 * @param authenticationResultHandler The handler to invoke with the authentication result. On successful authentication,
 *                                    the result contains a JWT with the authenticated user's claims.
 */
public void verifyPlain(final String authzid, final String authcid, final String password,
        final Handler<AsyncResult<HonoUser>> authenticationResultHandler) {

    final ProtonClientOptions options = new ProtonClientOptions();
    options.setReconnectAttempts(3).setReconnectInterval(50);
    options.addEnabledSaslMechanism(AuthenticationConstants.MECHANISM_PLAIN);

    final Promise<ProtonConnection> connectAttempt = Promise.promise();
    factory.connect(options, authcid, password, null, null, connectAttempt);

    connectAttempt.future()
    .compose(openCon -> getToken(openCon))
    .onComplete(s -> {
        if (s.succeeded()) {
            authenticationResultHandler.handle(Future.succeededFuture(s.result()));
        } else {
            authenticationResultHandler
            .handle(Future.failedFuture(mapConnectionFailureToServiceInvocationException(s.cause())));
        }
        Optional.ofNullable(connectAttempt.future().result())
        .ifPresent(con -> {
            LOG.debug("closing connection to Authentication service");
            con.close();
        });
    });
}
 
Example #25
Source Project: vertx-blueprint-microservice   Author: sczyh30   File: CheckoutServiceVertxProxyHandler.java    License: Apache License 2.0 5 votes vote down vote up
private <T> Handler<AsyncResult<Set<T>>> createSetHandler(Message msg) {
  return res -> {
    if (res.failed()) {
      if (res.cause() instanceof ServiceException) {
        msg.reply(res.cause());
      } else {
        msg.reply(new ServiceException(-1, res.cause().getMessage()));
      }
    } else {
      msg.reply(new JsonArray(new ArrayList<>(res.result())));
    }
  };
}
 
Example #26
Source Project: vxms   Author: amoAHCP   File: EventbusObjectExecutionUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * create execution chain for event-bus request and reply to rest
 *
 * @param _methodId the method identifier
 * @param _targetId the event-bus target id
 * @param _message the message to send
 * @param _objectFunction the function to process the result message
 * @param _options the event-bus delivery serverOptions
 * @param _vxmsShared the vxmsShared instance, containing the Vertx instance and other shared
 *     objects per instance
 * @param _failure the failure thrown while task execution
 * @param _errorMethodHandler the error-method handler
 * @param _context the vertx routing context
 * @param _encoder the encoder to encode your objects
 * @return the execution chain {@link ExecuteRSObjectResponse}
 */
public static ExecuteRSObjectResponse mapToObjectResponse(
    String _methodId,
    String _targetId,
    Object _message,
    ThrowableFutureBiConsumer<AsyncResult<Message<Object>>, Serializable> _objectFunction,
    DeliveryOptions _options,
    VxmsShared _vxmsShared,
    Throwable _failure,
    Consumer<Throwable> _errorMethodHandler,
    RoutingContext _context,
    Encoder _encoder) {

  return mapToObjectResponse(
      _methodId,
      _targetId,
      _message,
      _objectFunction,
      _options,
      _vxmsShared,
      _failure,
      _errorMethodHandler,
      _context,
      null,
      null,
      _encoder,
      null,
      null,
      0,
      0,
      0,
      0,
      0);
}
 
Example #27
Source Project: raml-module-builder   Author: folio-org   File: PostgresClient.java    License: Apache License 2.0 5 votes vote down vote up
void getSQLConnection(int queryTimeout, Handler<AsyncResult<SQLConnection>> handler) {
  getConnection(res -> {
    if (res.failed()) {
      handler.handle(Future.failedFuture(res.cause()));
      return;
    }

    PgConnection pgConnection = res.result();

    if (queryTimeout == 0) {
      handler.handle(Future.succeededFuture(new SQLConnection(pgConnection, null, null)));
      return;
    }

    long timerId = vertx.setTimer(queryTimeout, id -> pgConnection.cancelRequest(ar -> {
      if (ar.succeeded()) {
        log.warn(
            String.format("Cancelling request due to timeout after : %d ms",
                queryTimeout));
      } else {
        log.warn("Failed to send cancelling request", ar.cause());
      }
    }));

    SQLConnection sqlConnection = new SQLConnection(pgConnection, null, timerId);
    handler.handle(Future.succeededFuture(sqlConnection));
  });
}
 
Example #28
Source Project: raml-module-builder   Author: folio-org   File: PostgresClientIT.java    License: Apache License 2.0 5 votes vote down vote up
private void intsAsString(RowStream<Row> sqlRowStream, Handler<AsyncResult<String>> replyHandler) {
  StringBuilder s = new StringBuilder();
  sqlRowStream.handler(row -> {
    if (s.length() > 0) {
      s.append(", ");
    }
    s.append(row.getInteger(0));
  }).exceptionHandler(e -> {
    replyHandler.handle(Future.failedFuture(e));
  }).endHandler(end -> {
    replyHandler.handle(Future.succeededFuture(s.toString()));
  });
}
 
Example #29
Source Project: vertx-kafka-client   Author: vert-x3   File: KafkaTestBase.java    License: Apache License 2.0 5 votes vote down vote up
static void close(TestContext ctx, Consumer<Handler<AsyncResult<Void>>> producer) {
  if (producer != null) {
    Async closeAsync = ctx.async();
    producer.accept(v -> {
      closeAsync.complete();
    });
    closeAsync.awaitSuccess(10000);
  }
}
 
Example #30
Source Project: quarkus   Author: quarkusio   File: AbstractResponseWrapper.java    License: Apache License 2.0 5 votes vote down vote up
@Override

    public HttpServerResponse push(HttpMethod method, String host, String path,
            Handler<AsyncResult<HttpServerResponse>> handler) {
        delegate.push(method, host, path, handler);
        return this;
    }