List of usage examples for java.util.concurrent CompletableFuture completedFuture
public static <U> CompletableFuture<U> completedFuture(U value)
From source file:com.ikanow.aleph2.management_db.services.DataBucketStatusCrudService.java
/** Tries to distribute a request to listening data import managers to notify their harvesters that the bucket state has been updated * @param update_reply - the future reply to the find-and-update * @param suspended_predicate - takes the status bean (must exist at this point) and checks whether the bucket should be suspended * @param underlying_data_bucket_db - the data bucket bean db store * @param actor_context - actor context for distributing out requests * @param retry_store - the retry store for handling data import manager connectivity problems * @return a collection of success/error messages from either this function or the *//*from w ww . ja v a 2 s. c o m*/ private static <T> CompletableFuture<Collection<BasicMessageBean>> getOperationFuture( final CompletableFuture<Optional<DataBucketStatusBean>> update_reply, final Predicate<DataBucketStatusBean> suspended_predicate, final ICrudService<DataBucketBean> underlying_data_bucket_db, final ICrudService<DataBucketStatusBean> underlying_data_bucket_status_db, final ManagementDbActorContext actor_context, final ICrudService<BucketActionRetryMessage> retry_store) { return update_reply.thenCompose(sb -> { return sb.isPresent() ? underlying_data_bucket_db.getObjectById(sb.get()._id()) : CompletableFuture.completedFuture(Optional.empty()); }).thenCompose(bucket -> { if (!bucket.isPresent()) { return CompletableFuture.completedFuture(Arrays.asList(new BasicMessageBean(new Date(), // date false, // success IManagementDbService.CORE_MANAGEMENT_DB.get(), BucketActionMessage.UpdateBucketActionMessage.class.getSimpleName(), null, // message code ErrorUtils.get(ManagementDbErrorUtils.MISSING_STATUS_BEAN_OR_BUCKET, update_reply.join().map(s -> s._id()).orElse("(unknown)")), null) // details )); } else { // If we're here we've retrieved both the bucket and bucket status, so we're good to go final DataBucketStatusBean status_bean = update_reply.join().get(); // (as above, if we're here then must exist) // Once we have the bucket, issue the update command final BucketActionMessage.UpdateBucketActionMessage update_message = new BucketActionMessage.UpdateBucketActionMessage( bucket.get(), suspended_predicate.test(status_bean), // (ie user picks whether to suspend or unsuspend here) bucket.get(), new HashSet<String>( Optional.ofNullable(status_bean.node_affinity()).orElse(Collections.emptyList()))); // Collect message and handle retries final CompletableFuture<Collection<BasicMessageBean>> management_results = MgmtCrudUtils .applyRetriableManagementOperation(bucket.get(), actor_context, retry_store, update_message, source -> { return new BucketActionMessage.UpdateBucketActionMessage( update_message.bucket(), status_bean.suspended(), update_message.bucket(), new HashSet<String>(Arrays.asList(source))); }); return MgmtCrudUtils.handleUpdatingStatus(bucket.get(), status_bean, suspended_predicate.test(status_bean), management_results, underlying_data_bucket_status_db); } }); }
From source file:com.ikanow.aleph2.core.shared.services.TestMultiDataService.java
/** * @param mode: 0 => no data service provider (or no writable), 1 => no batch provider * @return//from w ww . j av a2 s . c o m */ public MockServiceContext getPopulatedServiceContext(int mode) { MockServiceContext mock_service_context = new MockServiceContext(); final SearchIndexAndMoreService search_index = Mockito.mock(SearchIndexAndMoreService.class); final IDocumentService document = Mockito.mock(IDocumentService.class); final IColumnarService columnar = Mockito.mock(IColumnarService.class); final ITemporalService temporal = Mockito.mock(ITemporalService.class); final IDataWarehouseService data_warehouse = Mockito.mock(IDataWarehouseService.class); final IGraphService graph = Mockito.mock(IGraphService.class); final IStorageService storage = Mockito.mock(IStorageService.class); Stream.<IDataServiceProvider>of(search_index, document, columnar, temporal, data_warehouse, graph, storage) .forEach(ds -> { if (0 == mode) { boolean tiebreak = 0 == (ds.getClass().toString().hashCode() % 2); //(get some code coverage) if (tiebreak) { Mockito.when(ds.getDataService()).thenReturn(Optional.empty()); } else { final IGenericDataService gds = Mockito.mock(IGenericDataService.class); Mockito.when(gds.getWritableDataService(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any())).thenReturn(Optional.empty()); Mockito.when(ds.getDataService()).thenReturn(Optional.of(gds)); } } else if (1 == mode) { // use slow write mode @SuppressWarnings("unchecked") final IDataWriteService<JsonNode> dws = (IDataWriteService<JsonNode>) Mockito .mock(IDataWriteService.class); Mockito.when(dws.getBatchWriteSubservice()).thenReturn(Optional.empty()); final Answer<Object> callback = new Answer<Object>() { public Object answer(InvocationOnMock invocation) { _crud_responses.compute(ds.getClass().toString(), (k, v) -> (null == v) ? 1 : v + 1); return (Object) CompletableFuture.completedFuture(Unit.unit()); } }; Mockito.when(dws.storeObject(Mockito.any())).then(callback); Mockito.when(dws.storeObject(Mockito.any(), Mockito.anyBoolean())).then(callback); final IGenericDataService gds = Mockito.mock(IGenericDataService.class); Mockito.when(gds.getWritableDataService(Mockito.<Class<JsonNode>>any(), Mockito.any(), Mockito.any(), Mockito.any())).thenReturn(Optional.of(dws)); Mockito.when(ds.getDataService()).thenReturn(Optional.of(gds)); } else { //full mapper @SuppressWarnings("unchecked") final IBatchSubservice<JsonNode> bss = Mockito.mock(IBatchSubservice.class); final Answer<Object> callback = new Answer<Object>() { public Object answer(InvocationOnMock invocation) { _batch_responses.compute(ds.getClass().toString(), (k, v) -> (null == v) ? 1 : v + 1); return (Object) CompletableFuture.completedFuture(Unit.unit()); } }; Mockito.doAnswer(callback).when(bss).flushOutput(); Mockito.doAnswer(callback).when(bss).storeObject(Mockito.any()); Mockito.doAnswer(callback).when(bss).storeObject(Mockito.any(), Mockito.anyBoolean()); @SuppressWarnings("unchecked") final IDataWriteService<JsonNode> dws = (IDataWriteService<JsonNode>) Mockito .mock(IDataWriteService.class); Mockito.when(dws.getBatchWriteSubservice()).thenReturn(Optional.of(bss)); final IGenericDataService gds = Mockito.mock(IGenericDataService.class); Mockito.when(gds.getWritableDataService(Mockito.<Class<JsonNode>>any(), Mockito.any(), Mockito.any(), Mockito.any())).thenReturn(Optional.of(dws)); Mockito.when(ds.getDataService()).thenReturn(Optional.of(gds)); } }); ; mock_service_context.addService(ISearchIndexService.class, Optional.empty(), search_index); // Defaults: mock_service_context.addService(IDocumentService.class, Optional.empty(), search_index); mock_service_context.addService(IColumnarService.class, Optional.empty(), search_index); mock_service_context.addService(ITemporalService.class, Optional.empty(), search_index); mock_service_context.addService(IDataWarehouseService.class, Optional.empty(), data_warehouse); mock_service_context.addService(IStorageService.class, Optional.empty(), storage); mock_service_context.addService(IGraphService.class, Optional.empty(), graph); // Alts: mock_service_context.addService(IDocumentService.class, Optional.of("test"), document); mock_service_context.addService(IColumnarService.class, Optional.of("test"), columnar); mock_service_context.addService(ITemporalService.class, Optional.of("test"), temporal); mock_service_context.addService(IDataWarehouseService.class, Optional.of("test"), data_warehouse); mock_service_context.addService(IGraphService.class, Optional.of("test"), graph); return mock_service_context; }
From source file:io.pravega.controller.store.stream.PersistentStreamBase.java
@Override public CompletableFuture<SimpleEntry<TxnStatus, Integer>> sealTransaction(final UUID txId, final boolean commit, final Optional<Integer> version) { val legal = verifyLegalState(); return legal//from w w w. j a va 2s .co m .thenCompose(v -> getTransactionEpoch(txId) .thenCompose(epoch -> sealActiveTxn(epoch, txId, commit, version)) .exceptionally(ex -> new SimpleEntry<>(handleDataNotFoundException(ex), null))) .thenCompose(pair -> { if (pair.getKey() == TxnStatus.UNKNOWN) { return validateCompletedTxn(txId, commit, "seal") .thenApply(status -> new SimpleEntry<>(status, null)); } else { return CompletableFuture.completedFuture(pair); } }); }
From source file:io.pravega.service.server.containers.StreamSegmentMapperTests.java
private void setupOperationLog(TestContext context) { AtomicLong seqNo = new AtomicLong(); context.operationLog.addHandler = op -> { if (op instanceof StreamSegmentMapOperation) { StreamSegmentMapOperation mapOp = (StreamSegmentMapOperation) op; mapOp.setStreamSegmentId(seqNo.incrementAndGet()); UpdateableSegmentMetadata segmentMetadata = context.metadata .mapStreamSegmentId(mapOp.getStreamSegmentName(), mapOp.getStreamSegmentId()); segmentMetadata.setStorageLength(0); segmentMetadata.setDurableLogLength(mapOp.getLength()); if (mapOp.isSealed()) { segmentMetadata.markSealed(); }//from w ww.j ava 2 s . co m segmentMetadata.updateAttributes(mapOp.getAttributes()); } else if (op instanceof TransactionMapOperation) { TransactionMapOperation mapOp = (TransactionMapOperation) op; mapOp.setStreamSegmentId(seqNo.incrementAndGet()); UpdateableSegmentMetadata segmentMetadata = context.metadata.mapStreamSegmentId( mapOp.getStreamSegmentName(), mapOp.getStreamSegmentId(), mapOp.getParentStreamSegmentId()); segmentMetadata.setStorageLength(0); segmentMetadata.setDurableLogLength(mapOp.getLength()); if (mapOp.isSealed()) { segmentMetadata.markSealed(); } segmentMetadata.updateAttributes(mapOp.getAttributes()); } return CompletableFuture.completedFuture(seqNo.incrementAndGet()); }; }
From source file:com.ikanow.aleph2.shared.crud.mongodb.services.MongoDbCrudService.java
public CompletableFuture<Boolean> deleteDatastore() { try {//from w ww. java 2 s . co m // Fongo has some issues with dropping and multiple instances if (_state.orig_coll instanceof FongoDBCollection) { _state.coll.remove(new BasicDBObject()); _state.coll.dropIndexes(); } else { _state.orig_coll.drop(); } return CompletableFuture.completedFuture((Boolean) (true)); } catch (Exception e) { return FutureUtils.<Boolean>returnError(e); } }
From source file:io.atomix.cluster.messaging.impl.NettyMessagingService.java
@Override public CompletableFuture<Void> stop() { if (started.compareAndSet(true, false)) { return CompletableFuture.supplyAsync(() -> { boolean interrupted = false; try { try { serverChannel.close().sync(); } catch (InterruptedException e) { interrupted = true;//w w w.j av a 2 s. com } Future<?> serverShutdownFuture = serverGroup.shutdownGracefully(); Future<?> clientShutdownFuture = clientGroup.shutdownGracefully(); try { serverShutdownFuture.sync(); } catch (InterruptedException e) { interrupted = true; } try { clientShutdownFuture.sync(); } catch (InterruptedException e) { interrupted = true; } timeoutFuture.cancel(false); timeoutExecutor.shutdown(); } finally { log.info("Stopped"); if (interrupted) { Thread.currentThread().interrupt(); } } return null; }); } return CompletableFuture.completedFuture(null); }
From source file:io.pravega.segmentstore.server.containers.StreamSegmentMapperTests.java
private void setupOperationLog(TestContext context) { AtomicLong seqNo = new AtomicLong(); context.operationLog.addHandler = op -> { long currentSeqNo = seqNo.incrementAndGet(); if (op instanceof StreamSegmentMapOperation) { StreamSegmentMapOperation mapOp = (StreamSegmentMapOperation) op; if (mapOp.getStreamSegmentId() == ContainerMetadata.NO_STREAM_SEGMENT_ID) { mapOp.setStreamSegmentId(currentSeqNo); }/*w w w .jav a2s. c o m*/ UpdateableSegmentMetadata segmentMetadata = context.metadata .mapStreamSegmentId(mapOp.getStreamSegmentName(), mapOp.getStreamSegmentId()); segmentMetadata.setStorageLength(0); segmentMetadata.setDurableLogLength(mapOp.getLength()); if (mapOp.isSealed()) { segmentMetadata.markSealed(); } segmentMetadata.updateAttributes(mapOp.getAttributes()); } else if (op instanceof TransactionMapOperation) { TransactionMapOperation mapOp = (TransactionMapOperation) op; if (mapOp.getStreamSegmentId() == ContainerMetadata.NO_STREAM_SEGMENT_ID) { mapOp.setStreamSegmentId(currentSeqNo); } UpdateableSegmentMetadata segmentMetadata = context.metadata.mapStreamSegmentId( mapOp.getStreamSegmentName(), mapOp.getStreamSegmentId(), mapOp.getParentStreamSegmentId()); segmentMetadata.setStorageLength(0); segmentMetadata.setDurableLogLength(mapOp.getLength()); if (mapOp.isSealed()) { segmentMetadata.markSealed(); } segmentMetadata.updateAttributes(mapOp.getAttributes()); } return CompletableFuture.completedFuture(currentSeqNo); }; }
From source file:io.pravega.controller.store.stream.PersistentStreamBase.java
/** * Seal a transaction in OPEN/COMMITTING/ABORTING state. This method does CAS on the transaction data node if * the transaction is in OPEN state, optionally checking version of transaction data node, if required. * * @param epoch transaction epoch.//from w ww . j a va 2s .c o m * @param txId transaction identifier. * @param commit boolean indicating whether to commit or abort the transaction. * @param version optional expected version of transaction node to validate before updating it. * @return a pair containing transaction status and its epoch. */ private CompletableFuture<SimpleEntry<TxnStatus, Integer>> sealActiveTxn(final int epoch, final UUID txId, final boolean commit, final Optional<Integer> version) { return getActiveTx(epoch, txId).thenCompose(data -> { ActiveTxnRecord txnRecord = ActiveTxnRecord.parse(data.getData()); int dataVersion = version.isPresent() ? version.get() : data.getVersion(); TxnStatus status = txnRecord.getTxnStatus(); switch (status) { case OPEN: return sealActiveTx(epoch, txId, commit, txnRecord, dataVersion).thenApply( y -> new SimpleEntry<>(commit ? TxnStatus.COMMITTING : TxnStatus.ABORTING, epoch)); case COMMITTING: case COMMITTED: if (commit) { return CompletableFuture.completedFuture(new SimpleEntry<>(status, epoch)); } else { throw StoreException.create(StoreException.Type.ILLEGAL_STATE, "Stream: " + getName() + " Transaction: " + txId.toString() + " State: " + status.name()); } case ABORTING: case ABORTED: if (commit) { throw StoreException.create(StoreException.Type.ILLEGAL_STATE, "Stream: " + getName() + " Transaction: " + txId.toString() + " State: " + status.name()); } else { return CompletableFuture.completedFuture(new SimpleEntry<>(status, epoch)); } default: throw StoreException.create(StoreException.Type.DATA_NOT_FOUND, "Stream: " + getName() + " Transaction: " + txId.toString()); } }); }
From source file:com.ikanow.aleph2.management_db.services.DataBucketCrudService.java
/** Internal function to delete the bucket, while notifying active users of the bucket * @param to_delete/*from ww w . j ava 2s . c o m*/ * @return a management future containing the result */ private ManagementFuture<Boolean> deleteBucket(final DataBucketBean to_delete) { try { // Also delete the file paths (currently, just add ".deleted" to top level path) deleteFilePath(to_delete, _storage_service.get()); //delete the logging path as well if it exists (it's okay if it fails, should mean it doesn't exist) try { deleteFilePath(BucketUtils.convertDataBucketBeanToLogging(to_delete), _storage_service.get()); } catch (Exception ex) { } // Add to the deletion queue (do it before trying to delete the bucket in case this bucket deletion fails - if so then delete queue will retry every hour) final Date to_delete_date = Timestamp.from(Instant.now().plus(1L, ChronoUnit.MINUTES)); final CompletableFuture<Supplier<Object>> enqueue_delete = this._bucket_deletion_queue.get() .storeObject(new BucketDeletionMessage(to_delete, to_delete_date, false)); final CompletableFuture<Boolean> delete_reply = enqueue_delete .thenCompose(__ -> _underlying_data_bucket_db.get().deleteObjectById(to_delete._id())); return FutureUtils.denestManagementFuture(delete_reply.thenCompose(del_reply -> { if (!del_reply) { // Didn't find an object to delete, just return that information to the user return CompletableFuture.completedFuture(Optional.empty()); } else { //Get the status and delete it final CompletableFuture<Optional<DataBucketStatusBean>> future_status_bean = _underlying_data_bucket_status_db .get().updateAndReturnObjectBySpec( CrudUtils.allOf(DataBucketStatusBean.class).when(DataBucketStatusBean::_id, to_delete._id()), Optional.empty(), CrudUtils.update(DataBucketStatusBean.class).deleteObject(), Optional.of(true), Collections.emptyList(), false); return future_status_bean; } }).thenApply(status_bean -> { if (!status_bean.isPresent()) { return FutureUtils.createManagementFuture(delete_reply); } else { final BucketActionMessage.DeleteBucketActionMessage delete_message = new BucketActionMessage.DeleteBucketActionMessage( to_delete, new HashSet<String>(Optional .ofNullable(status_bean.isPresent() ? status_bean.get().node_affinity() : null) .orElse(Collections.emptyList()))); final CompletableFuture<Collection<BasicMessageBean>> management_results = MgmtCrudUtils .applyRetriableManagementOperation(to_delete, _actor_context, _bucket_action_retry_store.get(), delete_message, source -> { return new BucketActionMessage.DeleteBucketActionMessage( delete_message.bucket(), new HashSet<String>(Arrays.asList(source))); }); // Convert BucketActionCollectedRepliesMessage into a management side-channel: return FutureUtils.createManagementFuture(delete_reply, management_results); } })); } catch (Exception e) { // This is a serious enough exception that we'll just leave here return FutureUtils.createManagementFuture(FutureUtils.returnError(e)); } }
From source file:io.pravega.segmentstore.server.containers.StreamSegmentMapperTests.java
private void setupStorageCreateHandler(TestContext context, HashSet<String> storageSegments) { context.storage.createHandler = segmentName -> { synchronized (storageSegments) { if (storageSegments.contains(segmentName)) { return FutureHelpers.failedFuture(new StreamSegmentExistsException(segmentName)); } else { storageSegments.add(segmentName); return CompletableFuture.completedFuture( new StreamSegmentInformation(segmentName, 0, false, false, new ImmutableDate())); }/*from ww w . j a v a 2 s. c om*/ } }; }