com.google.common.util.concurrent.UncheckedExecutionException Java Examples

The following examples show how to use com.google.common.util.concurrent.UncheckedExecutionException. 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: GrammaticalLabelSetLoader.java    From grammaticus with BSD 3-Clause "New" or "Revised" License 8 votes vote down vote up
/**
 * 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.throwIfUnchecked(e);
        throw new RuntimeException("Unable to load label set for " + desc, e);
    }
}
 
Example #2
Source File: MicroserviceInstanceCache.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
public static MicroserviceInstance getOrCreate(String serviceId, String instanceId) {
  try {
    String key = String.format("%s@%s", serviceId, instanceId);
    return instances.get(key, new Callable<MicroserviceInstance>() {

      @Override
      public MicroserviceInstance call() {
        MicroserviceInstance instance = DiscoveryManager.INSTANCE.getMicroserviceInstance(serviceId, instanceId);
        if (instance == null) {
          throw new IllegalArgumentException("instance id not exists.");
        }
        return instance;
      }
    });
  } catch (ExecutionException | UncheckedExecutionException e) {
    logger.error("get microservice instance from cache failed, {}, {}", String.format("%s@%s", serviceId, instanceId),
        e.getMessage());
    return null;
  }
}
 
Example #3
Source File: CachedASMReflector.java    From meghanada-server with GNU General Public License v3.0 6 votes vote down vote up
public List<MemberDescriptor> reflect(String className) {
  ClassName cn = new ClassName(className);
  // check type parameter
  String classWithoutTP = cn.getName();
  GlobalCache globalCache = GlobalCache.getInstance();
  try {
    List<MemberDescriptor> members = new ArrayList<>(16);
    List<MemberDescriptor> list = globalCache.getMemberDescriptors(classWithoutTP);
    if (!list.isEmpty()) {
      // TelemetryUtils.recordAutocompleteStat(classWithoutTP);
    }
    for (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);
  }
}
 
Example #4
Source File: ThriftHiveMetastore.java    From presto with Apache License 2.0 6 votes vote down vote up
private ThriftMetastoreClient createMetastoreClient(HiveIdentity identity)
        throws TException
{
    if (!impersonationEnabled) {
        return createMetastoreClient();
    }

    String username = identity.getUsername().orElseThrow(() -> new IllegalStateException("End-user name should exist when metastore impersonation is enabled"));
    if (authenticationEnabled) {
        String delegationToken;
        try {
            delegationToken = delegationTokenCache.getUnchecked(username);
        }
        catch (UncheckedExecutionException e) {
            throwIfInstanceOf(e.getCause(), PrestoException.class);
            throw e;
        }
        return clientProvider.createMetastoreClient(Optional.of(delegationToken));
    }

    ThriftMetastoreClient client = createMetastoreClient();
    setMetastoreUserOrClose(client, username);
    return client;
}
 
Example #5
Source File: CachingKeyResolverTest.java    From azure-keyvault-java with MIT License 6 votes vote down vote up
@Test
public void KeyVault_CachingKeyResolverThrows()
{
    IKeyResolver mockedKeyResolver = mock(IKeyResolver.class);
    CachingKeyResolver resolver = new CachingKeyResolver(10, mockedKeyResolver);

    // First throw exception and for the second call return a value
    when(mockedKeyResolver.resolveKeyAsync(keyId))
        .thenThrow(new RuntimeException("test"))
        .thenReturn(ikeyAsync);

    try {
        resolver.resolveKeyAsync(keyId);
        fail("Should have thrown an exception.");
    }
    catch (UncheckedExecutionException e) {
        assertTrue("RuntimeException is expected.", e.getCause() instanceof RuntimeException);
    }

    resolver.resolveKeyAsync(keyId);
    resolver.resolveKeyAsync(keyId);

    verify(mockedKeyResolver, times(2)).resolveKeyAsync(keyId);
}
 
Example #6
Source File: ServiceOrchestratorLoader.java    From yanwte2 with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
public static <T extends Function<?, ?>> T getOrchestratorByServiceType(Class<T> serviceType) {
    checkNotNull(serviceType);
    checkArgument(
            serviceType.isInterface(),
            "Service type is required to be an interface: " + serviceType.getName());
    checkArgument(
            Function.class.isAssignableFrom(serviceType),
            "Service type is required to be a function: " + serviceType.getName());

    try {
        ServiceTypeIndexEntry entry =
                serviceTypeIndex.get(
                        serviceType, () -> createServiceTypeIndexEntry(serviceType));
        return (T) entry.proxy;
    } catch (UncheckedExecutionException | ExecutionException e) {
        Throwables.throwIfUnchecked(e.getCause());
        throw new RuntimeException(e.getCause());
    }
}
 
Example #7
Source File: SheetsClient.java    From presto with Apache License 2.0 6 votes vote down vote up
public Set<String> getTableNames()
{
    ImmutableSet.Builder<String> tables = ImmutableSet.builder();
    try {
        List<List<Object>> tableMetadata = sheetDataCache.getUnchecked(metadataSheetId);
        for (int i = 1; i < tableMetadata.size(); i++) {
            if (tableMetadata.get(i).size() > 0) {
                tables.add(String.valueOf(tableMetadata.get(i).get(0)));
            }
        }
        return tables.build();
    }
    catch (UncheckedExecutionException e) {
        throwIfInstanceOf(e.getCause(), PrestoException.class);
        throw new PrestoException(SHEETS_METASTORE_ERROR, e);
    }
}
 
Example #8
Source File: SymmetricCacheService.java    From MaxKey with Apache License 2.0 6 votes vote down vote up
/**
 * Create a symmetric signing and validation service for the given client
 * 
 * @param client
 * @return
 */
public JwtSigningAndValidationService getSymmetricValidtor(ClientDetails client) {

	if (client == null) {
		logger.error("Couldn't create symmetric validator for null client");
		return null;
	}

	if (Strings.isNullOrEmpty(client.getClientSecret())) {
		logger.error("Couldn't create symmetric validator for client " + client.getClientId() + " without a client secret");
		return null;
	}

	try {
		return validators.get(client.getClientSecret());
	} catch (UncheckedExecutionException ue) {
		logger.error("Problem loading client validator", ue);
		return null;
	} catch (ExecutionException e) {
		logger.error("Problem loading client validator", e);
		return null;
	}

}
 
Example #9
Source File: DataExtensions.java    From yanwte2 with Apache License 2.0 6 votes vote down vote up
public static void put(Object extensibleData, String providerPackage, Object dataExtension) {
    checkNotNull(extensibleData);
    checkNotNull(providerPackage);

    try {
        ConcurrentHashMap<String, Object> secLevelMap =
                cache.get(extensibleData, ConcurrentHashMap::new);

        if (dataExtension != null) {
            secLevelMap.put(providerPackage, dataExtension);
        } else {
            secLevelMap.put(providerPackage, NULL_DATA_EXTENSION);
        }
    } catch (UncheckedExecutionException | ExecutionException e) {
        Throwables.throwIfUnchecked(e.getCause());
        throw new RuntimeException(e.getCause());
    }
}
 
Example #10
Source File: ValuePredicateTest.java    From yare with MIT License 6 votes vote down vote up
@Test
void shouldFailWithValuePlaceholderNotResolvedToBoolean() {
    // given
    Rule rule = RuleDsl.ruleBuilder()
            .name("Rule match based on isValid fact field")
            .fact("fact", NamedFact.class)
            .predicate(
                    value("${fact.name}")
            )
            .action("collect",
                    param("context", value("${ctx}")),
                    param("fact", value("${fact}"))
            )
            .build();

    RulesEngine engine = new RulesEngineBuilder()
            .withRulesRepository(uri -> Collections.singletonList(rule))
            .withActionMapping("collect", method(this, a -> a.collect(null, null)))
            .build();
    RuleSession session = engine.createSession("uri");

    // when / then
    assertThatThrownBy(() -> session.execute(null, Collections.emptyList()))
            .isExactlyInstanceOf(UncheckedExecutionException.class)
            .hasMessage("java.lang.IllegalArgumentException: Only references of boolean type can be translated directly to predicate");
}
 
Example #11
Source File: AbstractSkylarkFileParser.java    From buck with Apache License 2.0 6 votes vote down vote up
/** Loads all extensions identified by corresponding {@link SkylarkImport}s. */
protected ImmutableList<ExtensionData> loadExtensions(
    Label containingLabel, ImmutableList<SkylarkImport> skylarkImports)
    throws BuildFileParseException, IOException, InterruptedException {
  Set<SkylarkImport> processed = new HashSet<>(skylarkImports.size());
  ImmutableList.Builder<ExtensionData> extensions =
      ImmutableList.builderWithExpectedSize(skylarkImports.size());
  // foreach is not used to avoid iterator overhead
  for (int i = 0; i < skylarkImports.size(); ++i) {
    SkylarkImport skylarkImport = skylarkImports.get(i);
    // sometimes users include the same extension multiple times...
    if (!processed.add(skylarkImport)) continue;
    try {
      extensions.add(loadExtension(ImmutableLoadImport.of(containingLabel, skylarkImport)));
    } catch (UncheckedExecutionException e) {
      propagateRootCause(e);
    }
  }
  return extensions.build();
}
 
Example #12
Source File: CacheLoadingTest.java    From caffeine with Apache License 2.0 6 votes vote down vote up
public void testBulkLoadUncheckedException() throws ExecutionException {
  Exception e = new RuntimeException();
  CacheLoader<Object, Object> loader = exceptionLoader(e);
  LoadingCache<Object, Object> cache = CaffeinatedGuava.build(Caffeine.newBuilder()
      .recordStats(), 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());
}
 
Example #13
Source File: ReservedList.java    From nomulus with Apache License 2.0 6 votes vote down vote up
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());
}
 
Example #14
Source File: Writes.java    From bazel-buildfarm with Apache License 2.0 6 votes vote down vote up
public Write get(Digest digest, UUID uuid, RequestMetadata requestMetadata)
    throws ExcessiveWriteSizeException {
  if (digest.getSizeBytes() == 0) {
    return new CompleteWrite(0);
  }
  BlobWriteKey key =
      BlobWriteKey.newBuilder().setDigest(digest).setIdentifier(uuid.toString()).build();
  try {
    return new InvalidatingWrite(
        blobWriteInstances.get(key).getBlobWrite(digest, uuid, requestMetadata),
        () -> blobWriteInstances.invalidate(key));
  } catch (ExecutionException e) {
    Throwable cause = e.getCause();
    throwIfInstanceOf(cause, RuntimeException.class);
    throw new UncheckedExecutionException(cause);
  }
}
 
Example #15
Source File: PartitionedDatasetWriter.java    From kite with Apache License 2.0 6 votes vote down vote up
@Override
public void write(E entity) {
  Preconditions.checkState(state.equals(ReaderWriterState.OPEN),
      "Attempt to write to a writer in state:%s", state);

  accessor.keyFor(entity, provided, reusedKey);

  DatasetWriter<E> writer = cachedWriters.getIfPresent(reusedKey);
  if (writer == null) {
    // avoid checking in every whether the entity belongs in the view by only
    // checking when a new writer is created
    Preconditions.checkArgument(view.includes(entity),
        "View %s does not include entity %s", view, entity);
    // get a new key because it is stored in the cache
    StorageKey key = StorageKey.copy(reusedKey);
    try {
      writer = cachedWriters.getUnchecked(key);
    } catch (UncheckedExecutionException ex) {
      throw new IllegalArgumentException(
          "Problem creating view for entity: " + entity, ex.getCause());
    }
  }

  writer.write(entity);
}
 
Example #16
Source File: GuavaCacheManagerTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@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"));
}
 
Example #17
Source File: InMemoryTopology.java    From incubator-gobblin with Apache License 2.0 6 votes vote down vote up
public Collection<ConfigKeyPath> getImportedBy(ConfigKeyPath configKey, Optional<Config> runtimeConfig) {
  if (this.fullImportedByMap != null) {
    return this.fullImportedByMap.get(configKey);
  }

  try {
    return this.ownImportedByMap.get(configKey, () -> this.fallback.getImportedBy(configKey, runtimeConfig));
  } catch (UncheckedExecutionException exc) {
    if (exc.getCause() instanceof UnsupportedOperationException) {
      computeImportedByMap(runtimeConfig);
      return getImportedBy(configKey, runtimeConfig);
    } else {
      throw new RuntimeException(exc);
    }
  } catch (ExecutionException ee) {
    throw new RuntimeException(ee);
  }
}
 
Example #18
Source File: ConnectionManager.java    From pxf with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a connection to the target database either directly from the DriverManager or
 * from a Hikari connection pool that manages connections.
 * @param server configuration server
 * @param jdbcUrl JDBC url of the target database
 * @param connectionConfiguration connection configuration properties
 * @param isPoolEnabled true if the connection pool is enabled, false otherwise
 * @param poolConfiguration pool configuration properties
 * @return connection instance
 * @throws SQLException if connection can not be obtained
 */
public Connection getConnection(String server, String jdbcUrl, Properties connectionConfiguration, boolean isPoolEnabled, Properties poolConfiguration, String qualifier) throws SQLException {

    Connection result;
    if (!isPoolEnabled) {
        LOG.debug("Requesting DriverManager.getConnection for server={}", server);
        result = DriverManager.getConnection(jdbcUrl, connectionConfiguration);
    } else {

        PoolDescriptor poolDescriptor = new PoolDescriptor(server, jdbcUrl, connectionConfiguration, poolConfiguration, qualifier);

        DataSource dataSource;
        try {
            LOG.debug("Requesting datasource for server={} and {}", server, poolDescriptor);
            dataSource = dataSources.getUnchecked(poolDescriptor);
            LOG.debug("Obtained datasource {} for server={} and {}", dataSource.hashCode(), server, poolDescriptor);
        } catch (UncheckedExecutionException e) {
            Throwable cause = e.getCause() != null ? e.getCause() : e;
            throw new SQLException(String.format("Could not obtain datasource for server %s and %s : %s", server, poolDescriptor, cause.getMessage()), cause);
        }
        result = dataSource.getConnection();
    }
    LOG.debug("Returning JDBC connection {} for server={}", result, server);

    return result;
}
 
Example #19
Source File: HunspellService.java    From Elasticsearch with Apache License 2.0 6 votes vote down vote up
/**
 * 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);
                            }
                        }
                    }
                }
            }
        }
    }
}
 
Example #20
Source File: CompositeService.java    From twill with Apache License 2.0 6 votes vote down vote up
@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);
  }
}
 
Example #21
Source File: ApplicationSerializer.java    From vespa with Apache License 2.0 5 votes vote down vote up
public Application fromSlime(byte[] data) {
    var key = Hashing.sipHash24().hashBytes(data).asLong();
    try {
        return cache.get(key, () -> fromSlime(SlimeUtils.jsonToSlime(data)));
    } catch (ExecutionException e) {
        throw new UncheckedExecutionException(e);
    }
}
 
Example #22
Source File: TestHdfsSystemConsumer.java    From samza with Apache License 2.0 5 votes vote down vote up
@Test
public void testEmptyStagingDirectory() throws Exception {
  Map<String, String> configMap = new HashMap<>();
  configMap.put(String.format(HdfsConfig.CONSUMER_PARTITIONER_WHITELIST(), SYSTEM_NAME), ".*avro");
  Config config = new MapConfig(configMap);
  HdfsSystemFactory systemFactory = new HdfsSystemFactory();

  // create admin and do partitioning
  HdfsSystemAdmin systemAdmin = systemFactory.getAdmin(SYSTEM_NAME, config);
  String stream = WORKING_DIRECTORY;
  Set<String> streamNames = new HashSet<>();
  streamNames.add(stream);
  generateAvroDataFiles();
  Map<String, SystemStreamMetadata> streamMetadataMap = systemAdmin.getSystemStreamMetadata(streamNames);
  SystemStreamMetadata systemStreamMetadata = streamMetadataMap.get(stream);
  Assert.assertEquals(NUM_FILES, systemStreamMetadata.getSystemStreamPartitionMetadata().size());

  // create consumer and read from files
  HdfsSystemConsumer systemConsumer = systemFactory.getConsumer(SYSTEM_NAME, config, new NoOpMetricsRegistry());
  Partition partition = new Partition(0);
  SystemStreamPartition ssp = new SystemStreamPartition(SYSTEM_NAME, stream, partition);
  try {
    systemConsumer.register(ssp, "0");
    Assert.fail("Empty staging directory should fail system consumer");
  } catch (UncheckedExecutionException e) {
    Assert.assertTrue(e.getCause() instanceof SamzaException);
  }
}
 
Example #23
Source File: AbstractLoadingCache.java    From codebuff with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Override
    public V getUnchecked(K key) {
try {
        return get(key);
} catch (ExecutionException e) {
  throw new UncheckedExecutionException(e.getCause());
}
    }
 
Example #24
Source File: Writes.java    From bazel-buildfarm with Apache License 2.0 5 votes vote down vote up
private Write get(BlobWriteKey key) {
  try {
    return blobWrites.get(key, () -> newWrite(key));
  } catch (ExecutionException e) {
    throw new UncheckedExecutionException(e);
  }
}
 
Example #25
Source File: ImportTraverser.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
/**
 * Due to recursive nature of algorithm, we may end up with multiple layers of exceptions. Unpack them.
 */
private RuntimeException unpackExecutionException(Throwable exc) {
  while (exc instanceof ExecutionException || exc instanceof UncheckedExecutionException) {
    exc = exc.getCause();
  }
  return Throwables.propagate(exc);
}
 
Example #26
Source File: Concurrent.java    From nomulus with Apache License 2.0 5 votes vote down vote up
/**
 * Processes {@code items} in parallel using {@code funk}, with the specified number of threads.
 *
 * <p>If the maxThreadCount or the number of items is less than 2, will use a non-concurrent
 * transform.
 *
 * <p><b>Note:</b> Spawned threads will inherit the same namespace.
 *
 * @throws UncheckedExecutionException to wrap the exception thrown by {@code funk}. This will
 *     only contain the exception information for the first exception thrown.
 * @return transformed {@code items} in the same order.
 */
public static <A, B> ImmutableList<B> transform(
    Collection<A> items,
    int maxThreadCount,
    final Function<A, B> funk) {
  checkNotNull(funk);
  checkNotNull(items);
  int threadCount = max(1, min(items.size(), maxThreadCount));
  ThreadFactory threadFactory = threadCount > 1 ? currentRequestThreadFactory() : null;
  if (threadFactory == null) {
    // Fall back to non-concurrent transform if we only want 1 thread, or if we can't get an App
    // Engine thread factory (most likely caused by hitting this code from a command-line tool).
    // Default Java system threads are not compatible with code that needs to interact with App
    // Engine (such as Objectify), which we often have in funk when calling
    // Concurrent.transform(). For more info see: http://stackoverflow.com/questions/15976406
    return items.stream().map(funk).collect(toImmutableList());
  }
  ExecutorService executor = newFixedThreadPool(threadCount, threadFactory);
  try {
    List<Future<B>> futures = new ArrayList<>();
    for (final A item : items) {
      futures.add(executor.submit(() -> funk.apply(item)));
    }
    ImmutableList.Builder<B> results = new ImmutableList.Builder<>();
    for (Future<B> future : futures) {
      try {
        results.add(Uninterruptibles.getUninterruptibly(future));
      } catch (ExecutionException e) {
        throw new UncheckedExecutionException(e.getCause());
      }
    }
    return results.build();
  } finally {
    executor.shutdownNow();
  }
}
 
Example #27
Source File: RuleKeyTest.java    From buck with Apache License 2.0 5 votes vote down vote up
@Test(expected = UncheckedExecutionException.class)
public void badUseOfAddValueMethodsToRuleKey() {
  java.util.logging.Logger.getGlobal().addHandler(new ConsoleHandler());
  SourcePathRuleFinder pathRuleFinder = new TestActionGraphBuilder();
  createBuilder(pathRuleFinder)
      .setReflectively("value", (BadUseOfAddValueMethodsToRuleKey) () -> "")
      .build(RuleKey::new);
}
 
Example #28
Source File: CachingSqlStatisticProvider.java    From calcite with Apache License 2.0 5 votes vote down vote up
public boolean isKey(RelOptTable table, List<Integer> columns) {
  try {
    final ImmutableList<Object> key =
        ImmutableList.of("isKey", table.getQualifiedName(),
            ImmutableIntList.copyOf(columns));
    return (Boolean) cache.get(key, () -> provider.isKey(table, columns));
  } catch (UncheckedExecutionException | ExecutionException e) {
    Util.throwIfUnchecked(e.getCause());
    throw new RuntimeException(e.getCause());
  }
}
 
Example #29
Source File: BatchedAuthCache.java    From apiman-plugins with Apache License 2.0 5 votes vote down vote up
public int decrement(BackendConfiguration config, ApiRequest req, Object... elems) {
    try {
        int val = lruCache.get(getCacheKey(config, req, elems), () -> SENTINEL).getAndDecrement();
        if (val <= 0) {
            lruCache.invalidate(getCacheKey(config, req, elems));
        }
        return val;
    } catch (ExecutionException e) {
        throw new UncheckedExecutionException(e);
    }
}
 
Example #30
Source File: SslContextFactory.java    From drift with Apache License 2.0 5 votes vote down vote up
public ReloadableSslContext get(SslContextParameters sslContextParameters)
{
    try {
        return cache.getUnchecked(sslContextParameters);
    }
    catch (UncheckedExecutionException | ExecutionError e) {
        throw new RuntimeException("Error initializing SSL context", e.getCause());
    }
}