Java Code Examples for com.google.common.util.concurrent.Futures#immediateFailedFuture()

The following examples show how to use com.google.common.util.concurrent.Futures#immediateFailedFuture() . 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: CacheDeleteCommandTest.java    From buck with Apache License 2.0 6 votes vote down vote up
@Test
public void testRunCommandAndDeleteArtifactsUnsuccessfully() throws Exception {
  final String ruleKeyHash = "b64009ae3762a42a1651c139ec452f0d18f48e21";

  ArtifactCache cache =
      new FakeArtifactCache(
          Collections.singletonList(new RuleKey(ruleKeyHash)),
          Futures.immediateFailedFuture(new RuntimeException("test failure")));

  TestConsole console = new TestConsole();

  CommandRunnerParams commandRunnerParams =
      CommandRunnerParamsForTesting.builder().setConsole(console).setArtifactCache(cache).build();

  CacheDeleteCommand cacheDeleteCommand = new CacheDeleteCommand();
  cacheDeleteCommand.setArguments(ImmutableList.of(ruleKeyHash));
  ExitCode exitCode = cacheDeleteCommand.run(commandRunnerParams);
  assertEquals(ExitCode.FATAL_GENERIC, exitCode);
  assertThat(console.getTextWrittenToStdErr(), startsWith("Failed to delete artifacts."));
}
 
Example 2
Source File: SwingExecutorService.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
protected <T> Future<T> doInvoke(Callable<T> callable) {
   try {
      // always run after the current event finishes processing
      // this gives more natural behavior from the event thread
      SettableFuture<T> result = SettableFuture.create();
      SwingUtilities.invokeLater(() -> {
         if(result.isCancelled()) {
            return;
         }
         try {
            result.set(callable.call());
         }
         catch(Throwable t) {
         	logger.warn("Uncaught exception", t);
            result.setException(t);
         }
      });
      return result;
   }
   catch(Exception e) {
   	logger.warn("Uncaught exception", e);
      return Futures.immediateFailedFuture(e);
   }
}
 
Example 3
Source File: TestDriftNettyMethodInvoker.java    From drift with Apache License 2.0 6 votes vote down vote up
@Override
public ListenableFuture<Object> invoke(ServerInvokeRequest request)
{
    MethodMetadata method = request.getMethod();
    if (!LOG_METHOD_METADATA.getName().equals(method.getName())) {
        return Futures.immediateFailedFuture(new IllegalArgumentException("unknown method " + method));
    }

    Map<Short, Object> parameters = request.getParameters();
    if (parameters.size() != 1 || !parameters.containsKey((short) 1) || !(getOnlyElement(parameters.values()) instanceof List)) {
        return Futures.immediateFailedFuture(new IllegalArgumentException("invalid parameters"));
    }
    List<DriftLogEntry> messages = (List<DriftLogEntry>) getOnlyElement(parameters.values());

    for (DriftLogEntry message : messages) {
        if (message.getCategory().equals("exception")) {
            return Futures.immediateFailedFuture(new TApplicationException(UNSUPPORTED_CLIENT_TYPE, message.getMessage()));
        }
    }
    this.messages.addAll(messages);
    return Futures.immediateFuture(DRIFT_OK);
}
 
Example 4
Source File: IndexingServiceImpl.java    From connector-sdk with Apache License 2.0 6 votes vote down vote up
/**
 * Deletes items from a queue.
 *
 * @param queueName the queue name
 * @return {@link ListenableFuture} that the caller uses to obtain the result of a delete queue
 *     items operation (using {@link ListenableFuture#get()}).
 * @throws IOException when the service throws an exception
 */
@Override
public ListenableFuture<Operation> deleteQueueItems(String queueName) throws IOException {
  validateRunning();
  checkArgument(!Strings.isNullOrEmpty(queueName), "Queue name cannot be null.");

  DeleteQueueItems request =
      this.service
          .indexing()
          .datasources()
          .items()
          .deleteQueueItems(
              resourcePrefix,
              new DeleteQueueItemsRequest()
                  .setQueue(queueName)
                  .setDebugOptions(new DebugOptions().setEnableDebugging(enableApiDebugging)));
  acquireToken(Operations.DEFAULT);
  try {
    return Futures.immediateFuture(
        executeRequest(request, indexingServiceStats, true /* initializeDefaults */));
  } catch (IOException e) {
    return Futures.immediateFailedFuture(e);
  }
}
 
Example 5
Source File: GuavaLFReturnValueHandlerTest.java    From grpc-java-contrib with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void handlesFailure() throws Exception {
    final AtomicReference<Object> value = new AtomicReference<>();
    Exception ex = new Exception("This is bad");
    ListenableFuture<String> future = Futures.immediateFailedFuture(ex);

    GuavaLFReturnValueHandler handler = new GuavaLFReturnValueHandler() {
        @Override
        protected void startDeferredResultProcessing(ModelAndViewContainer mavContainer, NativeWebRequest webRequest, DeferredResult<Object> deferredResult) throws Exception {
            value.set(deferredResult.getResult());
        }
    };

    handler.handleReturnValue(future, null, null, null);
    assertThat(value.get()).isEqualTo(ex);
}
 
Example 6
Source File: AbstractZKServiceController.java    From twill with Apache License 2.0 6 votes vote down vote up
/**
 * Sends a {@link Message} to the remote service. Returns a future that will be completed when the message
 * has been processed.
 * @param message The message to send.
 * @param result Object to set into the future when message is being processed.
 * @param <V> Type of the result.
 * @return A {@link ListenableFuture} that will be completed when the message has been processed.
 */
protected final synchronized <V> ListenableFuture<V> sendMessage(Message message, V result) {
  if (!isRunning()) {
    return Futures.immediateFailedFuture(new IllegalStateException("Cannot send message to non-running application"));
  }
  final ListenableFuture<V> messageFuture = ZKMessages.sendMessage(zkClient, getMessagePrefix(), message, result);
  messageFutures.add(messageFuture);
  messageFuture.addListener(new Runnable() {
    @Override
    public void run() {
      // If the completion is triggered when stopping, do nothing.
      if (state() == State.STOPPING) {
        return;
      }
      synchronized (AbstractZKServiceController.this) {
        messageFutures.remove(messageFuture);
      }
    }
  }, Threads.SAME_THREAD_EXECUTOR);

  return messageFuture;
}
 
Example 7
Source File: HttpCacheClient.java    From bazel with Apache License 2.0 5 votes vote down vote up
@Override
public ListenableFuture<Void> uploadFile(Digest digest, Path file) {
  try (InputStream in = file.getInputStream()) {
    uploadBlocking(digest.getHash(), digest.getSizeBytes(), in, /* casUpload= */ true);
  } catch (IOException | InterruptedException e) {
    return Futures.immediateFailedFuture(e);
  }
  return Futures.immediateFuture(null);
}
 
Example 8
Source File: UserFinder.java    From ProjectAres with GNU Affero General Public License v3.0 5 votes vote down vote up
public ListenableFuture<PlayerSearchResponse> findPlayer(CommandSender sender, @Nullable String name, Scope scope, Default def) {
    try {
        final Player player = getLocalPlayer(sender, name);
        if(player != null) {
            return Futures.immediateFuture(localPlayerResponse(sender, player));
        }

        if(scope.noGreaterThan(Scope.LOCAL)) {
            throw new TranslatableCommandException("command.playerNotFound");
        }

        final SettableFuture<PlayerSearchResponse> playerResult = SettableFuture.create();
        mainThreadExecutor.callback(
            findUser(sender, name, scope, def),
            new FutureCallback<UserSearchResponse>() {
                @Override
                public void onSuccess(@Nullable UserSearchResponse userResult) {
                    playerResult.set(new PlayerSearchResponse(userResult, onlinePlayers.find(userResult.user)));
                }

                @Override
                public void onFailure(Throwable t) {
                    playerResult.setException(t);
                }
            }
        );

        return playerResult;
    } catch(CommandException e) {
        return Futures.immediateFailedFuture(e);
    }
}
 
Example 9
Source File: DriftServerMethodInvoker.java    From drift with Apache License 2.0 5 votes vote down vote up
@Override
public ListenableFuture<Object> invoke(ServerInvokeRequest request)
{
    ServiceMethod method = methods.get(request.getMethod().getName());
    if (method == null) {
        return Futures.immediateFailedFuture(new TApplicationException(Type.UNKNOWN_METHOD, "Invalid method name: '" + request.getMethod().getName() + "'"));
    }

    return method.invokeMethod(request);
}
 
Example 10
Source File: Retrier.java    From bazel-buildfarm with Apache License 2.0 5 votes vote down vote up
private <T> ListenableFuture<T> onExecuteAsyncFailure(
    Exception t, AsyncCallable<T> call, Backoff backoff) {
  long waitMillis = backoff.nextDelayMillis();
  if (waitMillis >= 0 && isRetriable.apply(Status.fromThrowable(t))) {
    try {
      return Futures.scheduleAsync(
          () -> executeAsync(call, backoff), waitMillis, TimeUnit.MILLISECONDS, retryScheduler);
    } catch (RejectedExecutionException e) {
      // May be thrown by .scheduleAsync(...) if i.e. the executor is shutdown.
      return Futures.immediateFailedFuture(new IOException(e));
    }
  } else {
    return Futures.immediateFailedFuture(t);
  }
}
 
Example 11
Source File: FitErrorAction.java    From titus-control-plane with Apache License 2.0 5 votes vote down vote up
@Override
public <T> Supplier<ListenableFuture<T>> aroundListenableFuture(String injectionPoint, Supplier<ListenableFuture<T>> source) {
    if (runBefore) {
        return () -> {
            if (shouldFailFunction.get()) {
                return Futures.immediateFailedFuture(newException(injectionPoint));
            }
            return source.get();
        };
    }
    return () -> Futures.transform(source.get(), input -> doFail(injectionPoint) ? null : input, MoreExecutors.directExecutor());
}
 
Example 12
Source File: ArpSender.java    From atrium-odl with Apache License 2.0 5 votes vote down vote up
/**
 * Sends ARP Request as packet-out from the given port (node connector).
 *
 * @param senderAddress
 *            the addresses used in sender part of ARP packet
 * @param tpa
 *            the target protocol address, in this case IPv4 address for
 *            which MAC should be discovered
 * @param egressNc
 *            the path to node connector from where the ARP packet will be
 *            sent
 * @return future result about success of packet-out
 */
public ListenableFuture<RpcResult<Void>> sendArp(ArpMessageAddress senderAddress, Ipv4Address tpa,
		InstanceIdentifier<NodeConnector> egressNc) {
	checkNotNull(senderAddress);
	checkNotNull(tpa);
	checkNotNull(egressNc);
	final Ethernet arpFrame = createArpFrame(senderAddress, tpa);
	byte[] arpFrameAsBytes;
	try {
		arpFrameAsBytes = arpFrame.serialize();
	} catch (PacketException e) {
		LOG.warn("Serializition of ARP packet is not successful.", e);
		if (LOG.isDebugEnabled()) {
			LOG.debug("ARP packet: {}", ArpUtils.getArpFrameToStringFormat(arpFrame));
		}
		return Futures.immediateFailedFuture(e);
	}
	// Generate packet with destination switch and port

	TransmitPacketInput packet = new TransmitPacketInputBuilder().setEgress(new NodeConnectorRef(egressNc))
			.setNode(new NodeRef(egressNc.firstIdentifierOf(Node.class))).setPayload(arpFrameAsBytes).build();
	if (LOG.isTraceEnabled()) {
		LOG.trace("Sending ARP REQUEST \n{}", ArpUtils.getArpFrameToStringFormat(arpFrame));
	}
	Future<RpcResult<Void>> futureTransmitPacketResult = packetProcessingService.transmitPacket(packet);
	return JdkFutureAdapters.listenInPoolThread(futureTransmitPacketResult);
}
 
Example 13
Source File: RsaKey.java    From azure-keyvault-java with MIT License 5 votes vote down vote up
@Override
public ListenableFuture<byte[]> decryptAsync(final byte[] ciphertext, final byte[] iv, final byte[] authenticationData, final byte[] authenticationTag, final String algorithm) throws NoSuchAlgorithmException {

    if (ciphertext == null) {
        throw new IllegalArgumentException("ciphertext");
    }

    // Interpret the requested algorithm
    if (Strings.isNullOrWhiteSpace(algorithm)) {
        throw new IllegalArgumentException("algorithm");
    }

    Algorithm baseAlgorithm = AlgorithmResolver.Default.get(algorithm);
    
    if (baseAlgorithm == null || !(baseAlgorithm instanceof AsymmetricEncryptionAlgorithm)) {
        throw new NoSuchAlgorithmException(algorithm);
    }
    
    AsymmetricEncryptionAlgorithm algo = (AsymmetricEncryptionAlgorithm)baseAlgorithm;

    ICryptoTransform         transform;
    ListenableFuture<byte[]> result;

    try {
        transform = algo.CreateDecryptor(_keyPair, _provider);
        result    = Futures.immediateFuture(transform.doFinal(ciphertext));
    } catch (Exception e) {
        result    = Futures.immediateFailedFuture(e);
    }

    return result;
}
 
Example 14
Source File: TestEpochsAreUnique.java    From hadoop with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public ListenableFuture<T> answer(InvocationOnMock invocation)
    throws Throwable {
  if (r.nextFloat() < faultProbability) {
    return Futures.immediateFailedFuture(
        new IOException("Injected fault"));
  }
  return (ListenableFuture<T>)invocation.callRealMethod();
}
 
Example 15
Source File: PersistenceService.java    From luna with MIT License 5 votes vote down vote up
/**
 * Asynchronously saves {@code data} under the key {@code username}. The task will fail if the player is being serviced
 * by the {@link LogoutService}.
 *
 * @param username The player's username.
 * @param data The data to save.
 * @return A listenable future describing the result of the save.
 */
public ListenableFuture<Void> save(String username, PlayerData data) {
    if (world.getLogoutService().hasRequest(username)) {
        // The LogoutService will handle the saving.
        IllegalStateException ex = new IllegalStateException("This player is already being serviced by LogoutService.");
        return Futures.immediateFailedFuture(ex);
    }
    logger.trace("Sending save request for {} to a worker...", username);
    return worker.submit(() -> {
        var timer = Stopwatch.createStarted();
        AuthenticationService.PERSISTENCE.save(username, data);
        logger.debug("Finished saving {}'s data (took {}ms).", username, box(timer.elapsed().toMillis()));
        return null;
    });
}
 
Example 16
Source File: TestQuorumJournalManagerUnit.java    From hadoop with Apache License 2.0 4 votes vote down vote up
static Stubber futureThrows(Throwable t) {
  ListenableFuture<?> ret = Futures.immediateFailedFuture(t);
  return Mockito.doReturn(ret);
}
 
Example 17
Source File: NullTournamentService.java    From ProjectAres with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public ListenableFuture<Entrant> entrant(String tournamentId, String teamId) {
    return Futures.immediateFailedFuture(new NotFound());
}
 
Example 18
Source File: TestQuorumJournalManagerUnit.java    From big-c with Apache License 2.0 4 votes vote down vote up
static Stubber futureThrows(Throwable t) {
  ListenableFuture<?> ret = Futures.immediateFailedFuture(t);
  return Mockito.doReturn(ret);
}
 
Example 19
Source File: NullUserService.java    From ProjectAres with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public ListenableFuture<User> changeClass(UserId userId, ChangeClassRequest request) {
    return Futures.immediateFailedFuture(new NotFound());
}
 
Example 20
Source File: GuavaOriginalFutureTestHelper.java    From future-converter with Apache License 2.0 4 votes vote down vote up
@Override
public ListenableFuture<String> createExceptionalFuture(Exception exception) {
    return Futures.immediateFailedFuture(exception);
}