java.util.concurrent.CompletableFuture Java Examples

The following examples show how to use java.util.concurrent.CompletableFuture. 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 File: ServerTextChannelBuilderDelegateImpl.java    From Javacord with Apache License 2.0 6 votes vote down vote up
@Override
public CompletableFuture<ServerTextChannel> create() {
    ObjectNode body = JsonNodeFactory.instance.objectNode();
    body.put("type", 0);
    super.prepareBody(body);
    if (topic != null) {
        body.put("topic", topic);
    }
    if (category != null) {
        body.put("parent_id", category.getIdAsString());
    }
    if (delayModified) {
        body.put("rate_limit_per_user", delay);
    }
    return new RestRequest<ServerTextChannel>(server.getApi(), RestMethod.POST, RestEndpoint.SERVER_CHANNEL)
            .setUrlParameters(server.getIdAsString())
            .setBody(body)
            .setAuditLogReason(reason)
            .execute(result -> server.getOrCreateServerTextChannel(result.getJsonBody()));
}
 
Example #2
Source File: ZKMetadataStore.java    From pulsar with Apache License 2.0 6 votes vote down vote up
@Override
public CompletableFuture<Boolean> exists(String path) {
    CompletableFuture<Boolean> future = new CompletableFuture<>();

    try {
        zkc.exists(path, null, (rc, path1, ctx, stat) -> {
            executor.execute(() -> {
                Code code = Code.get(rc);
                if (code == Code.OK) {
                    future.complete(true);
                } else if (code == Code.NONODE) {
                    future.complete(false);
                } else {
                    future.completeExceptionally(getException(code, path));
                }
            });
        }, future);
    } catch (Throwable t) {
        future.completeExceptionally(new MetadataStoreException(t));
    }

    return future;
}
 
Example #3
Source File: BattleDisplay.java    From triplea with GNU General Public License v3.0 6 votes vote down vote up
private Action getPlayerAction(
    final String title,
    final Supplier<RetreatResult> showDialog,
    final CompletableFuture<Territory> future) {
  return SwingAction.of(
      title,
      e -> {
        actionButton.setEnabled(false);
        final RetreatResult retreatResult = showDialog.get();
        if (retreatResult.isConfirmed()) {
          future.complete(retreatResult.getTarget());
          actionButton.setAction(nullAction);
        }
        actionButton.setEnabled(true);
      });
}
 
Example #4
Source File: ProjectionManager.java    From esjc with MIT License 6 votes vote down vote up
/**
 * Creates a projection with default options of the specified mode.
 *
 * @param name            the name of the projection.
 * @param query           the JavaScript source code for the query.
 * @param mode            projection mode.
 * @param userCredentials user credentials to be used for this operation (use {@code null} for default user credentials).
 * @return a {@code CompletableFuture} representing the result of this operation. The future's methods
 * {@code get} and {@code join} can throw an exception with cause {@link ProjectionConflictException}
 * or {@link ProjectionException} on exceptional completion. In case of successful completion,
 * the future's methods {@code get} and {@code join} returns {@code null}.
 * @see #create(String, String, CreateOptions, UserCredentials)
 */
default CompletableFuture<Void> create(String name, String query, ProjectionMode mode, UserCredentials userCredentials) {
    checkNotNull(mode, "mode is null");

    CreateOptions options;

    switch (mode) {
        case TRANSIENT:
            options = CreateOptions.TRANSIENT;
            break;
        case ONE_TIME:
            options = CreateOptions.ONE_TIME;
            break;
        case CONTINUOUS:
            options = CreateOptions.CONTINUOUS;
            break;
        default:
            throw new IllegalArgumentException("Unsupported projection mode: " + mode);
    }

    return create(name, query, options, userCredentials);
}
 
Example #5
Source File: TaskStoreFactoryForTests.java    From pravega with Apache License 2.0 6 votes vote down vote up
@Override
public CompletableFuture<Void> lock(final Resource resource,
                                    final TaskData taskData,
                                    final String owner,
                                    final String tag,
                                    final String oldOwner,
                                    final String oldTag) {
    CompletableFuture<Void> future = super.lock(resource, taskData, owner, tag, oldOwner, oldTag);

    CompletableFuture<Void> lf = latch.get();
    if (lf != null && first.getAndSet(false)) {
        log.debug("Waiting on the second thread to request the lock and complete the future");
        lf.join();
    } else if (lf != null) {
        log.debug("I'm the second thread, completing the future");
        lf.complete(null);
        latch.set(null);
    } else {
        log.debug("Latch is null");
    }

    return future;
}
 
Example #6
Source File: ParsecAsyncHttpClient.java    From parsec-libraries with Apache License 2.0 6 votes vote down vote up
/**
 * Critical execute a request (will not lookup in cache nor load into cache).
 *
 * @param request Request to critical execute
 * @param asyncHandler Request async handler
 * @param <T> Response type
 * @return {@literal CompletableFuture<T>}
 */
public <T> CompletableFuture<T> criticalExecute(
    final ParsecAsyncHttpRequest request,
    AsyncHandler<T> asyncHandler
) {
    AsyncHandler<T> practicalAsyncHandler =
        oldFashionProfiling? new ParsecAsyncHandlerWrapper<>(asyncHandler, request.getNingRequest()): asyncHandler;

    if (request.getRetryStatusCodes().isEmpty() && request.getRetryExceptions().isEmpty()) {
        return new ParsecCompletableFuture<>(
            client.executeRequest(request.getNingRequest(), practicalAsyncHandler)
        );
    } else {
        ParsecHttpRequestRetryCallable<T> retryCallable;
        retryCallable = retryIntervalMillisOpt.map(retryIntervalMillis -> new ParsecHttpRequestRetryCallable<>(
            client, request, practicalAsyncHandler, retryIntervalMillis))
            .orElseGet(() -> new ParsecHttpRequestRetryCallable<>(client, request, practicalAsyncHandler));
        return new ParsecCompletableFuture<>(executorService.submit(retryCallable));
    }
}
 
Example #7
Source File: Dispatcher.java    From Flink-CEPplus with Apache License 2.0 6 votes vote down vote up
@Override
public CompletableFuture<ClusterOverview> requestClusterOverview(Time timeout) {
	CompletableFuture<ResourceOverview> taskManagerOverviewFuture = runResourceManagerCommand(resourceManagerGateway -> resourceManagerGateway.requestResourceOverview(timeout));

	final List<CompletableFuture<Optional<JobStatus>>> optionalJobInformation = queryJobMastersForInformation(
		(JobMasterGateway jobMasterGateway) -> jobMasterGateway.requestJobStatus(timeout));

	CompletableFuture<Collection<Optional<JobStatus>>> allOptionalJobsFuture = FutureUtils.combineAll(optionalJobInformation);

	CompletableFuture<Collection<JobStatus>> allJobsFuture = allOptionalJobsFuture.thenApply(this::flattenOptionalCollection);

	final JobsOverview completedJobsOverview = archivedExecutionGraphStore.getStoredJobsOverview();

	return allJobsFuture.thenCombine(
		taskManagerOverviewFuture,
		(Collection<JobStatus> runningJobsStatus, ResourceOverview resourceOverview) -> {
			final JobsOverview allJobsOverview = JobsOverview.create(runningJobsStatus).combine(completedJobsOverview);
			return new ClusterOverview(resourceOverview, allJobsOverview);
		});
}
 
Example #8
Source File: BKLogWriteHandler.java    From distributedlog with Apache License 2.0 6 votes vote down vote up
/**
 * Close log segment.
 *
 * @param inprogressZnodeName
 * @param logSegmentSeqNo
 * @param logSegmentId
 * @param firstTxId
 * @param lastTxId
 * @param recordCount
 * @param lastEntryId
 * @param lastSlotId
 * @throws IOException
 */
protected LogSegmentMetadata doCompleteAndCloseLogSegment(
        String inprogressZnodeName,
        long logSegmentSeqNo,
        long logSegmentId,
        long firstTxId,
        long lastTxId,
        int recordCount,
        long lastEntryId,
        long lastSlotId) throws IOException {
    CompletableFuture<LogSegmentMetadata> promise = new CompletableFuture<LogSegmentMetadata>();
    doCompleteAndCloseLogSegment(
            inprogressZnodeName,
            logSegmentSeqNo,
            logSegmentId,
            firstTxId,
            lastTxId,
            recordCount,
            lastEntryId,
            lastSlotId,
            promise);
    return Utils.ioResult(promise);
}
 
Example #9
Source File: Dispatcher.java    From Flink-CEPplus with Apache License 2.0 6 votes vote down vote up
@Override
public CompletableFuture<JobStatus> requestJobStatus(JobID jobId, Time timeout) {

	final CompletableFuture<JobMasterGateway> jobMasterGatewayFuture = getJobMasterGatewayFuture(jobId);

	final CompletableFuture<JobStatus> jobStatusFuture = jobMasterGatewayFuture.thenCompose(
		(JobMasterGateway jobMasterGateway) -> jobMasterGateway.requestJobStatus(timeout));

	return jobStatusFuture.exceptionally(
		(Throwable throwable) -> {
			final JobDetails jobDetails = archivedExecutionGraphStore.getAvailableJobDetails(jobId);

			// check whether it is a completed job
			if (jobDetails == null) {
				throw new CompletionException(ExceptionUtils.stripCompletionException(throwable));
			} else {
				return jobDetails.getStatus();
			}
		});
}
 
Example #10
Source File: ShardDMLExecutor.java    From crate with Apache License 2.0 6 votes vote down vote up
@Override
public CompletableFuture<TResult> apply(BatchIterator<Row> batchIterator) {
    BatchIterator<TReq> reqBatchIterator =
        BatchIterators.partition(batchIterator, bulkSize, requestFactory, this::addRowToRequest, r -> false);
    // If the source batch iterator does not involve IO, mostly in-memory structures are used which we want to free
    // as soon as possible. We do not want to throttle based on the targets node counter in such cases.
    Predicate<TReq> shouldPause = ignored -> true;
    if (batchIterator.hasLazyResultSet()) {
        shouldPause = ignored ->
            nodeJobsCounter.getInProgressJobsForNode(localNodeId) >= MAX_NODE_CONCURRENT_OPERATIONS;
    }

    return new BatchIteratorBackpressureExecutor<>(
        scheduler,
        executor,
        reqBatchIterator,
        this::executeBatch,
        collector.combiner(),
        collector.supplier().get(),
        shouldPause,
        BACKOFF_POLICY
    ).consumeIteratorAndExecute()
        .thenApply(collector.finisher());
}
 
Example #11
Source File: FileDownloadExample.java    From datakernel with Apache License 2.0 5 votes vote down vote up
@Override
protected void run() throws Exception {
	ExecutorService executor = newSingleThreadExecutor();
	CompletableFuture<Void> future = eventloop.submit(() ->
			ChannelSupplier.ofPromise(client.download(REQUIRED_FILE))
					.streamTo(ChannelFileWriter.open(executor, clientStorage.resolve(DOWNLOADED_FILE)))
					.whenResult(() -> System.out.printf("\nFile '%s' successfully downloaded to '%s'\n\n",
							REQUIRED_FILE, clientStorage))
	);
	future.get();
	executor.shutdown();
}
 
Example #12
Source File: Async.java    From caffeine with Apache License 2.0 5 votes vote down vote up
@Override
@SuppressWarnings("FutureReturnValueIgnored")
public void onRemoval(@Nullable K key,
    @Nullable CompletableFuture<V> future, RemovalCause cause) {
  if (future != null) {
    future.thenAcceptAsync(value -> delegate.onRemoval(key, value, cause), executor);
  }
}
 
Example #13
Source File: CliMainTest.java    From styx with Apache License 2.0 5 votes vote down vote up
@Test
public void testBackfillShow() {
  final String backfillId = "backfill-2";

  final Backfill backfill = Backfill.newBuilder()
      .id(backfillId)
      .start(Instant.parse("2017-01-01T00:00:00Z"))
      .end(Instant.parse("2017-01-30T00:00:00Z"))
      .workflowId(WorkflowId.create("quux", backfillId))
      .concurrency(1)
      .description("Description")
      .nextTrigger(Instant.parse("2017-01-01T00:00:00Z"))
      .schedule(Schedule.DAYS)
      .created(currentTime)
      .lastModified(currentTime)
      .build();
  
  final BackfillPayload backfillPayload = BackfillPayload.create(backfill,
      Optional.empty());

  when(client.backfill(backfillId, true))
      .thenReturn(CompletableFuture.completedFuture(backfillPayload));

  CliMain.run(cliContext, "backfill", "show", backfillId, "--no-trunc");
  
  verify(client).backfill(backfillId, true);
  verify(cliOutput).printBackfillPayload(backfillPayload, true);
}
 
Example #14
Source File: HttpHandler.java    From webster with Apache License 2.0 5 votes vote down vote up
public HttpHandler(Function<Request, CompletableFuture<Response>> requestHandler,
                   ExecutorService executor,
                   long timeoutMillis) {
    super(false);
    this.requestHandler = requestHandler;
    this.executor = executor;
    this.timeoutMillis = timeoutMillis;
}
 
Example #15
Source File: BookKeeperLogTests.java    From pravega with Apache License 2.0 5 votes vote down vote up
/**
 * Tests the ability to retry writes when Bookies fail.
 */
@Test
public void testAppendTransientBookieFailure() throws Exception {
    TreeMap<LogAddress, byte[]> writeData = new TreeMap<>(Comparator.comparingLong(LogAddress::getSequence));
    try (DurableDataLog log = createDurableDataLog()) {
        log.initialize(TIMEOUT);

        val dataList = new ArrayList<byte[]>();
        val futures = new ArrayList<CompletableFuture<LogAddress>>();

        try {
            // Suspend a bookie (this will trigger write errors).
            stopFirstBookie();

            // Issue appends in parallel, without waiting for them.
            int writeCount = getWriteCount();
            for (int i = 0; i < writeCount; i++) {
                byte[] data = getWriteData();
                futures.add(log.append(new CompositeByteArraySegment(data), TIMEOUT));
                dataList.add(data);
            }
        } finally {
            // Resume the bookie with the appends still in flight.
            restartFirstBookie();
        }

        // Wait for all writes to complete, then reassemble the data in the order set by LogAddress.
        val addresses = Futures.allOfWithResults(futures).join();
        for (int i = 0; i < dataList.size(); i++) {
            writeData.put(addresses.get(i), dataList.get(i));
        }
    }

    // Verify data.
    try (DurableDataLog log = createDurableDataLog()) {
        log.initialize(TIMEOUT);
        verifyReads(log, writeData);
    }
}
 
Example #16
Source File: AbstractEndpointSelector.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Override
public final CompletableFuture<Endpoint> select(ClientRequestContext ctx,
                                                ScheduledExecutorService executor,
                                                long timeoutMillis) {
    Endpoint endpoint = selectNow(ctx);
    if (endpoint != null) {
        return UnmodifiableFuture.completedFuture(endpoint);
    }

    final ListeningFuture listeningFuture = new ListeningFuture(ctx, executor);
    endpointGroup.addListener(listeningFuture);

    // Try to select again because the EndpointGroup might have been updated
    // between selectNow() and addListener() above.
    endpoint = selectNow(ctx);
    if (endpoint != null) {
        endpointGroup.removeListener(listeningFuture);
        return UnmodifiableFuture.completedFuture(endpoint);
    }

    // Schedule the timeout task.
    final ScheduledFuture<?> timeoutFuture =
            executor.schedule(() -> listeningFuture.complete(null),
                              timeoutMillis, TimeUnit.MILLISECONDS);
    listeningFuture.timeoutFuture = timeoutFuture;

    // Cancel the timeout task if listeningFuture is done already.
    // This guards against the following race condition:
    // 1) (Current thread) Timeout task is scheduled.
    // 2) ( Other thread ) listeningFuture is completed, but the timeout task is not cancelled
    // 3) (Current thread) timeoutFuture is assigned to listeningFuture.timeoutFuture, but it's too late.
    if (listeningFuture.isDone()) {
        timeoutFuture.cancel(false);
    }

    return listeningFuture;
}
 
Example #17
Source File: FilterStageVerification.java    From microprofile-reactive-streams-operators with Apache License 2.0 5 votes vote down vote up
@Test(expectedExceptions = QuietRuntimeException.class, expectedExceptionsMessageRegExp = "failed")
public void filterStageShouldPropagateExceptions() {
    CompletableFuture<Void> cancelled = new CompletableFuture<>();
    CompletionStage<List<Integer>> result = infiniteStream()
        .onTerminate(() -> cancelled.complete(null))
        .filter(foo -> {
            throw new QuietRuntimeException("failed");
        })
        .toList()
        .run(getEngine());
    await(cancelled);
    await(result);
}
 
Example #18
Source File: Retryer.java    From mug with Apache License 2.0 5 votes vote down vote up
private <E extends Throwable, T> void retryIfCovered(
    E e, ScheduledExecutorService retryExecutor,
    CheckedSupplier<? extends CompletionStage<T>, ?> supplier, CompletableFuture<T> future)
        throws E {
  if (plan.covers(e)) {
    scheduleRetry(e, retryExecutor, supplier, future);
  } else {
    throw e;
  }
}
 
Example #19
Source File: CachingAsyncAtomicDocumentTree.java    From atomix with Apache License 2.0 5 votes vote down vote up
@Override
public CompletableFuture<Boolean> replace(DocumentPath path, V newValue, long version) {
  return super.replace(path, newValue, version)
      .whenComplete((r, e) -> {
        if (r) {
          cache.invalidate(path);
        }
      });
}
 
Example #20
Source File: ThenComposeAsyncTest.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
public void testThenComposeAsync() throws Exception {
    // Composing CompletableFuture is complete
    CompletableFuture<String> cf1 = CompletableFuture.completedFuture("one");

    // Composing function returns a CompletableFuture executed asynchronously
    CountDownLatch cdl = new CountDownLatch(1);
    CompletableFuture<String> cf2 = cf1.thenCompose(str -> CompletableFuture.supplyAsync(() -> {
        while (true) {
            try {
                cdl.await();
                break;
            }
            catch (InterruptedException e) {
            }
        }
        return str + ", two";
    }));

    // Ensure returned CompletableFuture completes after call to thenCompose
    // This guarantees that any premature internal completion will be
    // detected
    cdl.countDown();

    String val = cf2.get();
    Assert.assertNotNull(val);
    Assert.assertEquals(val, "one, two");
}
 
Example #21
Source File: RlpxConnectionTest.java    From besu with Apache License 2.0 5 votes vote down vote up
@Test
public void getPeer_pendingOutboundConnection() {
  final Peer peer = createPeer();
  final CompletableFuture<PeerConnection> future = new CompletableFuture<>();
  final RlpxConnection conn = RlpxConnection.outboundConnection(peer, future);

  assertThat(conn.getPeer()).isEqualTo(peer);
}
 
Example #22
Source File: CommandProcessTest.java    From vertx-shell with Apache License 2.0 5 votes vote down vote up
private Process createProcessInContext(Context context, Command command) throws Exception {
  CompletableFuture<Process> fut = new CompletableFuture<>();
  context.runOnContext(v -> {
    Process process = command.createProcess().setSession(Session.create()).setTty(Pty.create().slave());
    fut.complete(process);
  });
  return fut.get(2000, TimeUnit.MILLISECONDS);
}
 
Example #23
Source File: AtomixDocumentTree.java    From onos with Apache License 2.0 5 votes vote down vote up
@Override
public synchronized CompletableFuture<Void> addListener(DocumentPath path, DocumentTreeListener<V> listener) {
    io.atomix.core.tree.DocumentTreeEventListener<V> atomixListener = event ->
        listener.event(new DocumentTreeEvent<V>(
            toOnosPath(event.path()),
            DocumentTreeEvent.Type.valueOf(event.type().name()),
            event.newValue().map(this::toVersioned),
            event.oldValue().map(this::toVersioned)));
    listenerMap.put(listener, atomixListener);
    return adaptTreeFuture(atomixTree.addListener(toAtomixPath(path), atomixListener));
}
 
Example #24
Source File: BaseCharacteristic.java    From HAP-Java with MIT License 5 votes vote down vote up
/**
 * Creates the JSON serialized form of the accessory for use over the HomeKit Accessory Protocol.
 *
 * @param instanceId the static id of the accessory.
 * @return a future that will complete with the JSON builder for the object.
 */
protected CompletableFuture<JsonObjectBuilder> makeBuilder(int instanceId) {
  CompletableFuture<T> futureValue = getValue();

  if (futureValue == null) {
    futureValue = CompletableFuture.completedFuture(getDefault());
  }

  return futureValue
      .exceptionally(
          t -> {
            logger.warn("Could not retrieve value " + this.getClass().getName(), t);
            return null;
          })
      .thenApply(
          value -> {
            JsonArrayBuilder perms = Json.createArrayBuilder();
            if (isReadable) {
              perms.add("pr");
            }
            if (isWritable) {
              perms.add("pw");
            }
            if (subscriber.isPresent()) {
              perms.add("ev");
            }
            JsonObjectBuilder builder =
                Json.createObjectBuilder()
                    .add("iid", instanceId)
                    .add("type", shortType)
                    .add("perms", perms.build())
                    .add("format", format)
                    .add("ev", false)
                    .add("description", description);
            if (isReadable) setJsonValue(builder, value);
            return builder;
          });
}
 
Example #25
Source File: MiddlewareSetTest.java    From botbuilder-java with MIT License 5 votes vote down vote up
@Test
public void RunCodeBeforeAndAfter() {
    final boolean[] didRun1 = { false };
    final boolean[] codeafter2run = { false };
    final boolean[] didRun2 = { false };

    MiddlewareSet m = new MiddlewareSet();

    m.use(new AnonymousReceiveMiddleware((tc, nd) -> {
        Assert.assertFalse("Looks like the 1st middleware has already run", didRun1[0]);
        didRun1[0] = true;
        CompletableFuture<Void> result = nd.next();
        Assert.assertTrue("The 2nd middleware should have run now.", didRun1[0]);
        codeafter2run[0] = true;
        return result;
    }));

    m.use(new AnonymousReceiveMiddleware((tc, nd) -> {
        Assert.assertTrue("Looks like the 1st middleware has not been run", didRun1[0]);
        Assert.assertFalse(
            "The code that runs after middleware 2 is complete has already run.",
            codeafter2run[0]
        );
        didRun2[0] = true;
        return nd.next();
    }));

    m.receiveActivityWithStatus(null, null).join();
    Assert.assertTrue(didRun1[0]);
    Assert.assertTrue(didRun2[0]);
    Assert.assertTrue(codeafter2run[0]);
}
 
Example #26
Source File: RepoIO.java    From HubTurbo with GNU Lesser General Public License v3.0 5 votes vote down vote up
public CompletableFuture<Model> updateModel(Model model, boolean syncOperation, int remainingTries) {
    return downloadModelUpdates(model)
            .thenCompose((updates) -> getRepoOpControl().updateLocalModel(updates, syncOperation))
            .thenApply(newModel -> {
                boolean corruptedJson = false;
                if (!model.equals(newModel)) {
                    try {
                        corruptedJson =
                                jsonStore.saveRepository(newModel.getRepoId(), new SerializableModel(newModel))
                                        .get();
                    } catch (InterruptedException | ExecutionException ex) {
                        corruptedJson = true;
                    }
                } else {
                    logger.info(HTLog.format(model.getRepoId(),
                                             "Nothing changed; not writing to store"));
                }
                if (corruptedJson && remainingTries > 0) {
                    return downloadRepoFromSourceAsync(model.getRepoId(), remainingTries - 1).join();
                } else {
                    if (corruptedJson && remainingTries == 0) {
                        UI.events.triggerEvent(new ShowErrorDialogEvent("Could not sync " + model.getRepoId(),
                                        "We were not able to sync with GitHub "
                                        + "to retrieve and store data for the repository "
                                        + model.getRepoId()
                                        + ". Please let us know if you "
                                        + "encounter this issue consistently."));
                    } else {
                        UI.status.displayMessage(model.getRepoId() + " is up to date!");
                    }
                    UI.events.triggerEvent(new UpdateProgressEvent(model.getRepoId()));
                    return newModel;
                }
            }).exceptionally(withResult(new Model(model.getRepoId())));
}
 
Example #27
Source File: DefaultAtomicValueBuilder.java    From atomix with Apache License 2.0 5 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public CompletableFuture<AtomicValue<V>> buildAsync() {
  return newProxy(AtomicValueService.class, new ServiceConfig())
      .thenCompose(proxy -> new AtomicValueProxy(proxy, managementService.getPrimitiveRegistry()).connect())
      .thenApply(elector -> {
        Serializer serializer = serializer();
        return new TranscodingAsyncAtomicValue<V, byte[]>(
            elector,
            key -> serializer.encode(key),
            bytes -> serializer.decode(bytes))
            .sync();
      });
}
 
Example #28
Source File: TestAsyncRetriableTable.java    From samza with Apache License 2.0 5 votes vote down vote up
@Test
public void testPutWithPermFailureOnTimeout() {
  TableRetryPolicy policy = new TableRetryPolicy();
  policy.withFixedBackoff(Duration.ofMillis(5));
  policy.withStopAfterDelay(Duration.ofMillis(100));
  TableReadFunction<String, String> readFn = mock(TableReadFunction.class);
  TableWriteFunction<String, String> writeFn = mock(TableWriteFunction.class);
  doReturn(true).when(writeFn).isRetriable(any());
  CompletableFuture<String> future = new CompletableFuture();
  future.completeExceptionally(new RuntimeException("test exception"));
  doReturn(future).when(readFn).getAsync(anyString());
  AsyncReadWriteTable delegate = new AsyncRemoteTable(readFn, writeFn);
  AsyncRetriableTable table = new AsyncRetriableTable("t1", delegate, null, policy, schedExec, readFn, writeFn);
  table.init(TestRemoteTable.getMockContext());

  try {
    table.putAsync("foo", "bar").join();
    fail();
  } catch (Throwable t) {
  }

  verify(writeFn, atLeast(3)).putAsync(any(), any());
  assertTrue(table.writeRetryMetrics.retryCount.getCount() >= 3);
  assertEquals(0, table.writeRetryMetrics.successCount.getCount());
  assertEquals(1, table.writeRetryMetrics.permFailureCount.getCount());
  assertTrue(table.writeRetryMetrics.retryTimer.getSnapshot().getMax() > 0);
}
 
Example #29
Source File: JsonSchemaConverter.java    From component-runtime with Apache License 2.0 5 votes vote down vote up
@Override
public CompletionStage<PropertyContext<?>> convert(final CompletionStage<PropertyContext<?>> cs) {
    return cs.thenCompose(context -> {
        final JsonSchema jsonSchema = new JsonSchema();
        jsonSchema.setTitle(context.getProperty().getDisplayName());
        final String type = context.getProperty().getType();
        switch (type.toLowerCase(ROOT)) {
        case "enum":
            return new EnumPropertyConverter(jsonSchema)
                    .convert(CompletableFuture.completedFuture(context))
                    .thenCompose(c -> postHandling(context, jsonSchema, type));
        case "array":
            return new ArrayPropertyConverter(jsonb, jsonSchema, properties)
                    .convert(CompletableFuture.completedFuture(context))
                    .thenCompose(c -> postHandling(context, jsonSchema, type));
        default:
            if (context.getProperty().getPath().endsWith("[]")) {
                return CompletableFuture.completedFuture(context);
            }
            jsonSchema.setType(type.toLowerCase(ROOT));
            of(context
                    .findDirectChild(properties)
                    .filter(nested -> new PropertyContext<>(nested, context.getRootContext(),
                            context.getConfiguration()).isRequired())
                    .map(SimplePropertyDefinition::getName)
                    .collect(toSet())).filter(s -> !s.isEmpty()).ifPresent(jsonSchema::setRequired);
            return CompletableFuture
                    .completedFuture(context)
                    .thenCompose(c -> postHandling(context, jsonSchema, type));
        }
    });
}
 
Example #30
Source File: CompletableFutureResultType.java    From yql-plus with Apache License 2.0 4 votes vote down vote up
public CompletableFutureResultType(TypeWidget valueType) {
    super(Type.getType(CompletableFuture.class));
    this.valueType = valueType;
}