@Test public void failureMonitor() throws Exception { ProducerToken token = ProducerToken.create(SimpleProducerModule_SettableFutureStrFactory.class); SettableFuture<String> strFuture = SettableFuture.create(); SettableFuture<SettableFuture<String>> strFutureFuture = SettableFuture.create(); Producer<SettableFuture<String>> strFutureProducer = producerOfFuture(strFutureFuture); Producer<String> producer = new SimpleProducerModule_SettableFutureStrFactory( executorProvider, componentMonitorProvider, strFutureProducer); assertThat(producer.get().isDone()).isFalse(); InOrder order = inOrder(componentMonitor, monitor); order.verify(componentMonitor).producerMonitorFor(token); strFutureFuture.set(strFuture); order.verify(monitor).methodStarting(); order.verify(monitor).methodFinished(); assertThat(producer.get().isDone()).isFalse(); Throwable t = new RuntimeException("monkey"); strFuture.setException(t); try { producer.get().get(); fail(); } catch (ExecutionException e) { assertThat(e.getCause()).isSameAs(t); order.verify(monitor).failed(t); } order.verifyNoMoreInteractions(); }
/** * Fences a ledger. From this point on, clients will be unable to write to this ledger. Only * recoveryAddEntry will be able to add entries to the ledger. This method is idempotent. Once a * ledger is fenced, it can never be unfenced. Fencing a fenced ledger has no effect. */ public SettableFuture<Boolean> fenceLedger(long ledgerId, byte[] masterKey) throws IOException, BookieException { LedgerDescriptor handle = handles.getHandle(ledgerId, masterKey); boolean success; synchronized (handle) { success = handle.setFenced(); } if (success) { // fenced first time, we should add the key to journal ensure we can rebuild ByteBuffer bb = ByteBuffer.allocate(8 + 8); bb.putLong(ledgerId); bb.putLong(METAENTRY_ID_FENCE_KEY); bb.flip(); FutureWriteCallback fwc = new FutureWriteCallback(); LOG.debug("record fenced state for ledger {} in journal.", ledgerId); journal.logAddEntry(bb, fwc, null); return fwc.getResult(); } else { // already fenced SettableFuture<Boolean> successFuture = SettableFuture.create(); successFuture.set(true); return successFuture; } }
@Test public void successMonitor() throws Exception { ProducerToken token = ProducerToken.create(SimpleProducerModule_SettableFutureStrFactory.class); SettableFuture<String> strFuture = SettableFuture.create(); SettableFuture<SettableFuture<String>> strFutureFuture = SettableFuture.create(); Producer<SettableFuture<String>> strFutureProducer = producerOfFuture(strFutureFuture); Producer<String> producer = new SimpleProducerModule_SettableFutureStrFactory( executorProvider, componentMonitorProvider, strFutureProducer); assertThat(producer.get().isDone()).isFalse(); InOrder order = inOrder(componentMonitor, monitor); order.verify(componentMonitor).producerMonitorFor(token); strFutureFuture.set(strFuture); order.verify(monitor).methodStarting(); order.verify(monitor).methodFinished(); assertThat(producer.get().isDone()).isFalse(); strFuture.set("monkey"); assertThat(producer.get().get()).isEqualTo("monkey"); order.verify(monitor).succeeded("monkey"); order.verifyNoMoreInteractions(); }
private void doWalk( Path path, FileStatusCallback callback, AtomicLong taskCount, SettableFuture<Void> future) { try (SetThreadName ignored = new SetThreadName("HiveHdfsWalker")) { RemoteIterator<LocatedFileStatus> iterator = getLocatedFileStatusRemoteIterator(path); while (iterator.hasNext()) { LocatedFileStatus status = getLocatedFileStatus(iterator); // ignore hidden files. Hive ignores files starting with _ and . as well. String fileName = status.getPath().getName(); if (fileName.startsWith("_") || fileName.startsWith(".")) { continue; } if (isDirectory(status)) { recursiveWalk(status.getPath(), callback, taskCount, future); } else { callback.process(status, status.getBlockLocations()); } if (future.isDone()) { return; } } } catch (FileNotFoundException e) { future.setException(new FileNotFoundException("Partition location does not exist: " + path)); } catch (Throwable t) { future.setException(t); } finally { if (taskCount.decrementAndGet() == 0) { future.set(null); } } }
@Test public void disconnectOldVersions1() throws Exception { // Set up the connection with an old version. final SettableFuture<Void> connectedFuture = SettableFuture.create(); final SettableFuture<Void> disconnectedFuture = SettableFuture.create(); peer.addEventListener( new AbstractPeerEventListener() { @Override public void onPeerConnected(Peer peer, int peerCount) { connectedFuture.set(null); } @Override public void onPeerDisconnected(Peer peer, int peerCount) { disconnectedFuture.set(null); } }); connectWithVersion(500); // We must wait uninterruptibly here because connect[WithVersion] generates a peer that // interrupts the current // thread when it disconnects. Uninterruptibles.getUninterruptibly(connectedFuture); Uninterruptibles.getUninterruptibly(disconnectedFuture); try { peer.writeTarget.writeBytes(new byte[1]); fail(); } catch (IOException e) { assertTrue( (e.getCause() != null && e.getCause() instanceof CancelledKeyException) || (e instanceof SocketException && e.getMessage().equals("Socket is closed"))); } }
/** * Synchronously sends an opaque message to the RpcHandler on the server-side, waiting for up to a * specified timeout for a response. */ public ByteBuffer sendRpcSync(ByteBuffer message, long timeoutMs) { final SettableFuture<ByteBuffer> result = SettableFuture.create(); sendRpc( message, new RpcResponseCallback() { @Override public void onSuccess(ByteBuffer response) { result.set(response); } @Override public void onFailure(Throwable e) { result.setException(e); } }); try { return result.get(timeoutMs, TimeUnit.MILLISECONDS); } catch (ExecutionException e) { throw Throwables.propagate(e.getCause()); } catch (Exception e) { throw Throwables.propagate(e); } }
private void outboundPingAndWait(final InboundMessageQueuer p, long nonce) throws Exception { // Send a ping and wait for it to get to the other side SettableFuture<Void> pingReceivedFuture = SettableFuture.create(); p.mapPingFutures.put(nonce, pingReceivedFuture); p.peer.sendMessage(new Ping(nonce)); pingReceivedFuture.get(); p.mapPingFutures.remove(nonce); }
/** * Start the instance using the ports provided * * @param localPort the local port to expose * @param remoteHost the hostname of the remote server to connect to * @param remotePort the port of the remote server to connect to */ public DirectProxy(final Integer localPort, final String remoteHost, final Integer remotePort) { if (localPort == null) { throw new IllegalArgumentException("You must specify a local port"); } if (remoteHost == null) { throw new IllegalArgumentException("You must specify a remote port"); } if (remotePort == null) { throw new IllegalArgumentException("You must specify a remote hostname"); } hasStarted = SettableFuture.create(); new Thread( new Runnable() { @Override public void run() { try { remoteSocket = new InetSocketAddress(remoteHost, remotePort); channel = new ServerBootstrap() .group(bossGroup, workerGroup) .option(ChannelOption.SO_BACKLOG, 1024) .channel(NioServerSocketChannel.class) .childOption(ChannelOption.AUTO_READ, true) .childHandler(new DirectProxyUnificationHandler()) .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT) .childAttr(HTTP_PROXY, DirectProxy.this) .childAttr(REMOTE_SOCKET, remoteSocket) .childAttr(LOG_FILTER, logFilter) .bind(localPort) .sync() .channel(); logger.info( "MockServer proxy started on port: {} connected to remote server: {}", ((InetSocketAddress) channel.localAddress()).getPort(), remoteHost + ":" + remotePort); hasStarted.set("STARTED"); channel.closeFuture().sync(); } catch (InterruptedException ie) { logger.error("MockServer proxy receive InterruptedException", ie); } finally { bossGroup.shutdownGracefully(0, 1, TimeUnit.MILLISECONDS); workerGroup.shutdownGracefully(0, 1, TimeUnit.MILLISECONDS); } } }) .start(); try { hasStarted.get(); } catch (Exception e) { logger.warn("Exception while waiting for MockServer proxy to complete starting up", e); } }
@Test public void singleArgMethod() throws Exception { SettableFuture<Integer> intFuture = SettableFuture.create(); Producer<Integer> intProducer = producerOfFuture(intFuture); Producer<String> producer = new SimpleProducerModule_StrWithArgFactory( executorProvider, componentMonitorProvider, intProducer); assertThat(producer.get().isDone()).isFalse(); intFuture.set(42); assertThat(producer.get().get()).isEqualTo("str with arg"); }
@Override protected void processMessage(Message m) throws Exception { if (m instanceof Ping) { SettableFuture<Void> future = mapPingFutures.get(((Ping) m).getNonce()); if (future != null) { future.set(null); return; } } if (m instanceof BloomFilter) { lastReceivedFilter = (BloomFilter) m; } inboundMessages.offer(m); }
@Override public ListenableFuture<Boolean> consumeAsync() { // TODO make this actually asynch final SettableFuture<Boolean> result = SettableFuture.create(); try { consume(); result.set(true); } catch (final Exception e) { LOGGER.warn("Got exception consuming RDF stream", e); result.setException(e); result.set(false); } return result; }
@Test public void contextAlreadyCancelledNotifiesImmediately() throws Exception { // Attach the context which is recorded when the call is created Context.CancellableContext cancellableContext = Context.current().withCancellation(); Throwable cause = new Throwable(); cancellableContext.cancel(cause); Context previous = cancellableContext.attach(); ClientCallImpl<Void, Void> call = new ClientCallImpl<Void, Void>( DESCRIPTOR, new SerializingExecutor(Executors.newSingleThreadExecutor()), CallOptions.DEFAULT, provider, deadlineCancellationExecutor) .setDecompressorRegistry(decompressorRegistry); previous.attach(); final SettableFuture<Status> statusFuture = SettableFuture.create(); call.start( new ClientCall.Listener<Void>() { @Override public void onClose(Status status, Metadata trailers) { statusFuture.set(status); } }, new Metadata()); // Caller should receive onClose callback. Status status = statusFuture.get(5, TimeUnit.SECONDS); assertEquals(Status.Code.CANCELLED, status.getCode()); assertSame(cause, status.getCause()); // Following operations should be no-op. call.request(1); call.sendMessage(null); call.halfClose(); // Stream should never be created. verifyZeroInteractions(transport); try { call.sendMessage(null); fail("Call has been cancelled"); } catch (IllegalStateException ise) { // expected } }
/** * Reserves the given number of bytes. Caller should wait on the returned future, before * allocating more memory. */ public synchronized ListenableFuture<?> reserve(QueryId queryId, long bytes) { checkArgument(bytes >= 0, "bytes is negative"); if (bytes != 0) { queryMemoryReservations.merge(queryId, bytes, Long::sum); } freeBytes -= bytes; if (freeBytes <= 0) { if (future == null) { future = SettableFuture.create(); } checkState(!future.isDone(), "future is already completed"); return future; } return NOT_BLOCKED; }
@Override public ListenableFuture<List<MessageStatus>> list(Folder folder, int start, int end) { Preconditions.checkState( mailClientHandler.isLoggedIn(), "Can't execute command because client is not logged in"); Preconditions.checkState( !mailClientHandler.idleRequested.get(), "Can't execute command while idling (are you watching a folder?)"); checkCurrentFolder(folder); checkRange(start, end); Preconditions.checkArgument( start > 0, "Start must be greater than zero (IMAP uses 1-based " + "indexing)"); SettableFuture<List<MessageStatus>> valueFuture = SettableFuture.create(); // -ve end range means get everything (*). String extensions = config.useGmailExtensions() ? " X-GM-MSGID X-GM-THRID X-GM-LABELS UID" : ""; String args = start + ":" + toUpperBound(end) + " (RFC822.SIZE INTERNALDATE FLAGS ENVELOPE" + extensions + ")"; send(Command.FETCH_HEADERS, args, valueFuture); return valueFuture; }
@Override public ListenableFuture<List<MessageStatus>> listUidThin( Folder folder, List<Sequence> sequences) { Preconditions.checkState( mailClientHandler.isLoggedIn(), "Can't execute command because client is not logged in"); Preconditions.checkState( !mailClientHandler.idleRequested.get(), "Can't execute command while idling (are you watching a folder?)"); checkCurrentFolder(folder); SettableFuture<List<MessageStatus>> valueFuture = SettableFuture.create(); // -ve end range means get everything (*). String extensions = config.useGmailExtensions() ? " X-GM-MSGID X-GM-THRID X-GM-LABELS UID" : ""; StringBuilder argsBuilder = new StringBuilder(); // Emit ranges. for (int i = 0, sequencesSize = sequences.size(); i < sequencesSize; i++) { Sequence seq = sequences.get(i); argsBuilder.append(toUpperBound(seq.start)); if (seq.end != 0) argsBuilder.append(':').append(toUpperBound(seq.end)); if (i < sequencesSize - 1) argsBuilder.append(','); } argsBuilder.append(" (FLAGS" + extensions + ")"); send(Command.FETCH_THIN_HEADERS_UID, argsBuilder.toString(), valueFuture); return valueFuture; }
@Override public ListenableFuture<Boolean> canCommit() { if (LOG.isDebugEnabled()) { LOG.debug("Tx {} canCommit", transactionId); } final SettableFuture<Boolean> returnFuture = SettableFuture.create(); // The first phase of canCommit is to gather the list of cohort actor paths that will // participate in the commit. buildCohortPathsList combines the cohort path Futures into // one Future which we wait on asynchronously here. The cohort actor paths are // extracted from ReadyTransactionReply messages by the Futures that were obtained earlier // and passed to us from upstream processing. If any one fails then we'll fail canCommit. buildCohortList() .onComplete( new OnComplete<Void>() { @Override public void onComplete(Throwable failure, Void notUsed) throws Throwable { if (failure != null) { if (LOG.isDebugEnabled()) { LOG.debug("Tx {}: a cohort Future failed: {}", transactionId, failure); } returnFuture.setException(failure); } else { finishCanCommit(returnFuture); } } }, actorContext.getClientDispatcher()); return returnFuture; }
public boolean isFinished() { boolean finished = split.isFinished(); if (finished) { finishedFuture.set(null); } return finished || destroyed.get(); }
@Override protected void doSubscribe(String eventName, final SettableFuture<?> future) { List<SettableFuture<?>> futures = new ArrayList<SettableFuture<?>>(); for (RedisConnection conn : connections) { SettableFuture<?> newFuture = SettableFuture.create(); conn.subscribe(eventName, newFuture); futures.add(newFuture); } final ListenableFuture<?> combined = Futures.allAsList(futures); combined.addListener( new Runnable() { @Override public void run() { try { combined.get(); future.set(null); } catch (InterruptedException e) { future.setException(e); } catch (ExecutionException e) { future.setException(e.getCause()); } } }, getExecutorService()); }
@Override protected void setUp() throws Exception { super.setUp(); LocalWaveletContainer.Factory localFactory = mock(LocalWaveletContainer.Factory.class); WaveletNotificationSubscriber notifiee = mock(WaveletNotificationSubscriber.class); SettableFuture<ImmutableSet<WaveletId>> lookedupWavelets = SettableFuture.create(); lookedupWavelets.set(ImmutableSet.of(WAVELET_NAME.waveletId)); Wave wave = new Wave( WAVELET_NAME.waveId, lookedupWavelets, notifiee, localFactory, null, WAVELET_NAME.waveId.getDomain()); Map<WaveId, Wave> waves = Maps.newHashMap(); waves.put(WAVELET_NAME.waveId, wave); when(waveMap.getWaves()).thenReturn(waves); ImmutableSet<WaveletId> wavelets = ImmutableSet.of(WAVELET_NAME.waveletId); when(waveMap.lookupWavelets(WAVELET_NAME.waveId)).thenReturn(wavelets); LocalWaveletContainer c = mock(LocalWaveletContainer.class); when(c.hasParticipant(PARTICIPANT)).thenReturn(true); when(waveMap.getLocalWavelet(WAVELET_NAME)).thenReturn(c); }
@Override public <T> Future<T> submit(final GenericType<T> responseType) { final SettableFuture<T> responseFuture = SettableFuture.create(); configuration() .submit( requestContext, new InvocationCallback<Response>() { @Override public void completed(Response response) { if (response.getStatus() < 300) { try { responseFuture.set(response.readEntity(responseType)); } catch (Exception e) { failed( new InvocationException( LocalizationMessages.UNEXPECTED_ERROR_RESPONSE_PROCESSING(), e)); } } else { failed(convertToException(response)); } } @Override public void failed(InvocationException error) { responseFuture.setException(error); } }); return responseFuture; }
/** * Called when the client provides the multi-sig contract. Checks that the previously-provided * refund transaction spends this transaction (because we will use it as a base to create payment * transactions) as well as output value and form (ie it is a 2-of-2 multisig to the correct * keys). * * @param multisigContract The provided multisig contract. Do not mutate this object after this * call. * @return A future which completes when the provided multisig contract successfully broadcasts, * or throws if the broadcast fails for some reason Note that if the network simply rejects * the transaction, this future will never complete, a timeout should be used. * @throws VerificationException If the provided multisig contract is not well-formed or does not * meet previously-specified parameters */ public synchronized ListenableFuture<PaymentChannelServerState> provideMultiSigContract( final Transaction multisigContract) throws VerificationException { checkNotNull(multisigContract); checkState(state == State.WAITING_FOR_MULTISIG_CONTRACT); try { multisigContract.verify(); this.multisigContract = multisigContract; this.multisigScript = multisigContract.getOutput(0).getScriptPubKey(); // Check that multisigContract's first output is a 2-of-2 multisig to the correct pubkeys in // the correct order final Script expectedScript = ScriptBuilder.createMultiSigOutputScript(2, Lists.newArrayList(clientKey, serverKey)); if (!Arrays.equals(multisigScript.getProgram(), expectedScript.getProgram())) throw new VerificationException( "Multisig contract's first output was not a standard 2-of-2 multisig to client and server in that order."); this.totalValue = multisigContract.getOutput(0).getValue(); if (this.totalValue.signum() <= 0) throw new VerificationException( "Not accepting an attempt to open a contract with zero value."); } catch (VerificationException e) { // We couldn't parse the multisig transaction or its output. log.error("Provided multisig contract did not verify: {}", multisigContract.toString()); throw e; } log.info("Broadcasting multisig contract: {}", multisigContract); state = State.WAITING_FOR_MULTISIG_ACCEPTANCE; final SettableFuture<PaymentChannelServerState> future = SettableFuture.create(); Futures.addCallback( broadcaster.broadcastTransaction(multisigContract).future(), new FutureCallback<Transaction>() { @Override public void onSuccess(Transaction transaction) { log.info( "Successfully broadcast multisig contract {}. Channel now open.", transaction.getHashAsString()); try { // Manually add the multisigContract to the wallet, overriding the isRelevant checks // so we can track // it and check for double-spends later wallet.receivePending(multisigContract, null, true); } catch (VerificationException e) { throw new RuntimeException( e); // Cannot happen, we already called multisigContract.verify() } state = State.READY; future.set(PaymentChannelServerState.this); } @Override public void onFailure(Throwable throwable) { // Couldn't broadcast the transaction for some reason. log.error("Broadcast multisig contract failed", throwable); state = State.ERROR; future.setException(throwable); } }); return future; }
/** Created by Eric on 01/10/2015. */ public class SnitcoinDownloadProgressTracker extends DownloadProgressTracker { private final Logger log = LoggerFactory.getLogger(SnitcoinDownloadProgressTracker.class); private int originalBlocksLeft = -1; private int lastPercent = 0; private SettableFuture<Long> future = SettableFuture.create(); private boolean caughtUp = false; @Override public void onChainDownloadStarted(Peer peer, int blocksLeft) { super.onChainDownloadStarted(peer, blocksLeft); log.info("SnitcoinDownloadProgressTracker - Starting blockchain download " + blocksLeft); } @Override public void onBlocksDownloaded( Peer peer, Block block, @Nullable FilteredBlock filteredBlock, int blocksLeft) { super.onBlocksDownloaded(peer, block, filteredBlock, blocksLeft); double pct = 100.0 - (100.0 * (blocksLeft / (double) originalBlocksLeft)); if ((int) pct != lastPercent) { log.info("SnitcoinDownloadProgressTracker " + lastPercent + " " + blocksLeft); lastPercent = (int) pct; } } protected void doneDownload() { log.info("SnitcoinDownloadProgressTracker - Blockchain download done!"); } }
private void handleFailure( final SettableFuture<Response> future, final Supplier<ListenableFuture<Response>> code, final long deadline, final long delay, final TimeUnit timeUnit, final Throwable t) { if (clock.now().getMillis() < deadline) { if (delay > 0) { executorService.schedule( new Runnable() { @Override public void run() { startRetry(future, code, deadline - 1, delay, timeUnit); } }, delay, timeUnit); } else { startRetry(future, code, deadline - 1, delay, timeUnit); } } else { future.setException(t); } }
@Override public void onRemoval( RemovalNotification<String, InstallFuture> removalNotification) { switch (removalNotification.getCause()) { case EXPLICIT: break; case REPLACED: case COLLECTED: case EXPIRED: case SIZE: SettableFuture<Boolean> value = removalNotification.getValue().future; if (value != null) { // May have been GCed value.set(false); } break; } }
public synchronized ListenableFuture<?> waitForNotEmpty() { if (finishing || !buffer.isEmpty()) { return NOT_BLOCKED; } SettableFuture<?> settableFuture = SettableFuture.create(); blockedCallers.add(settableFuture); return settableFuture; }
private ListenableFuture<Void> voidOperation( final String operationName, final Object message, final Class<?> expectedResponseClass, final boolean propagateException, final OperationCallback callback) { if (LOG.isDebugEnabled()) { LOG.debug("Tx {} {}", transactionId, operationName); } final SettableFuture<Void> returnFuture = SettableFuture.create(); // The cohort actor list should already be built at this point by the canCommit phase but, // if not for some reason, we'll try to build it here. if (cohorts != null) { finishVoidOperation( operationName, message, expectedResponseClass, propagateException, returnFuture, callback); } else { buildCohortList() .onComplete( new OnComplete<Void>() { @Override public void onComplete(Throwable failure, Void notUsed) throws Throwable { if (failure != null) { if (LOG.isDebugEnabled()) { LOG.debug( "Tx {}: a {} cohort path Future failed: {}", transactionId, operationName, failure); } if (propagateException) { returnFuture.setException(failure); } else { returnFuture.set(null); } } else { finishVoidOperation( operationName, message, expectedResponseClass, propagateException, returnFuture, callback); } } }, actorContext.getClientDispatcher()); } return returnFuture; }
@SuppressWarnings({"rawtypes", "unchecked"}) @Override public void processResult(JsonNode response) { log.debug("Handle result"); String requestId = response.get("id").asText(); SettableFuture sf = requestResult.get(requestId); if (sf == null) { log.debug("No such future to process"); return; } String methodName = requestMethod.get(requestId); Object result; result = FromJsonUtil.jsonResultParser(response, methodName); sf.set(result); return; }
static void pingBeforeActivate( final AsyncCommand<?, ?, ?> cmd, final SettableFuture<Boolean> initializedFuture, final ChannelHandlerContext ctx, final List<ChannelHandler> handlers) throws Exception { cmd.handle( (o, throwable) -> { if (throwable == null) { initializedFuture.set(true); ctx.fireChannelActive(); } else { initializedFuture.setException(throwable); } return null; }); ctx.channel().writeAndFlush(cmd); }
private void inboundPongAndWait(final InboundMessageQueuer p, final long nonce) throws Exception { // Receive a ping (that the Peer doesn't see) and wait for it to get through the socket final SettableFuture<Void> pongReceivedFuture = SettableFuture.create(); PeerEventListener listener = new AbstractPeerEventListener() { @Override public Message onPreMessageReceived(Peer p, Message m) { if (m instanceof Pong && ((Pong) m).getNonce() == nonce) { pongReceivedFuture.set(null); return null; } return m; } }; p.peer.addEventListener(listener, Threading.SAME_THREAD); inbound(p, new Pong(nonce)); pongReceivedFuture.get(); p.peer.removeEventListener(listener); }
private ListenableFuture<Void> fetchMoreResults(FetchingState fetchState) { if (fetchState == null) return MoreFutures.VOID_SUCCESS; if (fetchState.inProgress != null) return fetchState.inProgress; assert fetchState.nextStart != null; ByteBuffer state = fetchState.nextStart; SettableFuture<Void> future = SettableFuture.create(); this.fetchState = new FetchingState(null, future); return queryNextPage(state, future); }