Java 类com.google.common.util.concurrent.UncheckedExecutionException 实例源码

项目:verify-hub    文件:TransactionsConfigProxy.java   
@Timed
public ResourceLocation getAssertionConsumerServiceUri(String entityId, Optional<Integer> assertionConsumerServiceIndex) {

    ImmutableMap<String, String> queryParams = ImmutableMap.of();

    if (assertionConsumerServiceIndex.isPresent()) {
        queryParams = ImmutableMap.of(
                Urls.ConfigUrls.ASSERTION_CONSUMER_SERVICE_INDEX_PARAM,
                assertionConsumerServiceIndex.get().toString());
    }
    final URI uri = getEncodedUri(Urls.ConfigUrls.TRANSACTIONS_ASSERTION_CONSUMER_SERVICE_URI_RESOURCE, queryParams, entityId);
    try {
        return resourceLocation.getUnchecked(uri);
    } catch (UncheckedExecutionException e) {
        Throwables.throwIfUnchecked(e.getCause());
        throw new RuntimeException(e.getCause());
    }
}
项目:drift    文件:SslContextFactory.java   
public ReloadableSslContext get(
        File trustCertificatesFile,
        Optional<File> clientCertificatesFile,
        Optional<File> privateKeyFile,
        Optional<String> privateKeyPassword,
        long sessionCacheSize,
        Duration sessionTimeout,
        List<String> ciphers)
{
    try {
        return cache.getUnchecked(new SslContextConfig(trustCertificatesFile, clientCertificatesFile, privateKeyFile, privateKeyPassword, sessionCacheSize, sessionTimeout, ciphers));
    }
    catch (UncheckedExecutionException | ExecutionError e) {
        throw new RuntimeException("Error initializing SSL context", e.getCause());
    }
}
项目: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());
}
项目:guava-mock    文件:NullCacheTest.java   
public void testGet_runtimeException() {
  final RuntimeException e = new RuntimeException();
  LoadingCache<Object, Object> map = CacheBuilder.newBuilder()
      .maximumSize(0)
      .removalListener(listener)
      .build(exceptionLoader(e));

  try {
    map.getUnchecked(new Object());
    fail();
  } catch (UncheckedExecutionException uee) {
    assertSame(e, uee.getCause());
  }
  assertTrue(listener.isEmpty());
  checkEmpty(map);
}
项目:Elasticsearch    文件:Exceptions.java   
public static Throwable unwrap(@Nonnull Throwable t) {
    int counter = 0;
    Throwable result = t;
    while (result instanceof RemoteTransportException ||
           result instanceof UncheckedExecutionException ||
           result instanceof UncategorizedExecutionException ||
           result instanceof ExecutionException) {
        Throwable cause = result.getCause();
        if (cause == null) {
            return result;
        }
        if (cause == result) {
            return result;
        }
        if (counter > 10) {
            return result;
        }
        counter++;
        result = cause;
    }
    return result;
}
项目:Elasticsearch    文件:HunspellService.java   
/**
 * Scans the hunspell directory and loads all found dictionaries
 */
private void scanAndLoadDictionaries() throws IOException {
    if (Files.isDirectory(hunspellDir)) {
        try (DirectoryStream<Path> stream = Files.newDirectoryStream(hunspellDir)) {
            for (Path file : stream) {
                if (Files.isDirectory(file)) {
                    try (DirectoryStream<Path> inner = Files.newDirectoryStream(hunspellDir.resolve(file), "*.dic")) {
                        if (inner.iterator().hasNext()) { // just making sure it's indeed a dictionary dir
                            try {
                                dictionaries.getUnchecked(file.getFileName().toString());
                            } catch (UncheckedExecutionException e) {
                                // The cache loader throws unchecked exception (see #loadDictionary()),
                                // here we simply report the exception and continue loading the dictionaries
                                logger.error("exception while loading dictionary {}", file.getFileName(), e);
                            }
                        }
                    }
                }
            }
        }
    }
}
项目:grammaticus    文件:GrammaticalLabelSetLoader.java   
/**
 * Return a LabelSet based on the supplied descriptor.
 */
protected GrammaticalLabelSet getSetByDescriptor(GrammaticalLabelSetDescriptor desc) {
    try {
        HumanLanguage fallbackLang = desc.getLanguage().getFallbackLanguage();
        if (fallbackLang != null) {
            // Always load english first.  Note, the cache never includes fallback.
            GrammaticalLabelSet fallback = getSetByDescriptor(desc.getForOtherLanguage(fallbackLang));
            return new GrammaticalLabelSetFallbackImpl(cache.get(desc), fallback);
        } else {
            return cache.get(desc);  // English only!
        }
    }
    catch(UncheckedExecutionException | ExecutionException e) {
        Throwables.propagateIfPossible(e);
        throw new RuntimeException("Unable to load label set for " + desc, e);
    }
}
项目:googles-monorepo-demo    文件: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());
}
项目:googles-monorepo-demo    文件:NullCacheTest.java   
public void testGet_runtimeException() {
  final RuntimeException e = new RuntimeException();
  LoadingCache<Object, Object> map = CacheBuilder.newBuilder()
      .maximumSize(0)
      .removalListener(listener)
      .build(exceptionLoader(e));

  try {
    map.getUnchecked(new Object());
    fail();
  } catch (UncheckedExecutionException uee) {
    assertSame(e, uee.getCause());
  }
  assertTrue(listener.isEmpty());
  checkEmpty(map);
}
项目:dremio-oss    文件:HBaseConnectionManager.java   
public Connection getConnection(HBaseConnectionKey key) {
  checkNotNull(key);
  try {
    Connection conn = connectionCache.get(key);
    if (!isValid(conn)) {
      key.lock(); // invalidate the connection with a per storage plugin lock
      try {
        conn = connectionCache.get(key);
        if (!isValid(conn)) {
          connectionCache.invalidate(key);
          conn = connectionCache.get(key);
        }
      } finally {
        key.unlock();
      }
    }
    return conn;
  } catch (ExecutionException | UncheckedExecutionException e) {
    throw UserException.dataReadError(e.getCause()).build(logger);
  }
}
项目:hashsdn-controller    文件:OnDemandShardStateCache.java   
OnDemandShardState get() throws Exception {
    if (shardActor == null) {
        return OnDemandShardState.newBuilder().build();
    }

    try {
        return ONDEMAND_SHARD_STATE_CACHE.get(shardName, this::retrieveState);
    } catch (ExecutionException | UncheckedExecutionException | ExecutionError e) {
        if (e.getCause() != null) {
            Throwables.propagateIfPossible(e.getCause(), Exception.class);
            throw new RuntimeException("unexpected", e.getCause());
        }

        throw e;
    }
}
项目:endpoints-management-java    文件:IntegrationTest.java   
@Test
public void testAuthenticateWithUnknownIssuer() {
  Authenticator authenticator = createAuthenticator(Clock.SYSTEM, ISSUER, null);
  String authToken = TestUtils.generateAuthToken(
      Optional.<Collection<String>>of(AUDIENCES), Optional.of(EMAIL),
      Optional.of("https://unknown.issuer.com"), Optional.of(SUBJECT),
      RSA_JSON_WEB_KEY);
  when(httpRequest.getHeader(HttpHeaders.AUTHORIZATION)).thenReturn("Bearer " + authToken);
  try {
    authenticator.authenticate(httpRequest, authInfo, SERVICE_NAME);
    fail();
  } catch (UncheckedExecutionException exception) {
    Throwable rootCause = ExceptionUtils.getRootCause(exception);
    assertTrue(rootCause instanceof UnauthenticatedException);
    assertTrue(rootCause.getMessage().contains("the issuer is unknown"));
  }
}
项目:mycore    文件:MCRFileSystemProvider.java   
static MCRFilesystemNode resolvePath(MCRPath path) throws IOException {
    try {
        String ifsid = nodeCache.getUnchecked(path);
        MCRFilesystemNode node = MCRFilesystemNode.getNode(ifsid);
        if (node != null) {
            return node;
        }
        nodeCache.invalidate(path);
        return resolvePath(path);
    } catch (UncheckedExecutionException e) {
        Throwable cause = e.getCause();
        if (cause instanceof NoSuchFileException) {
            throw (NoSuchFileException) cause;
        }
        if (cause instanceof NotDirectoryException) {
            throw (NotDirectoryException) cause;
        }
        if (cause instanceof IOException) {
            throw (IOException) cause;
        }
        throw e;
    }
}
项目:spring4-understanding    文件:GuavaCacheManagerTests.java   
@Test
public void cacheLoaderUseLoadingCache() {
    GuavaCacheManager cm = new GuavaCacheManager("c1");
    cm.setCacheLoader(new CacheLoader<Object, Object>() {
        @Override
        public Object load(Object key) throws Exception {
            if ("ping".equals(key)) {
                return "pong";
            }
            throw new IllegalArgumentException("I only know ping");
        }
    });
    Cache cache1 = cm.getCache("c1");
    Cache.ValueWrapper value = cache1.get("ping");
    assertNotNull(value);
    assertEquals("pong", value.get());

    thrown.expect(UncheckedExecutionException.class);
    thrown.expectMessage("I only know ping");
    assertNull(cache1.get("foo"));
}
项目:meghanada-server    文件:LocationSearcher.java   
private Optional<Location> getFieldLocationFromProject(
    final String fqcn, final String fieldName, final File file) {
  try {
    final Source declaringClassSrc = getSource(project, file);
    final String path = declaringClassSrc.getFile().getPath();
    return declaringClassSrc
        .getClassScopes()
        .stream()
        .map(cs -> getMatchField(cs, fqcn, fieldName))
        .filter(Optional::isPresent)
        .map(
            optional -> {
              final Variable variable = optional.get();
              return new Location(path, variable.range.begin.line, variable.range.begin.column);
            })
        .findFirst();
  } catch (Exception e) {
    throw new UncheckedExecutionException(e);
  }
}
项目:meghanada-server    文件:CachedASMReflector.java   
public List<MemberDescriptor> reflect(final String className) {
  final ClassName cn = new ClassName(className);
  // check type parameter
  final String classWithoutTP = cn.getName();
  final GlobalCache globalCache = GlobalCache.getInstance();
  try {
    final List<MemberDescriptor> members = new ArrayList<>(16);
    List<MemberDescriptor> list = globalCache.getMemberDescriptors(classWithoutTP);
    for (final MemberDescriptor md : list) {
      members.add(md.clone());
    }
    if (cn.hasTypeParameter()) {
      return this.replaceMembers(classWithoutTP, className, members);
    }
    return members;
  } catch (ExecutionException e) {
    throw new UncheckedExecutionException(e);
  }
}
项目:styx    文件:KubernetesGCPServiceAccountSecretManager.java   
String ensureServiceAccountKeySecret(String workflowId, String serviceAccount) {
  final long epoch = epochProvider.epoch(clock.millis(), serviceAccount);
  final String secretName = buildSecretName(serviceAccount, epoch);

  LOG.info("[AUDIT] Workflow {} refers to secret {} storing keys of {}",
      workflowId, secretName, serviceAccount);

  try {
    return serviceAccountSecretCache.get(serviceAccount, () ->
        getOrCreateSecret(workflowId, serviceAccount, epoch, secretName));
  } catch (ExecutionException | UncheckedExecutionException e) {
    final Throwable cause = e.getCause();
    if (cause instanceof InvalidExecutionException) {
      throw (InvalidExecutionException) cause;
    } else if (GcpUtil.isPermissionDenied(cause)) {
      throw new InvalidExecutionException("Permission denied to service account: " + serviceAccount);
    } else if (GcpUtil.isResourceExhausted(cause)) {
      throw new InvalidExecutionException("Maximum number of keys on service account reached: " + serviceAccount);
    } else {
      throw new RuntimeException(e);
    }
  }
}
项目:fiat    文件:FiatPermissionEvaluator.java   
public UserPermission.View getPermission(String username) {
  UserPermission.View view = null;
  if (StringUtils.isEmpty(username)) {
    return null;
  }

  try {
    AtomicBoolean cacheHit = new AtomicBoolean(true);
    view = permissionsCache.get(username, () -> {
      cacheHit.set(false);
      return AuthenticatedRequest.propagate(() -> fiatService.getUserPermission(username)).call();
    });
    log.debug("Fiat permission cache hit: " + cacheHit.get());
  } catch (ExecutionException | UncheckedExecutionException ee) {
    String message = String.format("Cannot get whole user permission for user %s. Cause: %s",
                                   username,
                                   ee.getCause().getMessage());
    if (log.isDebugEnabled()) {
      log.debug(message, ee.getCause());
    } else {
      log.info(message);
    }
  }
  return view;
}
项目:twill    文件:CompositeService.java   
@Override
protected void startUp() throws Exception {
  Throwable failureCause = null;

  for (Service service : services) {
    try {
      service.startAndWait();
    } catch (UncheckedExecutionException e) {
      failureCause = e.getCause();
      break;
    }
  }

  if (failureCause != null) {
    // Stop all running services and then throw the failure exception
    try {
      stopAll();
    } catch (Throwable t) {
      // Ignore the stop error. Just log.
      LOG.warn("Failed when stopping all services on start failure", t);
    }

    Throwables.propagateIfPossible(failureCause, Exception.class);
    throw new RuntimeException(failureCause);
  }
}
项目:endpoints-java    文件:CachingDiscoveryProvider.java   
@Override
public DirectoryList getDirectory(final String root) throws InternalServerErrorException {
  try {
    return directoryByRoot.get(root, new Callable<DirectoryList>() {
      @Override
      public DirectoryList call() throws Exception {
        return delegate.getDirectory(root);
      }
    });
  } catch (ExecutionException | UncheckedExecutionException e) {
    // Cast here so we can maintain specific errors for documentation in throws clauses.
    if (e.getCause() instanceof InternalServerErrorException) {
      throw (InternalServerErrorException) e.getCause();
    } else {
      logger.log(Level.SEVERE, "Could not generate or cache directory", e.getCause());
      throw new InternalServerErrorException("Internal Server Error", e.getCause());
    }
  }
}
项目:endpoints-java    文件:CachingDiscoveryProvider.java   
private <T> T getDiscoveryDoc(Cache<ApiKey, T> cache, String root, String name, String version,
    Callable<T> loader) throws NotFoundException, InternalServerErrorException {
  ApiKey key = new ApiKey(name, version, root);
  try {
    return cache.get(key, loader);
  } catch (ExecutionException | UncheckedExecutionException e) {
    // Cast here so we can maintain specific errors for documentation in throws clauses.
    if (e.getCause() instanceof NotFoundException) {
      throw (NotFoundException) e.getCause();
    } else if (e.getCause() instanceof InternalServerErrorException) {
      throw (InternalServerErrorException) e.getCause();
    } else {
      logger.log(Level.SEVERE, "Could not generate or cache discovery doc", e.getCause());
      throw new InternalServerErrorException("Internal Server Error", e.getCause());
    }
  }
}
项目:monitoring-center    文件:MonitoringCenter.java   
/**
 * Outputs all registered metrics to an SLF4J logger.
 *
 * @param logger an SLF4J logger to output metrics to.
 */
public static void reportMetricsToLogger(final Logger logger) {
    Preconditions.checkNotNull(logger, "logger cannot be null");
    if (!configured.get()) {
        return;
    }
    Preconditions.checkState(slf4jReportersByLoggerNames != null, "slf4jReportersByLoggerNames cannot be null");

    Slf4jReporter slf4jReporter = null;
    try {
         slf4jReporter = slf4jReportersByLoggerNames.get(logger.getName(), new Callable<Slf4jReporter>() {
            @Override
            public Slf4jReporter call() throws Exception {
                return Slf4jReporter.forRegistry(metricRegistry)
                        .convertRatesTo(TimeUnit.SECONDS)
                        .convertDurationsTo(TimeUnit.MICROSECONDS)
                        .outputTo(logger)
                        .build();
            }
        });
    } catch (ExecutionException | UncheckedExecutionException e) {
        throw new RuntimeException("Exception while initializing an SLF4J reporter", e.getCause());
    }

    slf4jReporter.report();
}
项目:drill    文件:HBaseConnectionManager.java   
public Connection getConnection(HBaseConnectionKey key) {
  checkNotNull(key);
  try {
    Connection conn = connectionCache.get(key);
    if (!isValid(conn)) {
      key.lock(); // invalidate the connection with a per storage plugin lock
      try {
        conn = connectionCache.get(key);
        if (!isValid(conn)) {
          connectionCache.invalidate(key);
          conn = connectionCache.get(key);
        }
      } finally {
        key.unlock();
      }
    }
    return conn;
  } catch (ExecutionException | UncheckedExecutionException e) {
    throw UserException.dataReadError(e.getCause()).build(logger);
  }
}
项目:nomulus    文件:ReservedList.java   
private static ImmutableSet<ReservedList> loadReservedLists(
    ImmutableSet<Key<ReservedList>> reservedListKeys) {
  return reservedListKeys
      .stream()
      .map(
          (listKey) -> {
            try {
              return cache.get(listKey.getName());
            } catch (ExecutionException e) {
              throw new UncheckedExecutionException(
                  String.format(
                      "Could not load the reserved list '%s' from the cache", listKey.getName()),
                  e);
            }
          })
      .collect(toImmutableSet());
}
项目:dynamodb-janusgraph-storage-backend    文件:AbstractDynamoDbStore.java   
@Override
public void acquireLock(final StaticBuffer key, final StaticBuffer column, final StaticBuffer expectedValue, final StoreTransaction txh) throws BackendException {
    final DynamoDbStoreTransaction tx = DynamoDbStoreTransaction.getTx(txh);
    final Pair<StaticBuffer, StaticBuffer> keyColumn = Pair.of(key, column);

    final DynamoDbStoreTransaction existing;
    try {
        existing = keyColumnLocalLocks.get(keyColumn, () -> tx);
    } catch (ExecutionException | UncheckedExecutionException | ExecutionError e) {
        throw new TemporaryLockingException("Unable to acquire lock", e);
    }
    if (null != existing && tx != existing) {
        throw new TemporaryLockingException(String.format("tx %s already locked key-column %s when tx %s tried to lock", existing.toString(), keyColumn.toString(), tx.toString()));
    }

    // Titan's locking expects that only the first expectedValue for a given key/column should be used
    tx.putKeyColumnOnlyIfItIsNotYetChangedInTx(this, key, column, expectedValue);
}
项目:cloud-config    文件:SequenceGeneratorFactoryBean.java   
@Override
public String next(String seqName) throws Exception {
    String routingKey = resolver.get().orNull();
    if( routingKey!=null ) {
        logger.debug("Routing sequence generator lookup key is '{}'", routingKey);
    } else {
        logger.warn("Routing sequence generator lookup key cannot be found in current context!");
        routingKey = "__absent_tenant__";
    }
    try {
        return localResourceStore.getUnchecked(routingKey).next(seqName);
    } catch (UncheckedExecutionException e) {
        Throwable cause = e.getCause();
        throw new IllegalStateException("Cannot determine target DataSource for lookup key [" + routingKey + "]", cause);
    }
}
项目:metasfresh    文件:CacheIntrospectionException.java   
public static final CacheIntrospectionException wrapIfNeeded(final Throwable e)
{
    if (e == null)
    {
        return new CacheIntrospectionException("Unknown cache exception");
    }
    else if (e instanceof CacheIntrospectionException)
    {
        return (CacheIntrospectionException)e;
    }
    else if ((e instanceof InvocationTargetException) && (e.getCause() != null))
    {
        return wrapIfNeeded(e.getCause());
    }
    else if ((e instanceof UncheckedExecutionException) && (e.getCause() != null))
    {
        return wrapIfNeeded(e.getCause());
    }
    else
    {
        return new CacheIntrospectionException(e);
    }
}
项目:metasfresh    文件:ServicesException.java   
public static final ServicesException wrapIfNeeded(final Throwable e)
{
    if (e == null)
    {
        return new ServicesException("Unknown service exception");
    }
    else if (e instanceof ServicesException)
    {
        return (ServicesException)e;
    }
    else if ((e instanceof InvocationTargetException) && (e.getCause() != null))
    {
        return wrapIfNeeded(e.getCause());
    }
    else if ((e instanceof UncheckedExecutionException) && (e.getCause() != null))
    {
        return wrapIfNeeded(e.getCause());
    }
    else
    {
        return new ServicesException(e);
    }
}
项目:guava-libraries    文件: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());
}
项目:guava-libraries    文件:NullCacheTest.java   
public void testGet_runtimeException() {
  final RuntimeException e = new RuntimeException();
  LoadingCache<Object, Object> map = CacheBuilder.newBuilder()
      .maximumSize(0)
      .removalListener(listener)
      .build(exceptionLoader(e));

  try {
    map.getUnchecked(new Object());
    fail();
  } catch (UncheckedExecutionException uee) {
    assertSame(e, uee.getCause());
  }
  assertTrue(listener.isEmpty());
  checkEmpty(map);
}
项目:cloud-bigtable-client    文件:BigtableAdmin.java   
@Override
public HTableDescriptor getTableDescriptor(TableName tableName)
    throws TableNotFoundException, IOException {
  if (tableName == null) {
    return null;
  }

  String bigtableTableName = TableMetadataSetter.getBigtableName(tableName, options);
  GetTableRequest request = GetTableRequest.newBuilder().setName(bigtableTableName).build();

  try {
    return tableAdapter.adapt(bigtableAdminClient.getTable(request));
  } catch (UncheckedExecutionException e) {
    if (e.getCause() != null && e.getCause() instanceof OperationRuntimeException) {
      Status status = ((OperationRuntimeException) e.getCause()).getStatus();
      if (status.getCode() == Status.NOT_FOUND.getCode()) {
        throw new TableNotFoundException(tableName);
      }
    }
    throw new IOException("Failed to getTableDescriptor() on " + tableName, e);
  } catch (Throwable throwable) {
    throw new IOException("Failed to getTableDescriptor() on " + tableName, throwable);
  }
}
项目:cloud-bigtable-client    文件:TestClusterAPI.java   
private Cluster getCluster(BigtableClusterAdminClient client, String clusterName) {
  GetClusterRequest request = GetClusterRequest.newBuilder().setName(clusterName).build();
  try {
    Cluster response = client.getCluster(request);
    return response;
  } catch (UncheckedExecutionException e) {
    if (e.getCause() != null && e.getCause() instanceof OperationRuntimeException) {
      Status status = ((OperationRuntimeException) e.getCause()).getStatus();
      if (status.getCode() == Status.NOT_FOUND.getCode()) {
        return null;
      }
    }
    e.printStackTrace();
    throw e;
  }
}
项目:presto    文件:FunctionRegistry.java   
public WindowFunctionSupplier getWindowFunctionImplementation(Signature signature)
{
    checkArgument(signature.getKind() == WINDOW || signature.getKind() == AGGREGATE, "%s is not a window function", signature);
    checkArgument(signature.getTypeParameterRequirements().isEmpty(), "%s has unbound type parameters", signature);
    Iterable<SqlFunction> candidates = functions.get(QualifiedName.of(signature.getName()));
    // search for exact match
    for (SqlFunction operator : candidates) {
        Type returnType = typeManager.getType(signature.getReturnType());
        List<Type> argumentTypes = resolveTypes(signature.getArgumentTypes(), typeManager);
        Map<String, Type> boundTypeParameters = operator.getSignature().bindTypeParameters(returnType, argumentTypes, false, typeManager);
        if (boundTypeParameters != null) {
            try {
                return specializedWindowCache.getUnchecked(new SpecializedFunctionKey(operator, boundTypeParameters, signature.getArgumentTypes().size()));
            }
            catch (UncheckedExecutionException e) {
                throw Throwables.propagate(e.getCause());
            }
        }
    }
    throw new PrestoException(FUNCTION_IMPLEMENTATION_MISSING, format("%s not found", signature));
}
项目:presto    文件:FunctionRegistry.java   
public InternalAggregationFunction getAggregateFunctionImplementation(Signature signature)
{
    checkArgument(signature.getKind() == AGGREGATE || signature.getKind() == APPROXIMATE_AGGREGATE, "%s is not an aggregate function", signature);
    checkArgument(signature.getTypeParameterRequirements().isEmpty(), "%s has unbound type parameters", signature);
    Iterable<SqlFunction> candidates = functions.get(QualifiedName.of(signature.getName()));
    // search for exact match
    for (SqlFunction operator : candidates) {
        Type returnType = typeManager.getType(signature.getReturnType());
        List<Type> argumentTypes = resolveTypes(signature.getArgumentTypes(), typeManager);
        Map<String, Type> boundTypeParameters = operator.getSignature().bindTypeParameters(returnType, argumentTypes, false, typeManager);
        if (boundTypeParameters != null) {
            try {
                return specializedAggregationCache.getUnchecked(new SpecializedFunctionKey(operator, boundTypeParameters, signature.getArgumentTypes().size()));
            }
            catch (UncheckedExecutionException e) {
                throw Throwables.propagate(e.getCause());
            }
        }
    }
    throw new PrestoException(FUNCTION_IMPLEMENTATION_MISSING, format("%s not found", signature));
}
项目:presto    文件:JoinProbeCompiler.java   
public OperatorFactory compileJoinOperatorFactory(int operatorId,
        PlanNodeId planNodeId,
        LookupSourceSupplier lookupSourceSupplier,
        List<? extends Type> probeTypes,
        List<Integer> probeJoinChannel,
        Optional<Integer> probeHashChannel,
        JoinType joinType)
{
    try {
        HashJoinOperatorFactoryFactory operatorFactoryFactory = joinProbeFactories.get(new JoinOperatorCacheKey(probeTypes, probeJoinChannel, probeHashChannel, joinType));
        return operatorFactoryFactory.createHashJoinOperatorFactory(operatorId, planNodeId, lookupSourceSupplier, probeTypes, probeJoinChannel, joinType);
    }
    catch (ExecutionException | UncheckedExecutionException | ExecutionError e) {
        throw Throwables.propagate(e.getCause());
    }
}
项目:presto    文件:FunctionAssertions.java   
private OperatorFactory compileFilterWithNoInputColumns(Expression filter, ExpressionCompiler compiler)
{
    filter = ExpressionTreeRewriter.rewriteWith(new SymbolToInputRewriter(ImmutableMap.<Symbol, Integer>of()), filter);

    IdentityHashMap<Expression, Type> expressionTypes = getExpressionTypesFromInput(TEST_SESSION, metadata, SQL_PARSER, INPUT_TYPES, ImmutableList.of(filter));

    try {
        PageProcessor processor = compiler.compilePageProcessor(toRowExpression(filter, expressionTypes), ImmutableList.of());

        return new FilterAndProjectOperator.FilterAndProjectOperatorFactory(0, new PlanNodeId("test"), processor, ImmutableList.<Type>of());
    }
    catch (Throwable e) {
        if (e instanceof UncheckedExecutionException) {
            e = e.getCause();
        }
        throw new RuntimeException("Error compiling " + filter + ": " + e.getMessage(), e);
    }
}
项目:presto    文件:FunctionAssertions.java   
private OperatorFactory compileFilterProject(Expression filter, Expression projection, ExpressionCompiler compiler)
{
    filter = ExpressionTreeRewriter.rewriteWith(new SymbolToInputRewriter(INPUT_MAPPING), filter);
    projection = ExpressionTreeRewriter.rewriteWith(new SymbolToInputRewriter(INPUT_MAPPING), projection);

    IdentityHashMap<Expression, Type> expressionTypes = getExpressionTypesFromInput(TEST_SESSION, metadata,
            SQL_PARSER, INPUT_TYPES, ImmutableList.of(filter, projection));

    try {
        List<RowExpression> projections = ImmutableList.of(toRowExpression(projection, expressionTypes));
        PageProcessor processor = compiler.compilePageProcessor(toRowExpression(filter, expressionTypes), projections);

        return new FilterAndProjectOperator.FilterAndProjectOperatorFactory(0, new PlanNodeId("test"), processor, ImmutableList.of(expressionTypes.get(projection)));
    }
    catch (Throwable e) {
        if (e instanceof UncheckedExecutionException) {
            e = e.getCause();
        }
        throw new RuntimeException("Error compiling " + projection + ": " + e.getMessage(), e);
    }
}
项目:metadict    文件:CachedLinearExecutionStrategy.java   
private void executeQueryStep(List<QueryStepResult> queryResults, AbstractQueryStep currentQueryStep) {
    QueryStepResult queryStepResult = this.queryStepResultCache.getIfPresent(currentQueryStep);

    try {
        if (queryStepResult == null) {
            LOGGER.debug("Local cache miss on query step {}", currentQueryStep);
            queryStepResult = this.queryStepResultCache.get(currentQueryStep, () -> queryStorageService(currentQueryStep));
        } else {
            LOGGER.debug("Local cache hit on query step {}", currentQueryStep);
        }
    } catch (ExecutionException | UncheckedExecutionException e) {
        LOGGER.error("Query step {} failed", currentQueryStep, e);
        queryStepResult = new QueryStepResultBuilder()
                .setFailedStep(true)
                .setQueryStep(currentQueryStep)
                .setErrorMessage(e.getMessage())
                .setEngineQueryResult(ImmutableBilingualQueryResult.EMPTY_QUERY_RESULT)
                .build();
    }
    if (queryStepResult != null && queryStepResult.isFailedStep()) {
        this.queryStepResultCache.invalidate(currentQueryStep);
    }
    queryResults.add(queryStepResult);
}
项目:datacollector    文件:HBaseUtil.java   
public static void handleHBaseException(
    Throwable t,
    Iterator<Record> records,
    ErrorRecordHandler errorRecordHandler
) throws StageException {
  Throwable cause = t;

  // Drill down to root cause
  while((cause instanceof UncheckedExecutionException || cause instanceof UndeclaredThrowableException ||
      cause instanceof ExecutionException) && cause.getCause() != null) {
    cause = cause.getCause();
  }

  // Column is null or No such Column Family exception
  if(cause instanceof NullPointerException || cause instanceof NoSuchColumnFamilyException) {
    while(records.hasNext()) {
      Record record = records.next();
      errorRecordHandler.onError(new OnRecordErrorException(record, Errors.HBASE_37, cause));
    }
  } else {
    LOG.error(Errors.HBASE_36.getMessage(), cause.toString(), cause);
    throw new StageException(Errors.HBASE_36, cause.toString(), cause);
  }
}
项目:metron    文件:BaseStellarProcessor.java   
/**
 * Parses and evaluates the given Stellar expression, {@code rule}.
 * @param rule The Stellar expression to parse and evaluate.
 * @param variableResolver The {@link VariableResolver} to determine values of variables used in the Stellar expression, {@code rule}.
 * @param functionResolver The {@link FunctionResolver} to determine values of functions used in the Stellar expression, {@code rule}.
 * @param context The context used during validation.
 * @return The value of the evaluated Stellar expression, {@code rule}.
 */
public T parse(final String rule, final VariableResolver variableResolver, final FunctionResolver functionResolver, final Context context) {
  StellarCompiler.Expression expression = null;
  if (rule == null || isEmpty(rule.trim())) {
    return null;
  }
  if(context.getActivityType() == null) {
    context.setActivityType(ActivityType.PARSE_ACTIVITY);
  }
  try {
    expression = expressionCache.get(rule, () -> compile(rule));
  } catch (ExecutionException|UncheckedExecutionException e) {
    throw new ParseException("Unable to parse: " + rule + " due to: " + e.getMessage(), e);
  }
  try {
    return clazz.cast(expression
        .apply(new StellarCompiler.ExpressionState(context, functionResolver, variableResolver)));
  }finally {
      // always reset the activity type
      context.setActivityType(null);
  }
}