Java 类java.util.concurrent.ExecutionException 实例源码

项目:openssp    文件:ExchangeServer.java   
private static Future<AdProviderReader> validate(final Future<AdProviderReader> a, final Future<AdProviderReader> b) {
    try {
        if (b.get() == null) {
            return a;
        }
        if (a.get() == null) {
            return b;
        }

        if (FloatComparator.greaterThanWithPrecision(a.get().getPriceEur(), b.get().getPriceEur())) {
            return a;
        }
    } catch (final InterruptedException | ExecutionException e) {
        log.error(e.getMessage());
    }

    return b;
}
项目:ETUmulator    文件:BaseConsoleTest.java   
/**
 * Test of read method, of class BaseConsole.
 *
 * @throws java.lang.InterruptedException
 * @throws java.util.concurrent.ExecutionException
 * @throws java.util.concurrent.TimeoutException
 */
@Test
public void testRead() throws InterruptedException, ExecutionException, TimeoutException {
    assert !Platform.isFxApplicationThread();
    new JFXPanel();

    FutureTask<Void> futureTask = new FutureTask<>(() -> {
        console.write('a');
        char output = console.read();
        assertEquals("BaseConsole does not work properly.", 'a', output);

        console.write('\n');
        output = console.read();
        assertEquals("BaseConsole does not work properly.", '\n', output);
        return null;
    });
    Platform.runLater(futureTask);
    futureTask.get(5, TimeUnit.SECONDS);
}
项目:rkt-launcher    文件:RktCommandHelperTest.java   
@Test
public void shouldThrowIfNotOK() throws Exception {
  when(client.send(any(Request.class)))
      .thenReturn(CompletableFuture.completedFuture(Response.forStatus(Status.BAD_REQUEST)));
  try {
    RktCommandHelper.sendRequest(client,
                                 "http://localhost:8080/rkt/gc",
                                 GcOptions
                                     .builder()
                                     .markOnly(true)
                                     .build(),
                                 GcOutput.class)
        .toCompletableFuture().get();
    fail();
  } catch (ExecutionException e) {
    assertSame(RktLauncherRemoteHttpException.class, e.getCause().getClass());
    assertEquals(400, ((RktLauncherRemoteHttpException) e.getCause()).getCode());
  }
}
项目:ReactiveRest    文件:RestService.java   
/**
 * This method is used to formulate an asynchronous api call on the base of the
 * given parameters and return a {@link HttpResponse}
 *
 * @param httpRequest,
 *            a prepared {@link HttpRequest} used for api call
 * @param consumerOnSuccess,
 *            the consumer used to handle success response
 * @param consumerOnError,
 *            the consumer used to handle error response
 * @param attempts,
 *            the number of attempts to test if an error occurs during the api
 *            call
 * @throws ExecutionException
 *             if a problem occurred during the retrieving of REST client
 */
public static void callAsync(HttpRequest httpRequest, Consumer<HttpResponse> consumerOnSuccess,
        Consumer<Throwable> consumerOnError, int attempts) throws ExecutionException {
    // prepare the call
    Call<ResponseBody> call = prepareCall(httpRequest);
    if (call == null) {
        LOGGER.error("Call cannot be null");
        return;
    }
    if (consumerOnSuccess == null) {
        LOGGER.error("Async consumer on success cannot be null");
        return;
    }
    Date startTime = new Date();
    // make asynchronous http request and get http response
    enqueueCall(call, consumerOnSuccess, consumerOnError, attempts, startTime);
}
项目:kafka-0.11.0.0-src-with-comment    文件:TransactionManagerTest.java   
@Test(expected = ExecutionException.class)
public void testProducerFencedException() throws InterruptedException, ExecutionException {
    final long pid = 13131L;
    final short epoch = 1;

    doInitTransactions(pid, epoch);

    transactionManager.beginTransaction();
    transactionManager.maybeAddPartitionToTransaction(tp0);

    Future<RecordMetadata> responseFuture = accumulator.append(tp0, time.milliseconds(), "key".getBytes(),
            "value".getBytes(), Record.EMPTY_HEADERS, null, MAX_BLOCK_TIMEOUT).future;

    assertFalse(responseFuture.isDone());
    prepareAddPartitionsToTxnResponse(Errors.NONE, tp0, epoch, pid);
    prepareProduceResponse(Errors.INVALID_PRODUCER_EPOCH, pid, epoch);
    sender.run(time.milliseconds()); // Add partitions.

    sender.run(time.milliseconds());  // send produce.

    assertTrue(responseFuture.isDone());
    assertTrue(transactionManager.hasError());
    responseFuture.get();
}
项目:aries-jpa    文件:BlueprintTest.java   
@Test
public void testCoordinationLifecycle() throws InterruptedException, ExecutionException {
    CarService carService = getCarService("em");
    assertNoCars(carService);
    Runnable carLifeCycle = getService(Runnable.class, "(type=carCoordinated)");
    carLifeCycle.run();
    ExecutorService exec = Executors.newFixedThreadPool(20);
    List<Future<?>> futures = new ArrayList<Future<?>>();
    for (int c=0; c<100; c++) {
        futures.add(exec.submit(carLifeCycle));
    }
    exec.shutdown();
    exec.awaitTermination(30, TimeUnit.SECONDS);
    for (Future<?> future : futures) {
        future.get();
    }
    assertNoCars(carService);
}
项目:guava-mock    文件:CacheLoadingTest.java   
public void testBulkLoadUncheckedException() throws ExecutionException {
  Exception e = new RuntimeException();
  CacheLoader<Object, Object> loader = exceptionLoader(e);
  LoadingCache<Object, Object> cache = CacheBuilder.newBuilder()
      .recordStats()
      .build(bulkLoader(loader));
  CacheStats stats = cache.stats();
  assertEquals(0, stats.missCount());
  assertEquals(0, stats.loadSuccessCount());
  assertEquals(0, stats.loadExceptionCount());
  assertEquals(0, stats.hitCount());

  try {
    cache.getAll(asList(new Object()));
    fail();
  } catch (UncheckedExecutionException expected) {
    assertSame(e, expected.getCause());
  }
  stats = cache.stats();
  assertEquals(1, stats.missCount());
  assertEquals(0, stats.loadSuccessCount());
  assertEquals(1, stats.loadExceptionCount());
  assertEquals(0, stats.hitCount());
}
项目:hashsdn-controller    文件:WildcardedDataChangeListenerTest.java   
@Test
public void testSeparateWrites() throws InterruptedException, TimeoutException, ExecutionException {

    DataBroker dataBroker = testContext.getDataBroker();

    final SettableFuture<AsyncDataChangeEvent<InstanceIdentifier<?>, DataObject>> eventFuture =
            SettableFuture.create();
    dataBroker.registerDataChangeListener(LogicalDatastoreType.OPERATIONAL, DEEP_WILDCARDED_PATH,
        dataChangeEvent -> eventFuture.set(dataChangeEvent), DataChangeScope.SUBTREE);

    final WriteTransaction transaction = dataBroker.newWriteOnlyTransaction();
    transaction.put(LogicalDatastoreType.OPERATIONAL, NODE_0_CWU_PATH, CWU, true);
    transaction.put(LogicalDatastoreType.OPERATIONAL, NODE_0_LVU_PATH, LVU, true);
    transaction.put(LogicalDatastoreType.OPERATIONAL, NODE_1_LVU_PATH, LVU, true);
    transaction.submit().get(5, TimeUnit.SECONDS);

    AsyncDataChangeEvent<InstanceIdentifier<?>, DataObject> event = eventFuture.get(1000, TimeUnit.MILLISECONDS);

    validateEvent(event);
}
项目:canal-elasticsearch    文件:TotoroLauncher.java   
public static void main(String[] args) throws InterruptedException, IOException, ExecutionException {

        setGlobalUncaughtExceptionHandler();

        String conf = System.getProperty("canal-es.properties", "classpath:canal-es.properties");

        Properties properties = getProperties(conf);

        TotoroBootStrap canalScheduler = new TotoroBootStrap(properties);
        canalScheduler.start();

        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            try {
                logger.info("## stop the totoro server");
                canalScheduler.stop();
            } catch (Throwable e) {
                logger.warn("##something goes wrong when stopping totoro Server:", e);
            } finally {
                logger.info("## totoro server is down.");
            }
        }));

    }
项目:wall-t    文件:ApiControllerTest.java   
@Test
public void loadProjectList_callback_registers_exception_on_ack_future( ) throws Exception {
    // Setup
    when( _mockRequestController.sendRequest( getApiVersion( ), "projects", ProjectList.class ) )
            .thenReturn( Futures.immediateFailedFuture( new RuntimeException( "Unexpected test exception" ) ) );
    // Exercise
    final ListenableFuture<Void> ackFuture = _apiController.loadProjectList( );
    // Verify
    try {
        ackFuture.get( );
    } catch ( ExecutionException e ) {
        if ( e.getCause( ).getClass( ) == RuntimeException.class && e.getCause( ).getMessage( ).equals( "Unexpected test exception" ) )
            return;
    }
    TestCase.fail( );
}
项目:jobson    文件:JobManagerTest.java   
@Test
public void testGetAllJobStatusChangesObservableEmitsExpectedEventsWhenAborted() throws InterruptedException, ExecutionException, TimeoutException {
    final JobExecutionResult executorResult = new JobExecutionResult(ABORTED);
    final JobExecutor executor = MockJobExecutor.thatResolvesWith(executorResult);
    final JobManager jobManager = createManagerWith(executor);

    final List<JobStatus> statusesEmitted = new ArrayList<>();
    jobManager.allJobStatusChanges()
            .map(JobEvent::getNewStatus)
            .subscribe(statusesEmitted::add);

    final Pair<JobId, CancelablePromise<FinalizedJob>> ret =
            jobManager.submit(STANDARD_VALID_REQUEST);

    ret.getRight().get(DEFAULT_TIMEOUT, MILLISECONDS);

    assertThat(statusesEmitted).isEqualTo(asList(SUBMITTED, RUNNING, ABORTED));
}
项目:angel    文件:CompDoubleVector.java   
@Override protected Double compute() {
  if (endPos <= startPos) {
    return 0.0;
  }
  if (endPos - startPos == 1) {
    if (splits[startPos] != null) {
      return splits[startPos].squaredNorm();
    } else {
      return 0.0;
    }
  } else {
    int middle = (startPos + endPos) / 2;
    SquaredNormOp opLeft = new SquaredNormOp(splits, startPos, middle);
    SquaredNormOp opRight = new SquaredNormOp(splits, middle, endPos);
    invokeAll(opLeft, opRight);

    try {
      return opLeft.get() + opRight.get();
    } catch (InterruptedException | ExecutionException e) {
      LOG.error("NNZCounterOp failed " + e.getMessage());
      return 0.0;
    }
  }
}
项目:googles-monorepo-demo    文件:CacheLoadingTest.java   
public void testBulkLoadNull() throws ExecutionException {
  LoadingCache<Object, Object> cache = CacheBuilder.newBuilder()
      .recordStats()
      .build(bulkLoader(constantLoader(null)));
  CacheStats stats = cache.stats();
  assertEquals(0, stats.missCount());
  assertEquals(0, stats.loadSuccessCount());
  assertEquals(0, stats.loadExceptionCount());
  assertEquals(0, stats.hitCount());

  try {
    cache.getAll(asList(new Object()));
    fail();
  } catch (InvalidCacheLoadException expected) {}
  stats = cache.stats();
  assertEquals(1, stats.missCount());
  assertEquals(0, stats.loadSuccessCount());
  assertEquals(1, stats.loadExceptionCount());
  assertEquals(0, stats.hitCount());
}
项目:talchain    文件:EthereumImpl.java   
@Override
public Future<Transaction> submitTransaction(Transaction transaction) {

    TransactionTask transactionTask = new TransactionTask(transaction, channelManager);

    final Future<List<Transaction>> listFuture =
            TransactionExecutor.instance.submitTransaction(transactionTask);

    pendingState.addPendingTransaction(transaction);

    return new FutureAdapter<Transaction, List<Transaction>>(listFuture) {
        @Override
        protected Transaction adapt(List<Transaction> adapteeResult) throws ExecutionException {
            return adapteeResult.get(0);
        }
    };
}
项目:GeekZone    文件:RequestFuture.java   
private synchronized T doGet(Long timeoutMs)
        throws InterruptedException, ExecutionException, TimeoutException {
    if (mException != null) {
        throw new ExecutionException(mException);
    }

    if (mResultReceived) {
        return mResult;
    }

    if (timeoutMs == null) {
        wait(0);
    } else if (timeoutMs > 0) {
        wait(timeoutMs);
    }

    if (mException != null) {
        throw new ExecutionException(mException);
    }

    if (!mResultReceived) {
        throw new TimeoutException();
    }

    return mResult;
}
项目:tokenapp-backend    文件:TestMinting.java   
@Test
public void testMintingLarge2() throws ExecutionException, InterruptedException {
    dataBtc(1).dataBtc(2);
    rateBtc(101, 1_050_001);
    rateBtc(102, 7);

    int current = 0;
    current = minting.mint(current, 100, 0, 1 * 100_000_000, 0, "w1");
    Assert.assertEquals(0, current);
    current = minting.mint(current, 102, 0, 1 * 100_000_000, 0, "w2");

    Assert.assertEquals(14, current);

    Iterator<Token> it = tokenRepository.findAllByOrderByWalletAddress().iterator();
    Assert.assertEquals(14,  it.next().getAmount().intValue());
}
项目:openjdk-jdk10    文件:ForkJoinTask8Test.java   
public void testAbnormalForkGet(ForkJoinPool pool) {
    RecursiveAction a = new CheckedRecursiveAction() {
        protected void realCompute() throws Exception {
            FailingAsyncFib f = new FailingAsyncFib(8);
            assertSame(f, f.fork());
            try {
                f.get();
                shouldThrow();
            } catch (ExecutionException success) {
                Throwable cause = success.getCause();
                assertTrue(cause instanceof FJException);
                checkCompletedAbnormally(f, cause);
            }
        }};
    testInvokeOnPool(pool, a);
}
项目:angel    文件:CompTIntVector.java   
@Override protected Double compute() {
  if (endPos <= startPos) {
    return 0.0;
  }
  if (endPos - startPos == 1) {
    if (splits[startPos] != null) {
      return splits[startPos].squaredNorm();
    } else {
      return 0.0;
    }
  } else {
    int middle = (startPos + endPos) / 2;
    SquaredNormOp opLeft = new SquaredNormOp(splits, startPos, middle);
    SquaredNormOp opRight = new SquaredNormOp(splits, middle, endPos);
    invokeAll(opLeft, opRight);

    try {
      return opLeft.get() + opRight.get();
    } catch (InterruptedException | ExecutionException e) {
      LOG.error("NNZCounterOp failed " + e.getMessage());
      return 0.0;
    }
  }
}
项目:openjdk-jdk10    文件:RandomStreamTest.java   
<T> void testRandomResultSupplierConcurrently(Supplier<T> s) throws InterruptedException, ExecutionException, TimeoutException {
    // Produce 10 completable future tasks
    final int tasks = 10;
    List<CompletableFuture<T>> cfs = Stream.generate(() -> CompletableFuture.supplyAsync(s)).
            limit(tasks).collect(toList());

    // Wait for all tasks to complete
    // Timeout is beyond reasonable doubt that completion should
    // have occurred unless there is an issue
    CompletableFuture<Void> all = CompletableFuture.allOf(cfs.stream().toArray(CompletableFuture[]::new));
    all.get(1, TimeUnit.MINUTES);

    // Count the distinct results, which should equal the number of tasks
    long rc = cfs.stream().map(CompletableFuture::join).distinct().count();
    assertEquals(rc, tasks);
}
项目:tomcat7    文件:WsRemoteEndpointImplBase.java   
private void handleSendFailureWithEncode(Throwable t) throws IOException, EncodeException {
    // First, unwrap any execution exception
    if (t instanceof ExecutionException) {
        t = t.getCause();
    }

    // Close the session
    wsSession.doClose(new CloseReason(CloseCodes.GOING_AWAY, t.getMessage()),
            new CloseReason(CloseCodes.CLOSED_ABNORMALLY, t.getMessage()));

    // Rethrow the exception
    if (t instanceof EncodeException) {
        throw (EncodeException) t;
    }
    if (t instanceof IOException) {
        throw (IOException) t;
    }
    throw new IOException(t);
}
项目:9AnimeAndroid    文件:NineAnimeApi.java   
public List<Anime> search(String query) throws IOException, InterruptedException, ExecutionException, JSONException {
    String url = "https://9anime.to/search?keyword=" + query.replace(" ", "+");
    Document doc = Jsoup.connect(url).get();
    int totalPages = 1;

    List<Anime> animes = new ArrayList<>();

    if (doc.select("div.paging").size() > 0) {
        totalPages = Math.max(Integer.parseInt(doc.select("span.total").first().text()), totalPages);
    }

    animes.addAll(parseSearchPage(doc));

    for (int i = 1; i < totalPages; ++i) {
        animes.addAll(parseSearchPage(Jsoup.connect(url + "&page=" + (i + 1)).get()));
    }

    return animes;
}
项目:Nird2    文件:ScreenFilterMonitorImpl.java   
@Override
public void startService() throws ServiceException {
    if (used.getAndSet(true)) throw new IllegalStateException();
    Future<Void> f = androidExecutor.runOnUiThread(new Callable<Void>() {
        @Override
        public Void call() {
            IntentFilter intentFilter = new IntentFilter();
            intentFilter.addAction(ACTION_PACKAGE_ADDED);
            intentFilter.addDataScheme("package");
            appContext.registerReceiver(ScreenFilterMonitorImpl.this,
                    intentFilter);
            apps.addAll(getInstalledScreenFilterApps());
            serviceStarted = true;
            return null;
        }
    });
    try {
        f.get();
    } catch (InterruptedException | ExecutionException e) {
        throw new ServiceException(e);
    }
}
项目:guava-mock    文件:AbstractFutureBenchmarks.java   
/**
 * Implementation of the actual value retrieval.  Will return the value
 * on success, an exception on failure, a cancellation on cancellation, or
 * an illegal state if the synchronizer is in an invalid state.
 */
private V getValue() throws CancellationException, ExecutionException {
  int state = getState();
  switch (state) {
    case COMPLETED:
      if (exception != null) {
        throw new ExecutionException(exception);
      } else {
        return value;
      }

    case CANCELLED:
    case INTERRUPTED:
      throw cancellationExceptionWithCause(
          "Task was cancelled.", exception);

    default:
      throw new IllegalStateException(
          "Error, synchronizer in invalid state: " + state);
  }
}
项目:trading-network    文件:Web3jHelper.java   
public static String transfer(String from, String to, int amount, Unit unit) throws InterruptedException, ExecutionException {
    BigInteger nonce = getNonce(from);
    BigInteger weiAmount = Convert.toWei(BigDecimal.valueOf(amount), unit).toBigInteger();
    Transaction transaction = new Transaction(from, nonce, GAS_PRICE_DEFAULT, GAS_LIMIT_DEFAULT, to, weiAmount, null);
    EthSendTransaction txRequest = getWeb3j().ethSendTransaction(transaction).sendAsync().get();
    return txRequest.getTransactionHash();
}
项目:r8    文件:R8GMSCoreV10DeployJarVerificationTest.java   
@Test
public void buildFromDeployJar()
    // TODO(tamaskenez): set hasReference = true when we have the noshrink file for V10
    throws ExecutionException, IOException, ProguardRuleParserException, CompilationException {
  AndroidApp app1 = buildFromDeployJar(
      CompilerUnderTest.R8, CompilationMode.RELEASE,
      GMSCoreCompilationTestBase.GMSCORE_V10_DIR, false);
  AndroidApp app2 = buildFromDeployJar(
      CompilerUnderTest.R8, CompilationMode.RELEASE,
      GMSCoreCompilationTestBase.GMSCORE_V10_DIR, false);

  // Verify that the result of the two compilations was the same.
  assertIdenticalApplications(app1, app2);
}
项目:elasticsearch_my    文件:IndexShardOperationsLockTests.java   
public void testOperationsDelayedIfBlock() throws ExecutionException, InterruptedException, TimeoutException {
    PlainActionFuture<Releasable> future = new PlainActionFuture<>();
    try (Releasable releasable = blockAndWait()) {
        block.acquire(future, ThreadPool.Names.GENERIC, true);
        assertFalse(future.isDone());
    }
    future.get(1, TimeUnit.HOURS).close();
}
项目:ReactiveRest    文件:TestAsyncAPI.java   
public static void testAsyncAPIWithOptionalParams() throws ExecutionException {
    System.out.println("Testing AsyncAPI call with optional params");
    // prepare http request
    HttpRequest httpRequest = new HttpRequest.Builder(BASE_URL, API_ENDPOINT).httpMethod(HTTP_METHOD)
            .headers(HEADERS).queryParams(QUERY_PARAMS).bodyParams(BODY_PARAMS).build();
    System.out.println(httpRequest.toString());
    // execute api call and getting http response
    AsyncAPI.call(httpRequest, consumerOnSuccess);
}
项目:exportJanusGraphToGephi    文件:Graph.java   
public List<Result> getAllEProps() {
    Map params = new HashMap();
    List<Result> E = new ArrayList<Result>();
    try {
        E = this.client.submit("g.E().valueMap(true)", params).all().get();
    } catch (InterruptedException | ExecutionException e) {
        e.printStackTrace();
    }
    return E;
}
项目:xbrowser    文件:Canvas.java   
public void weight(double lw) throws ExecutionException{
    if (Platform.isFxApplicationThread()) {
        body.getGraphicsContext2D().setLineWidth(lw);
    }else {
        counter++;
        if(counter>maxCounter){
            throw new ExecutionException(new Exception(hint));
        }

        Platform.runLater(() -> body.getGraphicsContext2D().setLineWidth(lw));
    }

}
项目:act-platform    文件:FactManager.java   
public FactTypeEntity getFactType(UUID id) {
  if (id == null) return null;

  try {
    return factTypeByIdCache.get(id);
  } catch (ExecutionException ignored) {
    // If fetching FactType fails just return null in order to be consistent with Cassandra's get().
    return null;
  }
}
项目:RNLearn_Project1    文件:SimpleSettableFuture.java   
@Override
public @Nullable T get() throws InterruptedException, ExecutionException {
  mReadyLatch.await();
  if (mException != null) {
    throw new ExecutionException(mException);
  }

  return mResult;
}
项目:sipsoup    文件:CacheCSSFunction.java   
@Override
public Elements call(Element e, List<String> args) {
    try {
        return Collector.collect(cache.get(args.get(0)), e);
    } catch (ExecutionException e1) {
        log.warn("error when loader css query rule cache", e1);
    }
    return e.select(args.get(0));// 发生异常则服务降级
}
项目:difftool    文件:DocumentManagerTests.java   
@Test
public void testInsertChar() {
    try {
        createEnv();
        currentDocument.insertString(0,"a", null);
        checkStringEquality();
    }
    catch (BadLocationException | InterruptedException | ExecutionException e) {
        fail(e);
    }
}
项目:streams-dojo    文件:ExampleParallelStreamTest.java   
@Test(timeout = maximumTestDuration)
public void shouldProcessAllFilteredCalculationInLessThan2Seconds() throws ExecutionException, InterruptedException {
    // Given
    Integer inventoryCountMoreThan = 50;

    // When
    List<BigDecimal> results = ExampleParallelStream.getCalculatedPrices(testItems, inventoryCountMoreThan);

    // Then
    assertThat(results).hasSize(6);
}
项目:JRediClients    文件:TimeoutTest.java   
public void testPubSub() throws InterruptedException, ExecutionException {
    RTopic<String> topic = redisson.getTopic("simple");
    topic.addListener(new MessageListener<String>() {
        @Override
        public void onMessage(String channel, String msg) {
            System.out.println("msg: " + msg);
        }
    });
    for (int i = 0; i < 100; i++) {
        Thread.sleep(1000);
        topic.publish("test" + i);
    }
}
项目:GitHub    文件:CompressTask.java   
public static boolean compress(final ImageCompressor imageCompressor, final ImageMedia image, final long maxSize) {
    if (imageCompressor == null || image == null || maxSize <= 0) {
        return false;
    }
    FutureTask<Boolean> task = BoxingExecutor.getInstance().runWorker(new Callable<Boolean>() {
        @Override
        public Boolean call() throws Exception {
            final String path = image.getPath();
            File compressSaveFile = imageCompressor.getCompressOutFile(path);
            File needCompressFile = new File(path);
            if (BoxingFileHelper.isFileValid(compressSaveFile)) {
                image.setCompressPath(compressSaveFile.getAbsolutePath());
                return true;
            }
            if (!BoxingFileHelper.isFileValid(needCompressFile)) {
                return false;
            } else if (image.getSize() < maxSize) {
                image.setCompressPath(path);
                return true;
            } else {
                try {
                    File result = imageCompressor.compress(needCompressFile);
                    boolean suc = BoxingFileHelper.isFileValid(result);
                    image.setCompressPath(suc ? result.getAbsolutePath() : null);
                    return suc;
                } catch (IOException | OutOfMemoryError | NullPointerException | IllegalArgumentException e) {
                    image.setCompressPath(null);
                    BoxingLog.d("image compress fail!");
                }
            }
            return false;
        }
    });
    try {
        return task != null && task.get();
    } catch (InterruptedException | ExecutionException ignore) {
        return false;
    }
}
项目:talk-observing-distributed-systems    文件:KafkaTweetEventRepository.java   
@Override
public void put(Tweet tweet) {
  try {
    final Long key = tweet.id();
    final String value = objectMapper.writeValueAsString(tweet);
    final ProducerRecord<Long, String> producerRecord = new ProducerRecord<>("tweet-events", key, value);
    final RecordMetadata metadata = kafkaProducer.send(producerRecord).get();
    LOGGER.info("Kafka Producer Metadata: {}-{}:{}", metadata.topic(), metadata.partition(), metadata.offset());
  } catch (JsonProcessingException | InterruptedException | ExecutionException e) {
    e.printStackTrace();
  }
}
项目:athena    文件:SimpleFlowRuleStore.java   
@Override
public void onRemoval(RemovalNotification<Integer, SettableFuture<CompletedBatchOperation>> notification) {
    // wrapping in ExecutionException to support Future.get
    if (notification.wasEvicted()) {
        notification.getValue()
                .setException(new ExecutionException("Timed out",
                                                     new TimeoutException()));
    }
}
项目:flux-capacitor-client    文件:CachingRepository.java   
@Override
public T get(Object id) {
    try {
        return cache.get(id, () -> delegate.get(id));
    } catch (ExecutionException e) {
        throw new IllegalStateException("Delegate repository threw an exception while loading " + id, e);
    }
}
项目:swaggy-jenkins    文件:ApiInvoker.java   
public String invokeAPI(String host, String path, String method, List<Pair> queryParams, Object body, Map<String, String> headerParams, Map<String, String> formParams, String contentType, String[] authNames) throws ApiException, InterruptedException, ExecutionException, TimeoutException {
  RequestFuture<String> future = RequestFuture.newFuture();
  Request request = createRequest(host, path, method, queryParams, body, headerParams, formParams, contentType, authNames, future, future);
  if(request != null) {
     mRequestQueue.add(request);
     return future.get(connectionTimeout, TimeUnit.SECONDS);
  } else {
    return "no data";
  }
}