com.twitter.util.Throw Java Examples
The following examples show how to use
com.twitter.util.Throw.
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 |
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: TerrapinServerInternalImplTest.java From terrapin with Apache License 2.0 | 6 votes |
@Test public void testGetErrorMultipleResources() throws Exception { TerrapinInternalGetRequest request = new TerrapinInternalGetRequest(); MultiKey multiKey1 = new MultiKey().setResource("resource1").setPartition("1"); multiKey1.addToKey(ByteBuffer.wrap("k1".getBytes())); MultiKey multiKey2 = new MultiKey().setResource("resource2").setPartition("1"); multiKey2.addToKey(ByteBuffer.wrap("k2".getBytes())); request.addToKeyList(multiKey1); request.addToKeyList(multiKey2); Reader mockReader = mock(Reader.class); when(mockResourcePartitionMap.getReader(eq("resource1"), eq("1"))).thenReturn(mockReader); Try<TerrapinResponse> responseTry = serverImpl.get(request).get(Duration.forever()); TerrapinGetException e = (TerrapinGetException)((Throw)responseTry).e(); assertEquals(TerrapinGetErrorCode.INVALID_REQUEST, e.getErrorCode()); }
Example #3
Source File: ZKSessionLock.java From distributedlog with Apache License 2.0 | 6 votes |
Future<BoxedUnit> asyncUnlock(final Throwable cause) { final Promise<BoxedUnit> promise = new Promise<BoxedUnit>(); // Use lock executor here rather than lock action, because we want this opertaion to be applied // whether the epoch has changed or not. The member node is EPHEMERAL_SEQUENTIAL so there's no // risk of an ABA problem where we delete and recreate a node and then delete it again here. lockStateExecutor.submit(lockPath, new SafeRunnable() { @Override public void safeRun() { acquireFuture.updateIfEmpty(new Throw<Boolean>(cause)); unlockInternal(promise); promise.addEventListener(new OpStatsListener<BoxedUnit>(unlockStats)); } }); return promise; }
Example #4
Source File: TerrapinServiceImplTest.java From terrapin with Apache License 2.0 | 6 votes |
@Test public void testMultiGetError() { TerrapinMultiGetRequest request = prepareMultiGetRequest(); Set<ByteBuffer> keys = Sets.newHashSet(ByteBuffer.wrap("key1".getBytes()), ByteBuffer.wrap("key2".getBytes()), ByteBuffer.wrap("key3".getBytes())); when (mockClient1.getMany(eq(FILESET), eq(keys))).thenReturn( Future.<TerrapinResponse>exception(new TerrapinGetException("Failed", TerrapinGetErrorCode.FILE_SET_NOT_FOUND))); Try<TerrapinResponse> responseTry = serviceIface.multiGet(request).get(Duration.forever()); assertTrue(responseTry.isThrow()); assertEquals(TerrapinGetErrorCode.FILE_SET_NOT_FOUND, ((TerrapinGetException)((Throw)responseTry).e()).getErrorCode()); when(mockClient1.getMany(eq(FILESET), eq(keys))).thenThrow( new RuntimeException(new NullPointerException())); responseTry = serviceIface.multiGet(request).get(Duration.forever()); assertTrue(responseTry.isThrow()); assertEquals(TerrapinGetErrorCode.OTHER, ((TerrapinGetException)((Throw)responseTry).e()).getErrorCode()); }
Example #5
Source File: TerrapinServiceImplTest.java From terrapin with Apache License 2.0 | 6 votes |
@Test public void testMultiGetEmptyClusters() { TerrapinMultiGetRequest request = prepareMultiGetRequest(); RequestOptions options = new RequestOptions(); options.setSelectionPolicy(SelectionPolicy.PRIMARY_FIRST); request.setOptions(options); request.setClusterList(ImmutableList.copyOf(new String[]{})); TerrapinResponse response = new TerrapinResponse().setResponseMap(ImmutableMap.of( ByteBuffer.wrap("key1".getBytes()), new TerrapinSingleResponse().setValue("value1".getBytes()), ByteBuffer.wrap("key2".getBytes()), new TerrapinSingleResponse().setErrorCode(TerrapinGetErrorCode.READ_ERROR))); Set<ByteBuffer> keys = Sets.newHashSet(ByteBuffer.wrap("key1".getBytes()), ByteBuffer.wrap("key2".getBytes()), ByteBuffer.wrap("key3".getBytes())); when(mockClient1.getMany(eq(FILESET), eq(keys))).thenReturn(Future.value(response)); when(mockClient2.getManyNoRetries(eq(FILESET), eq(keys))).thenReturn(Future.value(response)); Try<TerrapinResponse> returnResponseTry = serviceIface.multiGet(request).get(Duration.forever()); assertTrue(returnResponseTry.isThrow()); assertEquals(TerrapinGetErrorCode.INVALID_REQUEST, ((TerrapinGetException)((Throw)returnResponseTry).e()).getErrorCode()); }
Example #6
Source File: TerrapinServiceImplTest.java From terrapin with Apache License 2.0 | 6 votes |
@Test public void testGetEmptyClusters() { ByteBuffer key = ByteBuffer.wrap(KEY); TerrapinGetRequest request = prepareGetRequest(); RequestOptions options = new RequestOptions(); options.setSelectionPolicy(SelectionPolicy.PRIMARY_FIRST); request.setOptions(options); request.setClusterList(ImmutableList.copyOf(new String[]{})); TerrapinResponse response = new TerrapinResponse().setResponseMap(ImmutableMap.of( key, new TerrapinSingleResponse().setValue(ByteBuffer.wrap("value".getBytes())))); when(mockClient1.getMany(eq(FILESET), eq(Sets.newHashSet(key)))).thenReturn( Future.value(response)); when(mockClient2.getManyNoRetries(eq(FILESET), eq(Sets.newHashSet(key)))).thenReturn( Future.value(response)); Try<TerrapinSingleResponse> singleResponseTry = serviceIface.get(request).get(Duration.forever()); assertTrue(singleResponseTry.isThrow()); assertEquals(TerrapinGetErrorCode.INVALID_REQUEST, ((TerrapinGetException)((Throw)singleResponseTry).e()).getErrorCode()); }
Example #7
Source File: FutureUtils.java From distributedlog with Apache License 2.0 | 5 votes |
/** * Satisfy the <i>promise</i> with provided <i>cause</i>. * * @param promise promise to satisfy * @param cause cause to satisfy * @return true if successfully satisfy the future. false if the promise has been satisfied. */ public static <T> boolean setException(Promise<T> promise, Throwable cause) { boolean success = promise.updateIfEmpty(new Throw<T>(cause)); if (!success) { logger.info("Result set multiple times. Value = '{}', New = 'Throw({})'", promise.poll(), cause); } return success; }
Example #8
Source File: PinLaterQueryIssuer.java From pinlater with Apache License 2.0 | 5 votes |
private void issueEnqueueRequests(PinLater.ServiceIface iface) throws InterruptedException { Preconditions.checkNotNull(queueName, "Queue was not specified."); final AtomicLong queriesIssued = new AtomicLong(0); final Semaphore permits = new Semaphore(concurrency); while (numQueries == -1 || queriesIssued.get() < numQueries) { final PinLaterEnqueueRequest request = new PinLaterEnqueueRequest(); request.setQueueName(queueName); for (int i = 0; i < batchSize; i++) { PinLaterJob job = new PinLaterJob(ByteBuffer.wrap( new String("task_" + random.nextInt(Integer.MAX_VALUE)).getBytes())); job.setPriority(priority); request.addToJobs(job); } final long startTimeNanos = System.nanoTime(); queriesIssued.incrementAndGet(); permits.acquire(); iface.enqueueJobs(REQUEST_CONTEXT, request).respond( new Function<Try<PinLaterEnqueueResponse>, BoxedUnit>() { @Override public BoxedUnit apply(Try<PinLaterEnqueueResponse> responseTry) { permits.release(); statsLogger.requestComplete( Duration.fromNanoseconds(System.nanoTime() - startTimeNanos)); if (responseTry.isThrow()) { LOG.info("Exception for request: " + request + " : " + ((Throw) responseTry).e()); } return BoxedUnit.UNIT; } }); } permits.acquire(concurrency); LOG.info("Enqueue queries issued: " + queriesIssued); }
Example #9
Source File: FutureUtil.java From terrapin with Apache License 2.0 | 5 votes |
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 #10
Source File: TerrapinServiceImplTest.java From terrapin with Apache License 2.0 | 5 votes |
@Test public void testMultiGetClusterNotFound() { TerrapinMultiGetRequest request = prepareMultiGetRequest().setClusterList(ImmutableList.of( "random-cluster")); Try<TerrapinResponse> responseTry = serviceIface.multiGet(request).get(Duration.forever()); assertTrue(responseTry.isThrow()); assertEquals(TerrapinGetErrorCode.CLUSTER_NOT_FOUND, ((TerrapinGetException)((Throw)responseTry).e()).getErrorCode()); }
Example #11
Source File: TerrapinServiceImplTest.java From terrapin with Apache License 2.0 | 5 votes |
@Test public void testGetError() { // Test the case where We get back an error set through an error code set in // TerrapinSingleResponse. ByteBuffer key = ByteBuffer.wrap(KEY); TerrapinGetRequest request = prepareGetRequest(); TerrapinResponse response = new TerrapinResponse().setResponseMap(ImmutableMap.of( key, new TerrapinSingleResponse().setErrorCode(TerrapinGetErrorCode.OTHER))); when(mockClient1.getMany(eq(FILESET), eq(Sets.newHashSet(key)))).thenReturn( Future.value(response)); Try<TerrapinSingleResponse> singleResponseTry = serviceIface.get(request).get( Duration.forever()); assertTrue(singleResponseTry.isThrow()); assertEquals(TerrapinGetErrorCode.OTHER, ((TerrapinGetException)((Throw)singleResponseTry).e()).getErrorCode()); // Test the case where the call to the client library itself bails out due to a // legit error. when(mockClient1.getMany(eq(FILESET), eq(Sets.newHashSet(key)))).thenReturn( Future.<TerrapinResponse>exception(new TerrapinGetException("Failed.", TerrapinGetErrorCode.FILE_SET_NOT_FOUND))); singleResponseTry = serviceIface.get(request).get(Duration.forever()); assertTrue(singleResponseTry.isThrow()); assertEquals(TerrapinGetErrorCode.FILE_SET_NOT_FOUND, ((TerrapinGetException)((Throw)singleResponseTry).e()).getErrorCode()); // Test the case where the call to the client library bails out due to a runtime // exception. when(mockClient1.getMany(eq(FILESET), eq(Sets.newHashSet(key)))).thenThrow( new RuntimeException(new NullPointerException())); singleResponseTry = serviceIface.get(request).get(Duration.forever()); assertTrue(singleResponseTry.isThrow()); assertEquals(TerrapinGetErrorCode.OTHER, ((TerrapinGetException)((Throw)singleResponseTry).e()).getErrorCode()); }
Example #12
Source File: TerrapinServiceImplTest.java From terrapin with Apache License 2.0 | 5 votes |
@Test public void testGetClusterNotFound() { TerrapinGetRequest request = prepareGetRequest().setClusterList(ImmutableList.of( "random-cluster")); Try<TerrapinSingleResponse> singleResponseTry = serviceIface.get(request).get(Duration.forever()); assertTrue(singleResponseTry.isThrow()); assertEquals(TerrapinGetErrorCode.CLUSTER_NOT_FOUND, ((TerrapinGetException)((Throw)singleResponseTry).e()).getErrorCode()); }
Example #13
Source File: FutureUtils.java From distributedlog with Apache License 2.0 | 5 votes |
/** * Satisfy the <i>promise</i> with provided <i>cause</i>. * * @param promise promise to satisfy * @param cause cause to satisfy * @return true if successfully satisfy the future. false if the promise has been satisfied. */ public static <T> boolean setException(Promise<T> promise, Throwable cause) { boolean success = promise.updateIfEmpty(new Throw<T>(cause)); if (!success) { logger.info("Result set multiple times. Value = '{}', New = 'Throw({})'", promise.poll(), cause); } return success; }
Example #14
Source File: BKAsyncLogReaderDLSN.java From distributedlog with Apache License 2.0 | 5 votes |
void setException(Throwable throwable) { Stopwatch stopwatch = Stopwatch.createStarted(); if (promise.updateIfEmpty(new Throw<List<LogRecordWithDLSN>>(throwable))) { futureSetLatency.registerFailedEvent(stopwatch.stop().elapsed(TimeUnit.MICROSECONDS)); delayUntilPromiseSatisfied.registerFailedEvent(enqueueTime.elapsed(TimeUnit.MICROSECONDS)); } }
Example #15
Source File: BookKeeperClient.java From distributedlog with Apache License 2.0 | 5 votes |
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 #16
Source File: DistributedLogClientImpl.java From distributedlog with Apache License 2.0 | 5 votes |
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 #17
Source File: ZKSessionLock.java From distributedlog with Apache License 2.0 | 4 votes |
/** * Handle session expired for lock watcher at epoch <i>lockEpoch</i>. * * @param lockEpoch * lock epoch */ private void handleSessionExpired(final int lockEpoch) { executeLockAction(lockEpoch, new LockAction() { @Override public void execute() { if (lockState.inState(State.CLOSED) || lockState.inState(State.CLOSING)) { // Already fully closed, no need to process expire. return; } boolean shouldNotifyLockListener = lockState.inState(State.CLAIMED); lockState.transition(State.EXPIRED); // remove the watcher if (null != watcher) { zkClient.unregister(watcher); } // increment epoch to avoid any ongoing locking action ZKSessionLock.this.epoch.incrementAndGet(); // if session expired, just notify the waiter. as the lock acquire doesn't succeed. // we don't even need to clean up the lock as the znode will disappear after session expired acquireFuture.updateIfEmpty(new Throw<Boolean>( new LockSessionExpiredException(lockPath, lockId, lockState.getState()))); // session expired, ephemeral node is gone. currentNode = null; currentId = null; if (shouldNotifyLockListener) { // if session expired after claimed, we need to notify the caller to re-lock if (null != lockListener) { lockListener.onExpired(); } } } @Override public String getActionName() { return "handleSessionExpired(epoch=" + lockEpoch + ")"; } }); }
Example #18
Source File: ZKSessionLockFactory.java From distributedlog with Apache License 2.0 | 4 votes |
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 #19
Source File: PinLaterQueryIssuer.java From pinlater with Apache License 2.0 | 4 votes |
private void issueDequeueAckRequests(final PinLater.ServiceIface iface) throws InterruptedException { Preconditions.checkNotNull(queueName, "Queue was not specified."); final AtomicLong queriesIssued = new AtomicLong(0); final Semaphore permits = new Semaphore(concurrency); while (numQueries == -1 || queriesIssued.get() < numQueries) { final PinLaterDequeueRequest request = new PinLaterDequeueRequest(); request.setQueueName(queueName); request.setLimit(batchSize); final long startTimeNanos = System.nanoTime(); queriesIssued.incrementAndGet(); permits.acquire(); iface.dequeueJobs(REQUEST_CONTEXT, request).flatMap( new Function<PinLaterDequeueResponse, Future<Void>>() { @Override public Future<Void> apply(PinLaterDequeueResponse response) { if (response.getJobsSize() == 0) { return Future.Void(); } PinLaterJobAckRequest jobAckRequest = new PinLaterJobAckRequest(queueName); for (String job : response.getJobs().keySet()) { if (random.nextInt(100) < dequeueSuccessPercent) { jobAckRequest.addToJobsSucceeded(new PinLaterJobAckInfo(job)); } else { jobAckRequest.addToJobsFailed(new PinLaterJobAckInfo(job)); } } return iface.ackDequeuedJobs(REQUEST_CONTEXT, jobAckRequest); } }).respond(new Function<Try<Void>, BoxedUnit>() { @Override public BoxedUnit apply(Try<Void> voidTry) { permits.release(); statsLogger.requestComplete( Duration.fromNanoseconds(System.nanoTime() - startTimeNanos)); if (voidTry.isThrow()) { LOG.info("Exception for request: " + request + " : " + ((Throw) voidTry).e()); } return BoxedUnit.UNIT; } }); } permits.acquire(concurrency); LOG.info("Dequeue/ack queries issued: " + queriesIssued); }