Java Code Examples for io.vertx.core.Future
The following examples show how to use
io.vertx.core.Future.
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: hono Author: eclipse File: IntegrationTestSupport.java License: Eclipse Public License 2.0 | 6 votes |
/** * Sends a command to a device. * * @param notification The empty notification indicating the device's readiness to receive a command. * @param command The name of the command to send. * @param contentType The type of the command's input data. * @param payload The command's input data to send to the device. * @param properties The headers to include in the command message as AMQP application properties. * @return A future that is either succeeded with the response payload from the device or * failed with a {@link ServiceInvocationException}. */ public Future<BufferResult> sendCommand( final TimeUntilDisconnectNotification notification, final String command, final String contentType, final Buffer payload, final Map<String, Object> properties) { return sendCommand( notification.getTenantId(), notification.getDeviceId(), command, contentType, payload, properties, notification.getMillisecondsUntilExpiry()); }
Example #2
Source Project: hono Author: eclipse File: HotrodCache.java License: Eclipse Public License 2.0 | 6 votes |
@Override public Future<Boolean> remove(final K key, final V value) { Objects.requireNonNull(key); Objects.requireNonNull(value); return withCache(cache -> { final RemoteCache<K, V> remoteCache = (RemoteCache<K, V>) cache; return remoteCache.getWithMetadataAsync(key).thenCompose(metadataValue -> { if (metadataValue != null && value.equals(metadataValue.getValue())) { // If removeWithVersionAsync() returns false here (meaning that the value was updated in between), // the updated value shall prevail and no new removal attempt with a new getWithMetadataAsync() invocation will be done. return remoteCache.removeWithVersionAsync(key, metadataValue.getVersion()); } else { return CompletableFuture.completedFuture(Boolean.FALSE); } }); }); }
Example #3
Source Project: raml-module-builder Author: folio-org File: PostgresClient.java License: Apache License 2.0 | 6 votes |
public void delete(AsyncResult<SQLConnection> connection, String table, Object entity, Handler<AsyncResult<RowSet<Row>>> replyHandler) { try { long start = System.nanoTime(); if (connection.failed()) { replyHandler.handle(Future.failedFuture(connection.cause())); return; } String sql = DELETE + FROM + schemaName + DOT + table + WHERE + DEFAULT_JSONB_FIELD_NAME + "@>$1"; log.debug("delete by entity, query = " + sql + "; $1=" + entity); connection.result().conn.preparedQuery(sql).execute(Tuple.of(pojo2JsonObject(entity)), delete -> { statsTracker(DELETE_STAT_METHOD, table, start); if (delete.failed()) { log.error(delete.cause().getMessage(), delete.cause()); replyHandler.handle(Future.failedFuture(delete.cause())); return; } replyHandler.handle(Future.succeededFuture(delete.result())); }); } catch (Exception e) { replyHandler.handle(Future.failedFuture(e)); } }
Example #4
Source Project: raml-module-builder Author: folio-org File: RestVerticle.java License: Apache License 2.0 | 6 votes |
/** * 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 #5
Source Project: hono Author: eclipse File: FileBasedRegistrationService.java License: Eclipse Public License 2.0 | 6 votes |
Future<Void> loadRegistrationData() { if (getConfig().getFilename() == null || getConfig().isStartEmpty()) { LOG.info("Either filename is null or empty start is set, won't load any device identities"); return Future.succeededFuture(); } final Promise<Buffer> readResult = Promise.promise(); vertx.fileSystem().readFile(getConfig().getFilename(), readResult); return readResult.future() .compose(this::addAll) .recover(t -> { LOG.debug("cannot load device identities from file [{}]: {}", getConfig().getFilename(), t.getMessage()); return Future.succeededFuture(); }); }
Example #6
Source Project: enmasse Author: EnMasseProject File: MoreFutures.java License: Apache License 2.0 | 6 votes |
public static <T> CompletableFuture<T> map(final Future<T> future) { if (future == null) { return null; } final CompletableFuture<T> result = new CompletableFuture<>(); future.onComplete(ar -> { if (ar.succeeded()) { result.complete(ar.result()); } else { log.info("Operation failed", ar.cause()); result.completeExceptionally(ar.cause()); } }); return result; }
Example #7
Source Project: prebid-server-java Author: rubicon-project File: VtrackHandlerTest.java License: Apache License 2.0 | 6 votes |
@Test public void shouldRespondWithInternalServerErrorWhenFetchingAccountFails() throws JsonProcessingException { // given given(routingContext.getBody()) .willReturn(givenVtrackRequest(builder -> builder.bidid("bidId").bidder("bidder"))); given(applicationSettings.getAccountById(any(), any())) .willReturn(Future.failedFuture("error")); // when handler.handle(routingContext); // then verifyZeroInteractions(cacheService); verify(httpResponse).setStatusCode(eq(500)); verify(httpResponse).end(eq("Error occurred while fetching account: error")); }
Example #8
Source Project: vertx-kue Author: sczyh30 File: JobServiceVertxEBProxy.java License: Apache License 2.0 | 6 votes |
public JobService getIdsByState(JobState state, Handler<AsyncResult<List<Long>>> handler) { if (closed) { handler.handle(Future.failedFuture(new IllegalStateException("Proxy is closed"))); return this; } JsonObject _json = new JsonObject(); _json.put("state", state == null ? null : state.toString()); DeliveryOptions _deliveryOptions = (_options != null) ? new DeliveryOptions(_options) : new DeliveryOptions(); _deliveryOptions.addHeader("action", "getIdsByState"); _vertx.eventBus().<JsonArray>send(_address, _json, _deliveryOptions, res -> { if (res.failed()) { handler.handle(Future.failedFuture(res.cause())); } else { handler.handle(Future.succeededFuture(convertList(res.result().body().getList()))); } }); return this; }
Example #9
Source Project: prebid-server-java Author: rubicon-project File: JdbcApplicationSettingsTest.java License: Apache License 2.0 | 6 votes |
@Test public void getAmpStoredDataUnionSelectByIdShouldReturnStoredRequests(TestContext context) { // given jdbcApplicationSettings = new JdbcApplicationSettings(jdbcClient(), jacksonMapper, SELECT_UNION_QUERY, SELECT_UNION_QUERY, SELECT_RESPONSE_QUERY); // when final Future<StoredDataResult> storedRequestResultFuture = jdbcApplicationSettings.getAmpStoredData(new HashSet<>(asList("1", "2", "3")), new HashSet<>(asList("4", "5", "6")), timeout); // then final Async async = context.async(); storedRequestResultFuture.setHandler(context.asyncAssertSuccess(storedRequestResult -> { final Map<String, String> expectedRequests = new HashMap<>(); expectedRequests.put("1", "value1"); expectedRequests.put("2", "value2"); expectedRequests.put("3", "value3"); assertThat(storedRequestResult).isEqualTo( StoredDataResult.of(expectedRequests, emptyMap(), emptyList())); async.complete(); })); }
Example #10
Source Project: hono Author: eclipse File: HttpContextTenantAndAuthIdProvider.java License: Eclipse Public License 2.0 | 6 votes |
@Override public Future<TenantObjectWithAuthId> get(final HttpContext context, final SpanContext spanContext) { if (config.isAuthenticationRequired()) { return getFromClientCertificate(context.getRoutingContext(), spanContext) .recover(thr -> getFromAuthHeader(context.getRoutingContext(), spanContext)); } if (tenantIdContextParamName != null && deviceIdContextParamName != null) { final String tenantId = context.get(tenantIdContextParamName); final String deviceId = context.get(deviceIdContextParamName); if (tenantId != null && deviceId != null) { // unauthenticated request return tenantClientFactory.getOrCreateTenantClient() .compose(tenantClient -> tenantClient.get(tenantId, spanContext)) .map(tenantObject -> new TenantObjectWithAuthId(tenantObject, deviceId)); } } return Future.failedFuture("tenant could not be determined"); }
Example #11
Source Project: prebid-server-java Author: rubicon-project File: StoredRequestProcessorTest.java License: Apache License 2.0 | 6 votes |
@Test public void shouldReturnFailedFutureWhenMergedResultCouldNotBeConvertedToBidRequest() throws IOException { final BidRequest bidRequest = givenBidRequest(builder -> builder .ext(mapper.valueToTree( ExtBidRequest.of(ExtRequestPrebid.builder() .storedrequest(ExtStoredRequest.of("123")).build())))); final Map<String, String> storedRequestFetchResult = singletonMap("123", mapper.writeValueAsString( mapper.createObjectNode().put("tmax", "stringValue"))); given(applicationSettings.getStoredData(anySet(), anySet(), any())).willReturn(Future .succeededFuture(StoredDataResult.of(storedRequestFetchResult, emptyMap(), emptyList()))); // when final Future<BidRequest> bidRequestFuture = storedRequestProcessor.processStoredRequests(bidRequest); // then assertThat(bidRequestFuture.failed()).isTrue(); assertThat(bidRequestFuture.cause()) .isInstanceOf(InvalidRequestException.class) .hasMessageStartingWith("Can't convert merging result for id 123: Cannot deserialize"); }
Example #12
Source Project: vertx-stomp Author: vert-x3 File: DefaultConnectHandler.java License: Apache License 2.0 | 6 votes |
private void authenticate(Frame frame, StompServerConnection connection, Handler<AsyncResult<Void>> remainingActions) { if (connection.server().options().isSecured()) { String login = frame.getHeader(Frame.LOGIN); String passcode = frame.getHeader(Frame.PASSCODE); connection.handler().onAuthenticationRequest(connection, login, passcode, ar -> { if (ar.result()) { remainingActions.handle(Future.succeededFuture()); } else { connection.write(Frames.createErrorFrame( "Authentication failed", Headers.create( Frame.VERSION, getSupportedVersionsHeaderLine(connection), Frame.CONTENT_TYPE, "text/plain"), "The connection frame does not contain valid credentials.") ); connection.close(); } }); } else { remainingActions.handle(Future.succeededFuture()); } }
Example #13
Source Project: hono Author: eclipse File: AbstractRegistrationServiceTest.java License: Eclipse Public License 2.0 | 6 votes |
/** * Verifies that the service returns a 403 status code for a request for asserting the registration * of a device via a disabled gateway. * * @param ctx The vert.x test context. */ @Test public void testAssertRegistrationFailsForDisabledGateway(final VertxTestContext ctx) { when(service.processAssertRegistration(any(DeviceKey.class), any(Span.class))) .thenAnswer(invocation -> { final DeviceKey key = invocation.getArgument(0); if (key.getDeviceId().equals("gw")) { return Future.succeededFuture(RegistrationResult.from(HttpURLConnection.HTTP_OK, PAYLOAD_DISABLED)); } else { return Future.succeededFuture(RegistrationResult.from(HttpURLConnection.HTTP_OK, PAYLOAD_ENABLED)); } }); service.assertRegistration(Constants.DEFAULT_TENANT, "device", "gw", span) .onComplete(ctx.succeeding(result -> { ctx.verify(() -> { assertThat(result.getStatus()).isEqualTo(HttpURLConnection.HTTP_FORBIDDEN); }); ctx.completeNow(); })); }
Example #14
Source Project: vertx-blueprint-microservice Author: sczyh30 File: AccountServiceVertxEBProxy.java License: Apache License 2.0 | 6 votes |
public AccountService retrieveByUsername(String username, Handler<AsyncResult<Account>> resultHandler) { if (closed) { resultHandler.handle(Future.failedFuture(new IllegalStateException("Proxy is closed"))); return this; } JsonObject _json = new JsonObject(); _json.put("username", username); DeliveryOptions _deliveryOptions = (_options != null) ? new DeliveryOptions(_options) : new DeliveryOptions(); _deliveryOptions.addHeader("action", "retrieveByUsername"); _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() == null ? null : new Account(res.result().body()))); } }); return this; }
Example #15
Source Project: prebid-server-java Author: rubicon-project File: StoredResponseProcessor.java License: Apache License 2.0 | 6 votes |
Future<StoredResponseResult> getStoredResponseResult( List<Imp> imps, BidderAliases aliases, Timeout timeout) { final List<Imp> requiredRequestImps = new ArrayList<>(); final Map<String, String> storedResponseIdToImpId = new HashMap<>(); try { fillStoredResponseIdsAndRequestingImps(imps, requiredRequestImps, storedResponseIdToImpId, aliases); } catch (InvalidRequestException ex) { return Future.failedFuture(ex); } if (storedResponseIdToImpId.isEmpty()) { return Future.succeededFuture(StoredResponseResult.of(imps, Collections.emptyList())); } return applicationSettings.getStoredResponses(storedResponseIdToImpId.keySet(), timeout) .recover(exception -> Future.failedFuture(new InvalidRequestException( String.format("Stored response fetching failed with reason: %s", exception.getMessage())))) .map(storedResponseDataResult -> convertToSeatBid(storedResponseDataResult, storedResponseIdToImpId)) .map(storedResponse -> StoredResponseResult.of(requiredRequestImps, storedResponse)); }
Example #16
Source Project: graviteeio-access-management Author: gravitee-io File: UserAuthProviderImpl.java License: Apache License 2.0 | 5 votes |
private void parseClient(String clientId, Handler<AsyncResult<Client>> authHandler) { logger.debug("Attempt authentication with client " + clientId); clientSyncService .findByClientId(clientId) .subscribe( client -> authHandler.handle(Future.succeededFuture(client)), error -> authHandler.handle(Future.failedFuture(new ServerErrorException("Server error: unable to find client with client_id " + clientId))), () -> authHandler.handle(Future.failedFuture(new InvalidRequestException("No client found for client_id " + clientId))) ); }
Example #17
Source Project: vertx-mongo-client Author: vert-x3 File: GridFsTest.java License: Apache License 2.0 | 5 votes |
@Test public void testStreamUpload() { String fileName = createTempFileWithContent(1024); AtomicReference<MongoGridFsClient> gridFsClient = new AtomicReference<>(); Promise<MongoGridFsClient> gridFsClientPromise = Promise.promise(); mongoClient.createGridFsBucketService("fs", gridFsClientPromise); gridFsClientPromise.future().compose(mongoGridFsClient -> { assertNotNull(mongoGridFsClient); gridFsClient.set(mongoGridFsClient); Promise<Void> dropPromise = Promise.promise(); mongoGridFsClient.drop(dropPromise); return dropPromise.future(); }).compose(dropped -> { Promise<AsyncFile> openPromise = Promise.promise(); vertx.fileSystem().open(fileName, new OpenOptions(), openPromise); return openPromise.future(); }).compose(asyncFile -> { Promise<String> uploadedPromise = Promise.promise(); gridFsClient.get().uploadByFileName(asyncFile, fileName, uploadedPromise); return uploadedPromise.future(); }).compose(id -> { assertNotNull(id); testComplete(); return Future.succeededFuture(); }).onComplete(event -> { if (event.failed()) { fail(event.cause()); } }); await(); }
Example #18
Source Project: raml-module-builder Author: folio-org File: TenantLoading.java License: Apache License 2.0 | 5 votes |
private static void loadData(String okapiUrl, Map<String, String> headers, LoadingEntry loadingEntry, HttpClient httpClient, Handler<AsyncResult<Integer>> res) { String filePath = loadingEntry.lead; if (!loadingEntry.filePath.isEmpty()) { filePath = filePath + '/' + loadingEntry.filePath; } final String endPointUrl = okapiUrl + "/" + loadingEntry.uriPath; try { List<URL> urls = getURLsFromClassPathDir(filePath); if (urls.isEmpty()) { log.warn("loadData getURLsFromClassPathDir returns empty list for path=" + filePath); } Future<Void> future = Future.succeededFuture(); for (URL url : urls) { future = future.compose(x -> { Promise<Void> p = Promise.promise(); loadURL(headers, url, httpClient, loadingEntry, endPointUrl, p.future()); return p.future(); }); } future.onComplete(x -> { if (x.failed()) { res.handle(Future.failedFuture(x.cause().getLocalizedMessage())); } else { res.handle(Future.succeededFuture(urls.size())); } }); } catch (URISyntaxException|IOException ex) { log.error("Exception for path " + filePath, ex); res.handle(Future.failedFuture("Exception for path " + filePath + " ex=" + ex.getMessage())); } }
Example #19
Source Project: strimzi-kafka-operator Author: strimzi File: KafkaConnectS2IAssemblyOperatorTest.java License: Apache License 2.0 | 5 votes |
@Test public void testCreateClusterWithSameNameAsConnectFails(VertxTestContext context) { ResourceOperatorSupplier supplier = ResourceUtils.supplierWithMocks(true); CrdOperator mockConnectS2IOps = supplier.connectS2IOperator; CrdOperator mockConnectOps = supplier.connectOperator; String clusterCmName = "foo"; String clusterCmNamespace = "test"; KafkaConnectS2I clusterCm = ResourceUtils.createEmptyKafkaConnectS2ICluster(clusterCmNamespace, clusterCmName); clusterCm.getMetadata().setCreationTimestamp("2020-01-27T19:31:11Z"); KafkaConnect conflictingConnect = ResourceUtils.createEmptyKafkaConnectCluster(clusterCmNamespace, clusterCmName); conflictingConnect.getMetadata().setCreationTimestamp("2020-01-27T19:31:10Z"); when(mockConnectS2IOps.getAsync(anyString(), anyString())).thenReturn(Future.succeededFuture(clusterCm)); when(mockConnectOps.getAsync(clusterCmNamespace, clusterCmName)).thenReturn(Future.succeededFuture(conflictingConnect)); KafkaConnectApi mockConnectClient = mock(KafkaConnectApi.class); PlatformFeaturesAvailability pfa = new PlatformFeaturesAvailability(true, kubernetesVersion); ArgumentCaptor<KafkaConnectS2I> connectCaptor = ArgumentCaptor.forClass(KafkaConnectS2I.class); when(mockConnectS2IOps.updateStatusAsync(connectCaptor.capture())).thenReturn(Future.succeededFuture()); KafkaConnectS2IAssemblyOperator ops = new KafkaConnectS2IAssemblyOperator(vertx, pfa, supplier, ResourceUtils.dummyClusterOperatorConfig(VERSIONS), x -> mockConnectClient); Checkpoint async = context.checkpoint(); ops.createOrUpdate(new Reconciliation("test-trigger", KafkaConnectS2I.RESOURCE_KIND, clusterCmNamespace, clusterCmName), clusterCm) .onComplete(context.failing(v -> context.verify(() -> { // Verify status List<KafkaConnectS2I> capturedConnects = connectCaptor.getAllValues(); assertThat(capturedConnects.get(0).getStatus().getConditions().get(0).getStatus(), is("True")); assertThat(capturedConnects.get(0).getStatus().getConditions().get(0).getType(), is("NotReady")); assertThat(capturedConnects.get(0).getStatus().getConditions().get(0).getMessage(), is("Both KafkaConnect and KafkaConnectS2I exist with the same name. KafkaConnect is older and will be used while this custom resource will be ignored.")); async.flag(); }))); }
Example #20
Source Project: prebid-server-java Author: rubicon-project File: CircuitBreakerSecuredGeoLocationServiceTest.java License: Apache License 2.0 | 5 votes |
@Test public void lookupShouldSucceedsIfCircuitIsClosedAndWrappedGeoLocationSucceeds(TestContext context) { // given givenWrappedGeoLocationReturning( Future.succeededFuture(GeoInfo.builder().vendor("vendor").country("country").build())); // when final Future<GeoInfo> future = doLookup(context); // then assertThat(future.succeeded()).isTrue(); assertThat(future.result().getCountry()).isEqualTo("country"); verify(wrappedGeoLocationService).lookup(any(), any()); }
Example #21
Source Project: vertx-elasticsearch-service Author: hubrick File: DefaultElasticSearchService.java License: Apache License 2.0 | 5 votes |
@Override public void deleteByQuery(List<String> indices, DeleteByQueryOptions options, Handler<AsyncResult<com.hubrick.vertx.elasticsearch.model.DeleteByQueryResponse>> resultHandler) { final DeleteByQueryRequestBuilder deleteByQueryRequestBuilder = new DeleteByQueryRequestBuilder(client, DeleteByQueryAction.INSTANCE); deleteByQueryRequestBuilder.source(indices.toArray(new String[indices.size()])); if (options != null) { populateSearchRequestBuilder(deleteByQueryRequestBuilder.source(), options); if (options.getMaxRetries() != null) deleteByQueryRequestBuilder.setMaxRetries(options.getMaxRetries()); if (options.getSlices() != null) deleteByQueryRequestBuilder.setSlices(options.getSlices()); if (options.getWaitForActiveShards() != null) deleteByQueryRequestBuilder.waitForActiveShards(ActiveShardCount.from(options.getWaitForActiveShards())); if (options.getConflicts() != null) deleteByQueryRequestBuilder.abortOnVersionConflict(Optional.ofNullable(options.getConflicts()).map(e -> !Conflicts.PROCEED.equals(e)).orElse(true)); if (options.getRequestsPerSecond() != null) deleteByQueryRequestBuilder.setRequestsPerSecond(options.getRequestsPerSecond()); } deleteByQueryRequestBuilder.execute(new ActionListener<BulkByScrollResponse>() { @Override public void onResponse(BulkByScrollResponse deleteByQueryResponse) { resultHandler.handle(Future.succeededFuture(mapToDeleteByQueryResponse(deleteByQueryResponse))); } @Override public void onFailure(Exception t) { handleFailure(resultHandler, t); } }); }
Example #22
Source Project: vertx-kubernetes-workshop Author: cescoffier File: RXCompulsiveTraderVerticle.java License: Apache License 2.0 | 5 votes |
@Override public void start(Future<Void> future) { String company = TraderUtils.pickACompany(); int numberOfShares = TraderUtils.pickANumber(); System.out.println("Java-RX compulsive trader configured for company " + company + " and shares: " + numberOfShares); ServiceDiscovery.create(vertx, discovery -> { Single<PortfolioService> retrieveThePortfolioService = RXEventBusService.rxGetProxy(discovery, PortfolioService.class, rec -> rec.getName().equalsIgnoreCase("portfolio")); Single<MessageConsumer<JsonObject>> retrieveTheMarket = MessageSource.rxGetConsumer(discovery, rec -> rec.getName().equalsIgnoreCase("market-data")); //TODO //---- // TODO 1 - "wait" for both single to be completed (using Single.zip or Single.zipWith methods) // TODO 2 - When both single have completed, attach the handler to the message consumer to execute the // trading logic // TODO 3 - Use the TraderUtils.drumpTradingLogic method returning a Completable. Don't forget to // subscribe to it, or nothing will happen. Return "true" to comply with the "zip" operator // signature. // TODO 4 - Transform the output into a Completable (toCompletable) and subscribe to it using: //.subscribe(CompletableHelper.toObserver(future)) - it reports the failure or success to the `done` // future. // To remove future.complete(); //---- }); }
Example #23
Source Project: VX-API-Gateway Author: EliMirren File: CLIVerticle.java License: MIT License | 5 votes |
/** * 启动所有网关应用与API服务 * * @param apps * 应用集合 * @param success * 成功的数量 * @param fail * 失败的数量 * @param startAPI * 是否启动API true启动false不启动 * @param handler * 返回json key : success成功的数量,fail失败的数量 */ public void startAppService(JsonArray apps, int success, int fail, boolean startAPI, Handler<AsyncResult<JsonObject>> handler) { if (apps == null || apps.size() < 1) { JsonObject result = new JsonObject(); result.put("success", success); result.put("fail", fail); handler.handle(Future.succeededFuture(result)); return; } // 网关应用 JsonObject body = (JsonObject) apps.remove(0); // 网关应用的名字 final String appName = body.getString("appName"); if (appName == null) { startAppService(apps, success, fail + 1, startAPI, handler); LOG.error("cli->执行启动网关应用-->失败:获取不到应用的名字:" + body); return; } // 启动网关应用需要的配置信息 JsonObject config = new JsonObject(); config.put("app", body); config.put("appName", appName); String startAppAddress = thisVertxName + VxApiEventBusAddressConstant.DEPLOY_APP_DEPLOY; vertx.eventBus().send(startAppAddress, config, res -> { if (res.succeeded()) { // 判断是否启动所有API if (startAPI) { startAllAPI(appName); } startAppService(apps, success + 1, fail, startAPI, handler); } else { startAppService(apps, success, fail + 1, startAPI, handler); LOG.error("cli->执行启动网关应用-->失败:" + res.cause()); } }); }
Example #24
Source Project: hono Author: eclipse File: VertxBasedAmqpProtocolAdapterTest.java License: Eclipse Public License 2.0 | 5 votes |
/** * Verifies that a request to upload a pre-settled telemetry message results * in the downstream sender not waiting for the consumer's acknowledgment. * * @param ctx The vert.x test context. */ @Test public void testUploadTelemetryWithAtMostOnceDeliverySemantics(final VertxTestContext ctx) { // GIVEN an AMQP adapter with a configured server final VertxBasedAmqpProtocolAdapter adapter = givenAnAmqpAdapter(); final DownstreamSender telemetrySender = givenATelemetrySenderForAnyTenant(); when(telemetrySender.send(any(Message.class), (SpanContext) any())).thenReturn(Future.succeededFuture(mock(ProtonDelivery.class))); // which is enabled for a tenant final TenantObject tenantObject = givenAConfiguredTenant(TEST_TENANT_ID, true); // IF a device sends a 'fire and forget' telemetry message final ProtonDelivery delivery = mock(ProtonDelivery.class); when(delivery.remotelySettled()).thenReturn(true); final Buffer payload = Buffer.buffer("payload"); final String to = ResourceIdentifier.from(TelemetryConstants.TELEMETRY_ENDPOINT, TEST_TENANT_ID, TEST_DEVICE).toString(); adapter.onMessageReceived(AmqpContext.fromMessage(delivery, getFakeMessage(to, payload), null)) .onComplete(ctx.succeeding(d -> { ctx.verify(() -> { // THEN the adapter has forwarded the message downstream verify(telemetrySender).send(any(Message.class), (SpanContext) any()); // and acknowledged the message to the device verify(delivery).disposition(any(Accepted.class), eq(true)); // and has reported the telemetry message verify(metrics).reportTelemetry( eq(EndpointType.TELEMETRY), eq(TEST_TENANT_ID), eq(tenantObject), eq(ProcessingOutcome.FORWARDED), eq(QoS.AT_MOST_ONCE), eq(payload.length()), any()); }); ctx.completeNow(); })); }
Example #25
Source Project: vertx-web Author: vert-x3 File: OpenAPIHolderTest.java License: Apache License 2.0 | 5 votes |
private void stopSchemaServer(Handler<AsyncResult<Void>> completion) { if (schemaServer != null) { try { schemaServer.close((asyncResult) -> { completion.handle(Future.succeededFuture()); }); } catch (IllegalStateException e) { // Server is already open completion.handle(Future.succeededFuture()); } } else completion.handle(Future.succeededFuture()); }
Example #26
Source Project: vertx-web Author: vert-x3 File: AnotherTestServiceImpl.java License: Apache License 2.0 | 5 votes |
@Override public void testD(ServiceRequest context, Handler<AsyncResult<ServiceResponse>> resultHandler) { JsonObject body = context.getParams().getJsonObject("body"); resultHandler.handle(Future.succeededFuture( ServiceResponse.completedWithJson( new JsonObject() .put("content-type", context.getHeaders().get(HttpHeaders.CONTENT_TYPE)) .put("anotherResult", body.getString("name") + " " + body.getString("hello") + "?") ) )); }
Example #27
Source Project: raml-module-builder Author: folio-org File: PostgresClient.java License: Apache License 2.0 | 5 votes |
/** * Will connect to a specific database and execute the commands in the .sql file * against that database.<p /> * NOTE: NOT tested on all types of statements - but on a lot * * @param sqlFile - string of sqls with executable statements * @param stopOnError - stop on first error * @param replyHandler - the handler's result is the list of statements that failed; the list may be empty */ public void runSQLFile(String sqlFile, boolean stopOnError, Handler<AsyncResult<List<String>>> replyHandler){ try { execute(preprocessSqlStatements(sqlFile), stopOnError, replyHandler); } catch (Exception e) { log.error(e.getMessage(), e); replyHandler.handle(Future.failedFuture(e)); } }
Example #28
Source Project: vertx-web Author: vert-x3 File: RouterFactorySecurityTest.java License: Apache License 2.0 | 5 votes |
private AuthenticationHandler mockFailingAuthHandler(Handler<RoutingContext> mockHandler) { return new AuthenticationHandlerImpl<AuthenticationProvider>((authInfo, resultHandler) -> resultHandler.handle(Future.succeededFuture(User.create(new JsonObject())))) { @Override public void parseCredentials(RoutingContext context, Handler<AsyncResult<Credentials>> handler) { mockHandler.handle(context); handler.handle(Future.failedFuture(new HttpStatusException(401))); } }; }
Example #29
Source Project: hono Author: eclipse File: FileBasedRegistrationService.java License: Eclipse Public License 2.0 | 5 votes |
@Override protected Future<RegistrationResult> processAssertRegistration(final DeviceKey key, final Span span) { Objects.requireNonNull(key); Objects.requireNonNull(span); return Future.succeededFuture( convertResult(key.getDeviceId(), processReadDevice(key.getTenantId(), key.getDeviceId(), span))); }
Example #30
Source Project: hono Author: eclipse File: CommandSubscriptionsManager.java License: Eclipse Public License 2.0 | 5 votes |
/** * Closes the command consumer and removes the subscription entry for the given topic. * * @param topic The topic string to unsubscribe. * @param onConsumerRemovedFunction The function to be invoked if not {@code null} during removal of a subscription. * The first parameter is the tenant id, the second parameter the device id. * To be returned is a future indicating the outcome of the function. * @param spanContext The span context (may be {@code null}). * @throws NullPointerException if topic is {@code null}. * @return A future indicating the outcome of the operation. **/ public Future<Void> removeSubscription(final String topic, final BiFunction<String, String, Future<Void>> onConsumerRemovedFunction, final SpanContext spanContext) { Objects.requireNonNull(topic); final TriTuple<CommandSubscription, ProtocolAdapterCommandConsumer, Object> removed = subscriptions.remove(topic); if (removed != null) { final CommandSubscription subscription = removed.one(); final Future<Void> functionFuture = onConsumerRemovedFunction != null ? onConsumerRemovedFunction.apply(subscription.getTenant(), subscription.getDeviceId()) : Future.succeededFuture(); final ProtocolAdapterCommandConsumer commandConsumer = removed.two(); return CompositeFuture .join(functionFuture, closeCommandConsumer(subscription, commandConsumer, spanContext)).mapEmpty(); } else { LOG.debug("Cannot remove subscription; none registered for topic [{}]", topic); return Future.failedFuture(String.format("Cannot remove subscription; none registered for topic [%s]", topic)); } }