List of usage examples for java.util.concurrent CompletableFuture completedFuture
public static <U> CompletableFuture<U> completedFuture(U value)
From source file:com.ikanow.aleph2.shared.crud.mongodb.services.MongoDbCrudService.java
@Override public CompletableFuture<Long> countObjectsBySpec(final QueryComponent<O> spec) { try {// w ww . ja v a 2s. c o m final Tuple2<DBObject, DBObject> query_and_meta = MongoDbUtils.convertToMongoQuery(spec); final Long limit = (Long) query_and_meta._2().get("$limit"); if (null == limit) { return CompletableFuture.completedFuture(_state.orig_coll.count(query_and_meta._1())); } else { final BasicDBObject count_command = new BasicDBObject("count", _state.orig_coll.getName()); count_command.put("query", query_and_meta._1()); count_command.put("limit", limit); return CompletableFuture.completedFuture( ((Number) _state.orig_coll.getDB().command(count_command).get("n")).longValue()); } } catch (Exception e) { return FutureUtils.<Long>returnError(e); } }
From source file:io.pravega.controller.store.stream.InMemoryStream.java
@Override CompletableFuture<Data<Integer>> getCompletedTx(UUID txId) { Preconditions.checkNotNull(txId);//from www . j a va2 s .com synchronized (txnsLock) { if (!completedTxns.containsKey(txId.toString())) { return FutureHelpers.failedFuture(StoreException.create(StoreException.Type.DATA_NOT_FOUND, "Stream: " + getName() + " Transaction: " + txId.toString())); } return CompletableFuture.completedFuture(copy(completedTxns.get(txId.toString()))); } }
From source file:io.pravega.controller.task.Stream.StreamTransactionMetadataTasks.java
private CompletableFuture<PingTxnStatus> fenceTxnUpdateLease(final String scope, final String stream, final UUID txnId, final long lease, final OperationContext ctx) { // Step 1. Check whether lease value is within necessary bounds. // Step 2. Add txn to host-transaction index. // Step 3. Update txn node data in the store,thus updating its version // and fencing other processes from tracking this txn's timeout. // Step 4. Add this txn to timeout service and start managing timeout for this txn. return streamMetadataStore.getTransactionData(scope, stream, txnId, ctx, executor) .thenComposeAsync(txnData -> { // Step 1. Sanity check for lease value. if (lease > txnData.getScaleGracePeriod() || lease > timeoutService.getMaxLeaseValue()) { return CompletableFuture.completedFuture(createStatus(Status.LEASE_TOO_LARGE)); } else if (lease + System.currentTimeMillis() > txnData.getMaxExecutionExpiryTime()) { return CompletableFuture.completedFuture(createStatus(Status.MAX_EXECUTION_TIME_EXCEEDED)); } else { TxnResource resource = new TxnResource(scope, stream, txnId); int expVersion = txnData.getVersion() + 1; // Step 2. Add txn to host-transaction index CompletableFuture<Void> addIndex = streamMetadataStore .addTxnToIndex(hostId, resource, expVersion).whenComplete((v, e) -> { if (e != null) { log.debug("Txn={}, failed adding txn to host-txn index of host={}", txnId, hostId); } else { log.debug("Txn={}, added txn to host-txn index of host={}", txnId, hostId); }//from www .j ava 2 s . co m }); return addIndex.thenComposeAsync(x -> { // Step 3. Update txn node data in the store. CompletableFuture<VersionedTransactionData> pingTxn = streamMetadataStore .pingTransaction(scope, stream, txnData, lease, ctx, executor) .whenComplete((v, e) -> { if (e != null) { log.debug("Txn={}, failed updating txn node in store", txnId); } else { log.debug("Txn={}, updated txn node in store", txnId); } }); // Step 4. Add it to timeout service and start managing timeout for this txn. return pingTxn.thenApplyAsync(data -> { int version = data.getVersion(); long expiryTime = data.getMaxExecutionExpiryTime(); long scaleGracePeriod = data.getScaleGracePeriod(); // Even if timeout service has an active/executing timeout task for this txn, it is bound // to fail, since version of txn node has changed because of the above store.pingTxn call. // Hence explicitly add a new timeout task. log.debug("Txn={}, adding txn to host-txn index", txnId); timeoutService.addTxn(scope, stream, txnId, version, lease, expiryTime, scaleGracePeriod); return createStatus(Status.OK); }, executor); }, executor); } }, executor); }
From source file:io.pravega.segmentstore.server.containers.StreamSegmentMapperTests.java
/** * Tests the ability of getOrAssignStreamSegmentId to handle the TooManyActiveSegmentsException. *//* w w w .j av a2s .c o m*/ @Test public void testGetOrAssignStreamSegmentIdWithMetadataLimit() throws Exception { final String segmentName = "Segment"; final String transactionName = StreamSegmentNameUtils.getTransactionNameFromId(segmentName, UUID.randomUUID()); HashSet<String> storageSegments = new HashSet<>(); storageSegments.add(segmentName); storageSegments.add(transactionName); @Cleanup TestContext context = new TestContext(); setupStorageGetHandler(context, storageSegments, name -> new StreamSegmentInformation(name, 0, false, false, new ImmutableDate())); // 1. Verify the behavior when even after the retry we still cannot map. AtomicInteger exceptionCounter = new AtomicInteger(); AtomicBoolean cleanupInvoked = new AtomicBoolean(); // We use 'containerId' as a proxy for the exception id (to make sure we collect the right one). context.operationLog.addHandler = op -> FutureHelpers .failedFuture(new TooManyActiveSegmentsException(exceptionCounter.incrementAndGet(), 0)); Supplier<CompletableFuture<Void>> noOpCleanup = () -> { if (!cleanupInvoked.compareAndSet(false, true)) { return FutureHelpers.failedFuture(new AssertionError("Cleanup invoked multiple times/")); } return CompletableFuture.completedFuture(null); }; val mapper1 = new StreamSegmentMapper(context.metadata, context.operationLog, context.stateStore, noOpCleanup, context.storage, executorService()); AssertExtensions.assertThrows( "Unexpected outcome when trying to map a segment name to a full metadata that cannot be cleaned.", () -> mapper1.getOrAssignStreamSegmentId(segmentName, TIMEOUT), ex -> ex instanceof TooManyActiveSegmentsException && ((TooManyActiveSegmentsException) ex).getContainerId() == exceptionCounter.get()); Assert.assertEquals("Unexpected number of attempts to map.", 2, exceptionCounter.get()); Assert.assertTrue("Cleanup was not invoked.", cleanupInvoked.get()); // Now with a transaction. exceptionCounter.set(0); cleanupInvoked.set(false); AssertExtensions.assertThrows( "Unexpected outcome when trying to map a segment name to a full metadata that cannot be cleaned.", () -> mapper1.getOrAssignStreamSegmentId(transactionName, TIMEOUT), ex -> ex instanceof TooManyActiveSegmentsException && ((TooManyActiveSegmentsException) ex).getContainerId() == exceptionCounter.get()); Assert.assertEquals("Unexpected number of attempts to map.", 2, exceptionCounter.get()); Assert.assertTrue("Cleanup was not invoked.", cleanupInvoked.get()); // 2. Verify the behavior when the first call fails, but the second one succeeds. exceptionCounter.set(0); cleanupInvoked.set(false); Supplier<CompletableFuture<Void>> workingCleanup = () -> { if (!cleanupInvoked.compareAndSet(false, true)) { return FutureHelpers.failedFuture(new AssertionError("Cleanup invoked multiple times.")); } setupOperationLog(context); // Setup the OperationLog to function correctly. return CompletableFuture.completedFuture(null); }; val mapper2 = new StreamSegmentMapper(context.metadata, context.operationLog, context.stateStore, workingCleanup, context.storage, executorService()); long id = mapper2.getOrAssignStreamSegmentId(segmentName, TIMEOUT).join(); Assert.assertEquals("Unexpected number of attempts to map.", 1, exceptionCounter.get()); Assert.assertTrue("Cleanup was not invoked.", cleanupInvoked.get()); Assert.assertNotEquals("No valid SegmentId assigned.", ContainerMetadata.NO_STREAM_SEGMENT_ID, id); }
From source file:io.pravega.controller.store.stream.InMemoryStream.java
@Override CompletableFuture<Void> removeActiveTxEntry(int epoch, UUID txId) { Preconditions.checkNotNull(txId);// w w w.j av a2 s . c om synchronized (txnsLock) { activeTxns.remove(txId.toString()); epochTxnMap.computeIfPresent(epoch, (x, y) -> { y.remove(txId.toString()); return y; }); } return CompletableFuture.completedFuture(null); }
From source file:com.ikanow.aleph2.management_db.mongodb.services.IkanowV1SyncService_TestBuckets.java
/** * Moves up to test_spec.requested_num_objects into v2_output_db * Then marks the TestQueueBean as completed. * //from w ww . j av a 2s . c o m * @param data_bucket * @param test_source * @param source_test_db * @param v2_output_db * @return */ @SuppressWarnings("unchecked") private CompletableFuture<Boolean> retireTestJob(final DataBucketBean data_bucket, final TestQueueBean test_source, final ICrudService<TestQueueBean> source_test_db, final ICrudService<JsonNode> v2_output_db) { _logger.debug("retiring job"); final long requested_num_objects = Optional.ofNullable(test_source.test_params().requested_num_objects()) .orElse(10L); return v2_output_db.getObjectsBySpec(CrudUtils.allOf().limit(requested_num_objects)) .thenCompose(results -> { _logger.debug("returned: " + results.count() + " items in output collection (with limit, there could be more)"); _logger.debug("moving data to mongo collection: ingest." + data_bucket._id()); final ICrudService<JsonNode> v1_output_db = _underlying_management_db.get() .getUnderlyingPlatformDriver(ICrudService.class, Optional.of("ingest." + data_bucket._id())) .get(); List<JsonNode> objects_to_store = new ArrayList<JsonNode>(); results.forEach(objects_to_store::add); return objects_to_store.isEmpty() ? CompletableFuture.completedFuture(true) : v1_output_db.deleteDatastore() // (should have already been deleted at test startup _and_ on completion, so this is to be on the safe side!) .thenCompose(__ -> v1_output_db.storeObjects(objects_to_store) .thenCompose(x -> CompletableFuture.completedFuture(true))); }).thenCompose(x -> { _logger.debug("Marking job completed"); //do final step for exists/not exists final String output_collection = data_bucket._id(); //mark job as complete, point to v1 collection return updateTestSourceStatus(test_source._id(), TestStatus.completed, source_test_db, Optional.empty(), Optional.ofNullable(output_collection), Optional.empty()); }).exceptionally(t -> { _logger.debug("Marking job completed with error"); return updateTestSourceStatus(test_source._id(), TestStatus.error, source_test_db, Optional.empty(), Optional.empty(), Optional.of(ErrorUtils.getLongForm("error: {0}", t))).join(); }); }
From source file:io.pravega.controller.store.stream.InMemoryStream.java
@Override CompletableFuture<Void> createCompletedTxEntry(UUID txId, TxnStatus complete, long timestamp) { Preconditions.checkNotNull(txId);/*from w w w. j a v a 2 s . c om*/ synchronized (txnsLock) { completedTxns.putIfAbsent(txId.toString(), new Data<>(new CompletedTxnRecord(timestamp, complete).toByteArray(), 0)); } return CompletableFuture.completedFuture(null); }
From source file:io.pravega.controller.store.stream.InMemoryStream.java
@Override CompletableFuture<Void> createMarkerData(int segmentNumber, long timestamp) { byte[] b = new byte[Long.BYTES]; BitConverter.writeLong(b, 0, timestamp); synchronized (markersLock) { markers.putIfAbsent(segmentNumber, new Data<>(b, 0)); }// www . j ava 2 s . c om return CompletableFuture.completedFuture(null); }
From source file:org.glassfish.jersey.apache.connector.ApacheConnector.java
@Override public Future<?> apply(final ClientRequest request, final AsyncConnectorCallback callback) { try {// ww w. j a v a2s. c o m ClientResponse response = apply(request); callback.response(response); return CompletableFuture.completedFuture(response); } catch (Throwable t) { callback.failure(t); CompletableFuture<Object> future = new CompletableFuture<>(); future.completeExceptionally(t); return future; } }
From source file:com.ikanow.aleph2.shared.crud.mongodb.services.MongoDbCrudService.java
@Override public CompletableFuture<Boolean> updateObjectBySpec(final QueryComponent<O> unique_spec, final Optional<Boolean> upsert, final UpdateComponent<O> update) { try {//from ww w .j a v a 2 s . c o m final Tuple2<DBObject, DBObject> query_and_meta = MongoDbUtils.convertToMongoQuery(unique_spec); final DBObject update_object = MongoDbUtils.createUpdateObject(update); final WriteResult<O, K> wr = _state.coll.update(query_and_meta._1(), update_object, upsert.orElse(false), false); return CompletableFuture.completedFuture(wr.getN() > 0); } catch (Exception e) { return FutureUtils.<Boolean>returnError(e); } }