/** * Execute and validate a Stellar expression. * * <p>This is intended for use while unit testing Stellar expressions. This ensures that the expression * validates successfully and produces a result that can be serialized correctly. * * @param expression The expression to execute. * @param variables The variables to expose to the expression. * @return The result of executing the expression. */ public static Object run(String expression, Map<String, Object> variables) { return run(expression, variables, Context.EMPTY_CONTEXT()); }
public Optional<Object> getCapability(Enum<?> capability) { return getCapability(capability, true); }
@Override public synchronized void initialize(Context context) { try { Optional<Object> clientOptional = context.getCapability(Context.Capabilities.ZOOKEEPER_CLIENT); CuratorFramework client = null; if (clientOptional.isPresent() && clientOptional.get() instanceof CuratorFramework) { client = (CuratorFramework) clientOptional.get(); } else { throw new IllegalStateException("Unable to initialize function: Cannot find zookeeper client."); } try { discoverer = createDiscoverer(client); context.addCapability(Context.Capabilities.SERVICE_DISCOVERER, () -> discoverer); isValidState = true; } catch (Exception e) { LOG.error(e.getMessage(), e); throw new IllegalStateException("Unable to initialize MAAS_GET_ENDPOINT", e); } } finally { isInitialized = true; } }
@Test public void testContextActivityTypeReset(){ String query = "someVar"; Context context = Context.EMPTY_CONTEXT(); validate(query,context); Assert.assertNull(context.getActivityType()); run(query,ImmutableMap.of("someVar","someValue"),context); Assert.assertNull(context.getActivityType()); }
/** * Creates the Stellar execution environment. * @param commandLine The command line arguments. * @param console The console which drives the REPL. * @param properties Stellar properties. */ private StellarShellExecutor createExecutor( CommandLine commandLine, Console console, Properties properties, StellarAutoCompleter autoCompleter) throws Exception { // setup zookeeper client Optional<String> zookeeperUrl = Optional.empty(); if(commandLine.hasOption("z")) { zookeeperUrl = Optional.of(commandLine.getOptionValue("z")); } StellarShellExecutor executor = new DefaultStellarShellExecutor(properties, zookeeperUrl); // the 'CONSOLE' capability is only available with the CLI REPL executor.getContext().addCapability(CONSOLE, () -> console); // allows some Stellar functions to access Stellar internals; should probably use %magics instead executor.getContext().addCapability(SHELL_VARIABLES, () -> executor.getState()); // register the auto-completer to be notified when needed executor.addSpecialListener( (special) -> autoCompleter.addCandidateFunction(special.getCommand())); executor.addFunctionListener( (function) -> autoCompleter.addCandidateFunction(function.getName())); executor.addVariableListener((name, val) -> autoCompleter.addCandidateVariable(name)); executor.init(); return executor; }
return null; if(context.getActivityType() == null) { context.setActivityType(ActivityType.PARSE_ACTIVITY); context.setActivityType(null);
@Override public void exitVariable(StellarParser.VariableContext ctx) { final FrameContext.Context context = getArgContext(); expression.tokenDeque.push(new Token<>( (tokenDeque, state) -> { String varName = ctx.getText(); if(state.context.getActivityType().equals(ActivityType.PARSE_ACTIVITY) && !state.variableResolver.exists(varName)) { // when parsing, missing variables are an error! throw new ParseException(String.format("variable: %s is not defined",varName)); } Object resolved = state.variableResolver.resolve(varName); tokenDeque.push(new Token<>(resolved, Object.class, context)); }, DeferredFunction.class, context)); expression.variablesUsed.add(ctx.getText()); }
/** * The REST_GET function should perform a get request using a proxy and parse the results. */ @Test @SuppressWarnings("unchecked") public void restGetShouldSucceedWithProxy() { mockServerClient.when( request() .withMethod("GET") .withPath("/get")) .respond(response() .withBody("{\"proxyGet\":\"success\"}")); context.addCapability(Context.Capabilities.GLOBAL_CONFIG, () -> new HashMap<String, Object>() {{ put(PROXY_HOST, "localhost"); put(PROXY_PORT, proxyRule.getHttpPort()); }}); Map<String, Object> actual = (Map<String, Object>) run(String.format("REST_GET('%s')", getUri), context); assertEquals(1, actual.size()); assertEquals("success", actual.get("proxyGet")); }
@Override public void configure(Map<String, Object> config) { Object o = config.get(QUERY_STRING_CONF); if(o instanceof String) { query= o.toString(); } Context stellarContext = (Context) config.get("stellarContext"); if(stellarContext == null) { stellarContext = Context.EMPTY_CONTEXT(); } processor.validate(query, true, stellarContext); }
public Optional<Object> getCapability(String capability) { return getCapability(capability, true); }
/** * The REST_GET function should timeout and return null. */ @Test @SuppressWarnings("unchecked") public void restGetShouldTimeout() { String uri = String.format("http://localhost:%d/get", mockServerRule.getPort()); mockServerClient.when( request() .withMethod("GET") .withPath("/get")) .respond(response() .withBody("{\"get\":\"success\"}")); Map<String, Object> globalConfig = new HashMap<String, Object>() {{ put(STELLAR_REST_SETTINGS, new HashMap<String, Object>() {{ put(TIMEOUT, 1); }}); }}; context.addCapability(Context.Capabilities.GLOBAL_CONFIG, () -> globalConfig); Map<String, Object> actual = (Map<String, Object>) run(String.format("REST_GET('%s')", uri), context); assertNull(actual); }
public static void validate(String rule) { validate(rule, Context.EMPTY_CONTEXT()); }
@SuppressWarnings("unchecked") private static Map<String, VariableResult> getVariables(Context context) { return (Map<String, VariableResult>) context.getCapability(Context.Capabilities.SHELL_VARIABLES).get(); }
public static boolean runPredicate(String rule, Map resolver) { return runPredicate(rule, resolver, Context.EMPTY_CONTEXT()); }
public Optional<Object> getCapability(Enum<?> capability, boolean errorIfNotThere) { return getCapability(capability.toString(), errorIfNotThere); }
/** * Execute and validate a Stellar expression. * * <p>This is intended for use while unit testing Stellar expressions. This ensures that the expression * validates successfully and produces a result that can be serialized correctly. * * @param expression The expression to execute. * @param variables The variables to expose to the expression. * @return The result of executing the expression. */ public static Object run(String expression, VariableResolver variables) { return run(expression, variables, Context.EMPTY_CONTEXT()); }
@SuppressWarnings("unchecked") private Map<String, Object> getGlobalConfig(Context context) { Optional<Object> globalCapability = context.getCapability(GLOBAL_CONFIG, false); return globalCapability.map(o -> (Map<String, Object>) o).orElseGet(HashMap::new); }
/** * This method determines if a given rule is valid or not. If the given rule is valid then true * will be returned otherwise a {@link ParseException} is thrown. If it is desired to return a boolean * whether the rule is valid or not, use the {@link #validate(String, boolean, Context) validate} method. It is important * to note that all variables will resolve to 'null.' * * @param rule The rule to validate. * @return If the given rule is valid then true otherwise an exception is thrown. * @throws ParseException If the rule is invalid an exception of this type is thrown. */ public boolean validate(final String rule) throws ParseException { return validate(rule, true, Context.EMPTY_CONTEXT()); }
@SuppressWarnings("unchecked") private static Map<String, Object> getConfig(Context context) { return (Map<String, Object>) context.getCapability(Context.Capabilities.GLOBAL_CONFIG, false) .orElse(new HashMap<>()); }
public static boolean runPredicate(String rule, VariableResolver resolver) { return runPredicate(rule, resolver, Context.EMPTY_CONTEXT()); }