private void breakupJavaLines(String input) { CommandHelper.breakupArguments( input, (javaLine) -> { javaLine = javaLine.trim(); if (!javaLine.isEmpty() && !javaLine.startsWith("//")) { code.addLine(javaLine); } return true; }, JAVA_OPTIONS.separatorCode(';')); }
@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"); }
@Override public void execute(String line, PrintStream out, PrintStream err) { Objects.requireNonNull(classLoaderContext, "Did not set ClassLoaderCapabilities"); CommandInvocation invocation = javaArgs.parse(line, JAVA_OPTIONS.separatorCode(' ')); if (invocation.hasOption(RESET_CODE_ARG)) { code.resetCode(); } if (invocation.hasOption(RESET_ALL_ARG)) { code.resetAll(); } String codeToRun = invocation.getUnprocessedInput(); @Nullable String className; if (invocation.hasOption(CLASS_ARG) && (className = extractClassName(codeToRun, err)) != null) { Optional<Class<Object>> javaClass = javacService.compileJavaClass(classLoaderContext, className, codeToRun, err); javaClass.ifPresent(out::println); } else { breakupJavaLines(codeToRun); boolean show = invocation.hasOption(SHOW_ARG); if (show) { out.println(javacService.getJavaSnippetClass(code)); if (!codeToRun.isEmpty()) { // add new lines between the code and its result out.println(); } } // run the current code if some input was given, or in any case when no show option if (!codeToRun.isEmpty() || !show) { runJava(out, err); } } }