com.twitter.util.Return Java Examples

The following examples show how to use com.twitter.util.Return. 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: BookKeeperClient.java    From distributedlog with Apache License 2.0 6 votes vote down vote up
public Future<LedgerHandle> createLedger(int ensembleSize,
                                         int writeQuorumSize,
                                         int ackQuorumSize) {
    BookKeeper bk;
    try {
        bk = get();
    } catch (IOException ioe) {
        return Future.exception(ioe);
    }
    final Promise<LedgerHandle> promise = new Promise<LedgerHandle>();
    bk.asyncCreateLedger(ensembleSize, writeQuorumSize, ackQuorumSize,
            BookKeeper.DigestType.CRC32, passwd, new AsyncCallback.CreateCallback() {
                @Override
                public void createComplete(int rc, LedgerHandle lh, Object ctx) {
                    if (BKException.Code.OK == rc) {
                        promise.updateIfEmpty(new Return<LedgerHandle>(lh));
                    } else {
                        promise.updateIfEmpty(new Throw<LedgerHandle>(BKException.create(rc)));
                    }
                }
            }, null);
    return promise;
}
 
Example #2
Source File: AbstractStreamOp.java    From distributedlog with Apache License 2.0 5 votes vote down vote up
protected void setResponse(Response response) {
  Return<Response> responseTry = new Return(response);
  boolean isEmpty = result.updateIfEmpty(responseTry);
  if (!isEmpty) {
    Option<Try<Response>> resultTry = result.poll();
    logger.error("Result set multiple times. Value='{}', New='{}'", resultTry, responseTry);
  }
}
 
Example #3
Source File: DistributedLogClientImpl.java    From distributedlog with Apache License 2.0 5 votes vote down vote up
private void getOwnerFromResourcePlacementServer(final StreamOp op,
                                                 final Promise<SocketAddress> getOwnerPromise) {
    clusterClient.get().getService().getOwner(op.stream, op.ctx)
        .addEventListener(new FutureEventListener<WriteResponse>() {
            @Override
            public void onFailure(Throwable cause) {
                getOwnerPromise.updateIfEmpty(new Throw<SocketAddress>(cause));
            }

            @Override
            public void onSuccess(WriteResponse value) {
                if (StatusCode.FOUND == value.getHeader().getCode()
                      && null != value.getHeader().getLocation()) {
                    try {
                        InetSocketAddress addr = DLSocketAddress.deserialize(
                            value.getHeader().getLocation()
                        ).getSocketAddress();
                        getOwnerPromise.updateIfEmpty(new Return<SocketAddress>(addr));
                    } catch (IOException e) {
                        // retry from the routing server again
                        logger.error("ERROR in getOwner", e);
                        retryGetOwnerFromResourcePlacementServer(op, getOwnerPromise, e);
                        return;
                    }
                } else {
                    // retry from the routing server again
                    retryGetOwnerFromResourcePlacementServer(op, getOwnerPromise,
                            new StreamUnavailableException("Stream " + op.stream + "'s owner is unknown"));
                }
            }
        });
}
 
Example #4
Source File: BookKeeperClient.java    From distributedlog with Apache License 2.0 5 votes vote down vote up
public Future<Void> deleteLedger(long lid,
                                 final boolean ignoreNonExistentLedger) {
    BookKeeper bk;
    try {
        bk = get();
    } catch (IOException ioe) {
        return Future.exception(ioe);
    }
    final Promise<Void> promise = new Promise<Void>();
    bk.asyncDeleteLedger(lid, new AsyncCallback.DeleteCallback() {
        @Override
        public void deleteComplete(int rc, Object ctx) {
            if (BKException.Code.OK == rc) {
                promise.updateIfEmpty(new Return<Void>(null));
            } else if (BKException.Code.NoSuchLedgerExistsException == rc) {
                if (ignoreNonExistentLedger) {
                    promise.updateIfEmpty(new Return<Void>(null));
                } else {
                    promise.updateIfEmpty(new Throw<Void>(BKException.create(rc)));
                }
            } else {
                promise.updateIfEmpty(new Throw<Void>(BKException.create(rc)));
            }
        }
    }, null);
    return promise;
}
 
Example #5
Source File: ZKSessionLock.java    From distributedlog with Apache License 2.0 5 votes vote down vote up
private void claimOwnership(int lockEpoch) {
    lockState.transition(State.CLAIMED);
    // clear previous lock ids
    lockContext.clearLockIds();
    // add current lock id
    lockContext.addLockId(lockId);
    if (LOG.isDebugEnabled()) {
        LOG.debug("Notify lock waiters on {} at {} : watcher epoch {}, lock epoch {}",
                new Object[] { lockPath, System.currentTimeMillis(),
                        lockEpoch, ZKSessionLock.this.epoch.get() });
    }
    acquireFuture.updateIfEmpty(new Return<Boolean>(true));
}
 
Example #6
Source File: FutureUtils.java    From distributedlog with Apache License 2.0 5 votes vote down vote up
/**
 * Satisfy the <i>promise</i> with provide value.
 * <p>If the promise was already satisfied, nothing will be changed.
 *
 * @param promise promise to satisfy
 * @param value value to satisfy
 * @return true if successfully satisfy the future. false if the promise has been satisfied.
 */
public static <T> boolean setValue(Promise<T> promise, T value) {
    boolean success = promise.updateIfEmpty(new Return<T>(value));
    if (!success) {
        logger.info("Result set multiple times. Value = '{}', New = 'Return({})'",
                promise.poll(), value);
    }
    return success;
}
 
Example #7
Source File: AbstractStreamOp.java    From distributedlog with Apache License 2.0 5 votes vote down vote up
protected void setResponse(Response response) {
  Return<Response> responseTry = new Return(response);
  boolean isEmpty = result.updateIfEmpty(responseTry);
  if (!isEmpty) {
    Option<Try<Response>> resultTry = result.poll();
    logger.error("Result set multiple times. Value='{}', New='{}'", resultTry, responseTry);
  }
}
 
Example #8
Source File: FutureUtil.java    From terrapin with Apache License 2.0 5 votes vote down vote up
public static <T> Future<Try<T>> lifeToTry(Future<T> future) {
  return future.map(new Function<T, Try<T>>() {
    @Override
    public Try<T> apply(T o) {
      return new Return(o);
    }
  }).handle(new Function<Throwable, Try<T>>() {
    @Override
    public Try<T> apply(Throwable throwable) {
      return new Throw(throwable);
    }
  });
}
 
Example #9
Source File: TwitterFutureUtils.java    From distributedlog with Apache License 2.0 4 votes vote down vote up
public static <T> void setValue(Promise<T> promise, T value) {
    promise.updateIfEmpty(new Return<T>(value));
}
 
Example #10
Source File: ZKSessionLockFactory.java    From distributedlog with Apache License 2.0 4 votes vote down vote up
void createLock(final String lockPath,
                final DistributedLockContext context,
                final AtomicReference<Throwable> interruptedException,
                final AtomicInteger numRetries,
                final Promise<SessionLock> createPromise,
                final long delayMs) {
    lockStateExecutor.schedule(lockPath, new Runnable() {
        @Override
        public void run() {
            if (null != interruptedException.get()) {
                createPromise.updateIfEmpty(new Throw<SessionLock>(interruptedException.get()));
                return;
            }
            try {
                SessionLock lock = new ZKSessionLock(
                        zkc,
                        lockPath,
                        clientId,
                        lockStateExecutor,
                        lockOpTimeout,
                        lockStatsLogger,
                        context);
                createPromise.updateIfEmpty(new Return<SessionLock>(lock));
            } catch (DLInterruptedException dlie) {
                // if the creation is interrupted, throw the exception without retrie.
                createPromise.updateIfEmpty(new Throw<SessionLock>(dlie));
                return;
            } catch (IOException e) {
                if (numRetries.getAndDecrement() < 0) {
                    createPromise.updateIfEmpty(new Throw<SessionLock>(e));
                    return;
                }
                createLock(
                        lockPath,
                        context,
                        interruptedException,
                        numRetries,
                        createPromise,
                        zkRetryBackoffMs);
            }
        }
    }, delayMs, TimeUnit.MILLISECONDS);
}
 
Example #11
Source File: FutureUtils.java    From distributedlog with Apache License 2.0 3 votes vote down vote up
/**
 * Satisfy the <i>promise</i> with provide value.
 *
 * <p>If the promise was already satisfied, nothing will be changed.
 *
 * @param promise promise to satisfy
 * @param value value to satisfy
 * @return true if successfully satisfy the future. false if the promise has been satisfied.
 */
public static <T> boolean setValue(Promise<T> promise, T value) {
    boolean success = promise.updateIfEmpty(new Return<T>(value));
    if (!success) {
        logger.info("Result set multiple times. Value = '{}', New = 'Return({})'",
                promise.poll(), value);
    }
    return success;
}