List of usage examples for java.util.concurrent CompletableFuture complete
public boolean complete(T value)
From source file:org.apache.pulsar.functions.runtime.ProcessRuntime.java
@Override public CompletableFuture<FunctionStatus> getFunctionStatus(int instanceId) { CompletableFuture<FunctionStatus> retval = new CompletableFuture<>(); if (stub == null) { retval.completeExceptionally(new RuntimeException("Not alive")); return retval; }/*from w w w. j ava 2 s . c om*/ ListenableFuture<FunctionStatus> response = stub.withDeadlineAfter(GRPC_TIMEOUT_SECS, TimeUnit.SECONDS) .getFunctionStatus(Empty.newBuilder().build()); Futures.addCallback(response, new FutureCallback<FunctionStatus>() { @Override public void onFailure(Throwable throwable) { FunctionStatus.Builder builder = FunctionStatus.newBuilder(); builder.setRunning(false); if (deathException != null) { builder.setFailureException(deathException.getMessage()); } else { builder.setFailureException(throwable.getMessage()); } retval.complete(builder.build()); } @Override public void onSuccess(InstanceCommunication.FunctionStatus t) { retval.complete(t); } }); return retval; }
From source file:io.pravega.controller.server.SegmentHelper.java
public CompletableFuture<TxnStatus> commitTransaction(final String scope, final String stream, final int segmentNumber, final UUID txId, final HostControllerStore hostControllerStore, final ConnectionFactory clientCF) { final Controller.NodeUri uri = getSegmentUri(scope, stream, segmentNumber, hostControllerStore); final CompletableFuture<TxnStatus> result = new CompletableFuture<>(); final WireCommandType type = WireCommandType.COMMIT_TRANSACTION; final FailingReplyProcessor replyProcessor = new FailingReplyProcessor() { @Override/*from w w w . ja v a2 s . c om*/ public void connectionDropped() { result.completeExceptionally( new WireCommandFailedException(type, WireCommandFailedException.Reason.ConnectionDropped)); } @Override public void wrongHost(WireCommands.WrongHost wrongHost) { result.completeExceptionally( new WireCommandFailedException(type, WireCommandFailedException.Reason.UnknownHost)); } @Override public void transactionCommitted(WireCommands.TransactionCommitted transactionCommitted) { result.complete(TxnStatus.newBuilder().setStatus(TxnStatus.Status.SUCCESS).build()); } @Override public void transactionAborted(WireCommands.TransactionAborted transactionAborted) { result.completeExceptionally( new WireCommandFailedException(type, WireCommandFailedException.Reason.PreconditionFailed)); } @Override public void processingFailure(Exception error) { result.completeExceptionally(error); } }; WireCommands.CommitTransaction request = new WireCommands.CommitTransaction(idGenerator.get(), Segment.getScopedName(scope, stream, segmentNumber), txId); sendRequestAsync(request, replyProcessor, result, clientCF, ModelHelper.encode(uri)); return result; }
From source file:org.apache.pulsar.broker.authorization.PulsarAuthorizationProvider.java
public CompletableFuture<Boolean> checkPermission(TopicName topicName, String role, AuthAction action) { CompletableFuture<Boolean> permissionFuture = new CompletableFuture<>(); try {/*from w w w.j av a 2s. c o m*/ configCache.policiesCache().getAsync(POLICY_ROOT + topicName.getNamespace()).thenAccept(policies -> { if (!policies.isPresent()) { if (log.isDebugEnabled()) { log.debug("Policies node couldn't be found for topic : {}", topicName); } } else { Map<String, Set<AuthAction>> namespaceRoles = policies.get().auth_policies.namespace_auth; Set<AuthAction> namespaceActions = namespaceRoles.get(role); if (namespaceActions != null && namespaceActions.contains(action)) { // The role has namespace level permission permissionFuture.complete(true); return; } Map<String, Set<AuthAction>> topicRoles = policies.get().auth_policies.destination_auth .get(topicName.toString()); if (topicRoles != null) { // Topic has custom policy Set<AuthAction> topicActions = topicRoles.get(role); if (topicActions != null && topicActions.contains(action)) { // The role has topic level permission permissionFuture.complete(true); return; } } // Using wildcard if (conf.isAuthorizationAllowWildcardsMatching()) { if (checkWildcardPermission(role, action, namespaceRoles)) { // The role has namespace level permission by wildcard match permissionFuture.complete(true); return; } if (topicRoles != null && checkWildcardPermission(role, action, topicRoles)) { // The role has topic level permission by wildcard match permissionFuture.complete(true); return; } } } permissionFuture.complete(false); }).exceptionally(ex -> { log.warn("Client with Role - {} failed to get permissions for topic - {}. {}", role, topicName, ex.getMessage()); permissionFuture.completeExceptionally(ex); return null; }); } catch (Exception e) { log.warn("Client with Role - {} failed to get permissions for topic - {}. {}", role, topicName, e.getMessage()); permissionFuture.completeExceptionally(e); } return permissionFuture; }
From source file:com.yahoo.pulsar.client.impl.PulsarClientImpl.java
@Override public CompletableFuture<Void> closeAsync() { log.info("Client closing. URL: {}", lookup.getServiceUrl()); if (!state.compareAndSet(State.Open, State.Closing)) { return FutureUtil .failedFuture(new PulsarClientException.AlreadyClosedException("Client already closed")); }/* www. j a v a2s . c o m*/ final CompletableFuture<Void> closeFuture = new CompletableFuture<>(); List<CompletableFuture<Void>> futures = Lists.newArrayList(); synchronized (producers) { // Copy to a new list, because the closing will trigger a removal from the map // and invalidate the iterator List<ProducerBase> producersToClose = Lists.newArrayList(producers.keySet()); producersToClose.forEach(p -> futures.add(p.closeAsync())); } synchronized (consumers) { List<ConsumerBase> consumersToClose = Lists.newArrayList(consumers.keySet()); consumersToClose.forEach(c -> futures.add(c.closeAsync())); } FutureUtil.waitForAll(futures).thenRun(() -> { // All producers & consumers are now closed, we can stop the client safely try { shutdown(); closeFuture.complete(null); state.set(State.Closed); } catch (PulsarClientException e) { closeFuture.completeExceptionally(e); } }).exceptionally(exception -> { closeFuture.completeExceptionally(exception); return null; }); return closeFuture; }
From source file:org.apache.pulsar.client.impl.BinaryProtoLookupService.java
private void getTopicsUnderNamespace(InetSocketAddress socketAddress, NamespaceName namespace, Backoff backoff, AtomicLong remainingTime, CompletableFuture<List<String>> topicsFuture, Mode mode) { client.getCnxPool().getConnection(socketAddress).thenAccept(clientCnx -> { long requestId = client.newRequestId(); ByteBuf request = Commands.newGetTopicsOfNamespaceRequest(namespace.toString(), requestId, mode); clientCnx.newGetTopicsOfNamespace(request, requestId).thenAccept(topicsList -> { if (log.isDebugEnabled()) { log.debug("[namespace: {}] Success get topics list in request: {}", namespace.toString(), requestId);/*from ww w .j a v a 2 s. c om*/ } // do not keep partition part of topic name List<String> result = Lists.newArrayList(); topicsList.forEach(topic -> { String filtered = TopicName.get(topic).getPartitionedTopicName(); if (!result.contains(filtered)) { result.add(filtered); } }); topicsFuture.complete(result); }).exceptionally((e) -> { topicsFuture.completeExceptionally(e); return null; }); }).exceptionally((e) -> { long nextDelay = Math.min(backoff.next(), remainingTime.get()); if (nextDelay <= 0) { topicsFuture.completeExceptionally(new PulsarClientException.TimeoutException( "Could not getTopicsUnderNamespace within configured timeout.")); return null; } ((ScheduledExecutorService) executor).schedule(() -> { log.warn( "[namespace: {}] Could not get connection while getTopicsUnderNamespace -- Will try again in {} ms", namespace, nextDelay); remainingTime.addAndGet(-nextDelay); getTopicsUnderNamespace(socketAddress, namespace, backoff, remainingTime, topicsFuture, mode); }, nextDelay, TimeUnit.MILLISECONDS); return null; }); }
From source file:org.onosproject.segmentrouting.pwaas.L2TunnelHandler.java
/** * Deletes a given policy using the parameter supplied. * * @param tunnelId the tunnel id// w w w . ja v a 2 s. co m * @param ingress the ingress point * @param ingressInner the ingress inner vlan id * @param ingressOuter the ingress outer vlan id * @param future to perform the async operation * @param direction the direction: forward or reverse */ private void deletePolicy(long tunnelId, ConnectPoint ingress, VlanId ingressInner, VlanId ingressOuter, CompletableFuture<ObjectiveError> future, Direction direction) { if (!srManager.mastershipService.isLocalMaster(ingress.deviceId())) { log.info("Abort delete of policy for tunnel {}: I am not the master", tunnelId); if (future != null) { future.complete(null); } return; } String key = generateKey(tunnelId, direction); if (!l2InitiationNextObjStore.containsKey(key)) { log.warn("Abort delete of policy for tunnel {}: next does not exist in the store", tunnelId); if (future != null) { future.complete(null); } return; } NextObjective nextObjective = l2InitiationNextObjStore.get(key).value(); int nextId = nextObjective.id(); List<Objective> objectives = Lists.newArrayList(); // We create the forwarding objective. ForwardingObjective.Builder fwdBuilder = createInitFwdObjective(tunnelId, ingress.port(), nextId); ObjectiveContext context = new ObjectiveContext() { @Override public void onSuccess(Objective objective) { log.debug("Previous fwdObj for policy {} removed", tunnelId); if (future != null) { future.complete(null); } } @Override public void onError(Objective objective, ObjectiveError error) { log.warn("Failed to remove previous fwdObj for policy {}: {}", tunnelId, error); if (future != null) { future.complete(error); } } }; objectives.add(fwdBuilder.remove(context)); // We create the filtering objective to define the // permit traffic in the switch FilteringObjective.Builder filtBuilder = createFiltObjective(ingress.port(), ingressInner, ingressOuter); TrafficTreatment.Builder treatment = DefaultTrafficTreatment.builder().setTunnelId(tunnelId); filtBuilder.withMeta(treatment.build()); context = new DefaultObjectiveContext((objective) -> log.debug("FilterObj for policy {} revoked", tunnelId), (objective, error) -> log.warn("Failed to revoke filterObj for policy {}", tunnelId, error)); objectives.add(filtBuilder.remove(context)); for (Objective objective : objectives) { if (objective instanceof ForwardingObjective) { srManager.flowObjectiveService.forward(ingress.deviceId(), (ForwardingObjective) objective); } else { srManager.flowObjectiveService.filter(ingress.deviceId(), (FilteringObjective) objective); } } }
From source file:org.apache.pulsar.client.impl.ClientCnx.java
@Override protected void handleGetSchemaResponse(CommandGetSchemaResponse commandGetSchemaResponse) { checkArgument(state == State.Ready); long requestId = commandGetSchemaResponse.getRequestId(); CompletableFuture<Optional<SchemaInfo>> future = pendingGetSchemaRequests.remove(requestId); if (future == null) { log.warn("{} Received unknown request id from server: {}", ctx.channel(), requestId); return;/*w w w. j a va 2 s . co m*/ } if (commandGetSchemaResponse.hasErrorCode()) { // Request has failed ServerError rc = commandGetSchemaResponse.getErrorCode(); if (rc == ServerError.TopicNotFound) { future.complete(Optional.empty()); } else { future.completeExceptionally( getPulsarClientException(rc, commandGetSchemaResponse.getErrorMessage())); } } else { future.complete(Optional.of(SchemaInfoUtil.newSchemaInfo(commandGetSchemaResponse.getSchema()))); } }
From source file:org.onosproject.p4runtime.ctl.P4RuntimeClientImpl.java
private void doArbitrationUpdateFromDevice(MasterArbitrationUpdate arbitrationMsg) { log.debug("Received arbitration update from {}: {}", deviceId, arbitrationMsg); Uint128 electionId = arbitrationMsg.getElectionId(); CompletableFuture<Boolean> mastershipFeature = arbitrationUpdateMap.remove(electionId); if (mastershipFeature == null) { log.warn("Can't find completable future of election id {}", electionId); return;// www . j av a 2 s .c o m } this.p4RuntimeElectionId = electionId; int statusCode = arbitrationMsg.getStatus().getCode(); MastershipRole arbitrationRole; // arbitration update success if (statusCode == Status.OK.getCode().value()) { mastershipFeature.complete(true); arbitrationRole = MastershipRole.MASTER; } else { mastershipFeature.complete(false); arbitrationRole = MastershipRole.STANDBY; } DefaultArbitration arbitrationEventSubject = new DefaultArbitration(arbitrationRole, electionId); P4RuntimeEvent event = new P4RuntimeEvent(P4RuntimeEvent.Type.ARBITRATION, arbitrationEventSubject); controller.postEvent(event); }
From source file:io.pravega.controller.server.SegmentHelper.java
public CompletableFuture<Boolean> deleteSegment(final String scope, final String stream, final int segmentNumber, final HostControllerStore hostControllerStore, final ConnectionFactory clientCF) { final CompletableFuture<Boolean> result = new CompletableFuture<>(); final Controller.NodeUri uri = getSegmentUri(scope, stream, segmentNumber, hostControllerStore); final WireCommandType type = WireCommandType.DELETE_SEGMENT; final FailingReplyProcessor replyProcessor = new FailingReplyProcessor() { @Override/*ww w . j av a 2 s . c o m*/ public void connectionDropped() { result.completeExceptionally( new WireCommandFailedException(type, WireCommandFailedException.Reason.ConnectionDropped)); } @Override public void wrongHost(WireCommands.WrongHost wrongHost) { result.completeExceptionally( new WireCommandFailedException(type, WireCommandFailedException.Reason.UnknownHost)); } @Override public void noSuchSegment(WireCommands.NoSuchSegment noSuchSegment) { result.complete(true); } @Override public void segmentDeleted(WireCommands.SegmentDeleted segmentDeleted) { result.complete(true); } @Override public void processingFailure(Exception error) { result.completeExceptionally(error); } }; WireCommands.DeleteSegment request = new WireCommands.DeleteSegment(idGenerator.get(), Segment.getScopedName(scope, stream, segmentNumber)); sendRequestAsync(request, replyProcessor, result, clientCF, ModelHelper.encode(uri)); return result; }
From source file:org.onosproject.segmentrouting.pwaas.L2TunnelHandler.java
/** * Deletes the pseudo wire initiation.//from ww w. jav a2s. c om * * @param l2TunnelId the tunnel id * @param ingress the ingress connect point * @param future to perform an async operation * @param direction the direction: reverse of forward */ private void tearDownPseudoWireInit(long l2TunnelId, ConnectPoint ingress, CompletableFuture<ObjectiveError> future, Direction direction) { String key = generateKey(l2TunnelId, direction); if (!srManager.mastershipService.isLocalMaster(ingress.deviceId())) { log.info("Abort delete of {} for {}: I am not the master", INITIATION, key); if (future != null) { future.complete(null); } return; } if (!l2InitiationNextObjStore.containsKey(key)) { log.info("Abort delete of {} for {}: next does not exist in the store", INITIATION, key); if (future != null) { future.complete(null); } return; } NextObjective nextObjective = l2InitiationNextObjStore.get(key).value(); ObjectiveContext context = new ObjectiveContext() { @Override public void onSuccess(Objective objective) { log.debug("Previous {} next for {} removed", INITIATION, key); if (future != null) { future.complete(null); } } @Override public void onError(Objective objective, ObjectiveError error) { log.warn("Failed to remove previous {} next for {}: {}", INITIATION, key, error); if (future != null) { future.complete(error); } } }; srManager.flowObjectiveService.next(ingress.deviceId(), (NextObjective) nextObjective.copy().remove(context)); l2InitiationNextObjStore.remove(key); }