@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()); } }
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()); } }
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()); }
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); }
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; }
/** * 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); } } } } } } } }
/** * 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); } }
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); } }
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; } }
@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")); } }
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; } }
@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")); }
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); } }
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); } }
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); } } }
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; }
@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); } }
@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()); } } }
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()); } } }
/** * 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(); }
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()); }
@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); }
@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); } }
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); } }
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); } }
@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); } }
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; } }
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)); }
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)); }
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()); } }
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); } }
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); } }
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); }
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); } }
/** * 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); } }