private void runJava(PrintStream out, PrintStream err) { Binding.out = out; Binding.err = err; Binding.ctx = bundle.getBundleContext(); try { Callable<?> callable = javacService.compileJavaSnippet(code, classLoaderContext, err).orElse(ERROR); if (callable != ERROR) { Object result = callable.call(); if (result != null) { out.println(result); } code.commit(); } else { code.abort(); } } catch (Throwable e) { code.abort(); e.printStackTrace(err); } }
@Override public OutputStream pipe(String command, PrintStream out, PrintStream err) { CommandInvocation invocation = javaArgs.parse(command, JAVA_OPTIONS.separatorCode(' ')); Matcher identifierMatcher = lambdaIdentifierRegex.matcher(invocation.getUnprocessedInput()); if (identifierMatcher.matches()) { String lambdaArgIdentifier = identifierMatcher.group("id"); String lambdaBody = identifierMatcher.group("body").trim(); if (lambdaBody.endsWith(";")) { lambdaBody = lambdaBody.substring(0, lambdaBody.length() - 1); } String lineConsumerCode = "return (java.util.function.Function<String, ?>)" + "((" + lambdaArgIdentifier.trim() + ") -> " + lambdaBody + ")"; JavaCode functionCode = new JavaCode(code); functionCode.addLine(lineConsumerCode); Optional<Callable<?>> callable = javacService.compileJavaSnippet(functionCode, classLoaderContext, err); if (callable.isPresent()) { try { Function<String, ?> callback = (Function<String, ?>) callable.get().call(); return new LineOutputStream( line -> { @Nullable Object output = callback.apply(line); if (output != null) { out.println(output); } }, out); } catch (Exception e) { err.println(e); } } } throw new RuntimeException( "When used in a pipeline, the Java snippet must be in the form of a " + "lambda of type Function<String, ?> that takes one text line of the input at a time.\n" + "Example: ... | java line -> line.contains(\"text\") ? line : null"); }