Java源码示例:jdk.jshell.JShell
示例1
@Override
protected JShell createJShellInstance() {
ClassLoader ctxLoader = Thread.currentThread().getContextClassLoader();
try {
Thread.currentThread().setContextClassLoader(Lookup.getDefault().lookup(ClassLoader.class));
JShell.Builder b = makeBuilder();
if (execGen != null) {
b.executionEngine(new CaptureExecControl(execGen), null);
}
String s = System.getProperty("jshell.logging.properties");
if (s != null) {
b = b.remoteVMOptions(quote("-Djava.util.logging.config.file=" + s));
}
JShell ret = b.build();
return ret;
} finally {
Thread.currentThread().setContextClassLoader(ctxLoader);
}
}
示例2
private synchronized void attachTo(JShell shell) {
if (shell == state) {
return;
}
if (state != null) {
sub.unsubscribe();
state = null;
}
if (shell != null) {
NR subscription = new NR(this, shell);
subscription.subscribe();
// may fail in JShell, record in member variables only after successful
// registration
state = shell;
sub = subscription;
}
}
示例3
public JShell.Builder customizeJShell(JShell.Builder b) {
if (ShellProjectUtils.isModularProject(project)) {
if (requiredModules != null) {
b.compilerOptions("--add-modules", String.join(",", requiredModules)); // NOI18N
}
// extra options to include the modules:
List<String> opts = ShellProjectUtils.launchVMOptions(project);
b.remoteVMOptions(opts.toArray(new String[opts.size()]));
String modPath = addRoots("", ShellProjectUtils.projectRuntimeModulePath(project));
if (!modPath.isEmpty()) {
b.remoteVMOptions("--module-path", modPath);
}
}
return b;
}
示例4
/**
* Returns the user-entered snippets. Does not return snippets, which are run
* during the initial startup of JShell, just snippets executed afterwards.
*
* @param onlyValid
* @return
*/
public List<Snippet> getSnippets(boolean onlyUser, boolean onlyValid) {
Set<Snippet> initial = this.initialSetupSnippets;
JShell sh = shell;
if (sh == null) {
return Collections.emptyList();
}
List<Snippet> snips = new ArrayList<>(sh.snippets().collect(Collectors.toList()));
if (onlyUser) {
snips.removeAll(initial);
snips.removeAll(excludedSnippets);
}
if (onlyValid) {
for (Iterator<Snippet> it = snips.iterator(); it.hasNext(); ) {
Snippet s = it.next();
if (!validSnippet(s)) {
it.remove();
}
}
}
return snips;
}
示例5
public void testTempNameGenerator() {
JShell.Builder builder = getBuilder().tempVariableNameGenerator(new Supplier<String>() {
int count = 0;
@Override
public String get() {
return "temp" + ++count;
}
});
try (JShell jShell = builder.build()) {
for (int i = 0; i < 3; ++i) {
VarSnippet v = (VarSnippet) jShell.eval("2 + " + (i + 1)).get(0).snippet();
assertEquals("temp" + (i + 1), v.name(), "Custom id: ");
}
}
}
示例6
public static void main(String[] args) {
Map<String,Object> params = new HashedMap();
params.put("param1", 10);
JShell jShell = JShell.create();
jShell.eval("import java.util.Date;");
jShell.eval("import java.util.Map;");
jShell.eval("import java.util.HashMap;");
jShell.eval("int i = 0;");
jShell.eval("i = i + 10;");
jShell.eval("Map<String,Object> map1 = new HashMap<>();");
jShell.eval("map1.put(\"field\", new Date());");
jShell.variables().map(x -> x.name()).forEach(System.out::println);
jShell.variables().map(x -> jShell.varValue(x)).forEach(System.out::println);
}
示例7
@Override
public void start(Stage primaryStage) throws Exception {
JShell shell = JShell.builder().build();
TextField textField = new TextField();
Button evalButton = new Button("eval");
ListView<String> listView = new ListView<>();
evalButton.setOnAction(e -> {
List<SnippetEvent> events = shell.eval(textField.getText());
events.stream().map(event -> convert(event)).filter(s -> s != null).forEach(s -> listView.getItems().add(s));
});
BorderPane pane = new BorderPane();
pane.setTop(new HBox(textField, evalButton));
pane.setCenter(listView);
Scene scene = new Scene(pane);
primaryStage.setScene(scene);
primaryStage.show();
}
示例8
public static void main(String[] args) {
JShell myShell = JShell.create();
System.out.println("Welcome to JShell Java API Demo");
System.out.println("Please Enter a Snippet. Enter EXIT to exit:");
try(Scanner reader = new Scanner(System.in)){
while(true){
String snippet = reader.nextLine();
if ( "EXIT".equals(snippet)){
break;
}
List<SnippetEvent> events = myShell.eval(snippet);
events.stream().forEach(se -> {
System.out.print("Evaluation status: " + se.status());
System.out.println(" Evaluation result: " + se.value());
});
}
}
System.out.println("Snippets processed: ");
myShell.snippets().forEach(s -> {
String msg = String.format("%s -> %s", s.kind(), s.source());
System.out.println(msg);
});
System.out.println("Methods: ");
myShell.methods().forEach(m -> System.out.println(m.name() + " " + m.signature()));
System.out.println("Variables: ");
myShell.variables().forEach(v -> System.out.println(v.typeName() + " " + v.name()));
myShell.close();
}
示例9
public static void main(String[] args) {
JShell myShell = JShell.create();
System.out.println("Welcome to JShell Java API Demo");
System.out.println("Please Enter a Snippet. Enter EXIT to exit:");
try(Scanner reader = new Scanner(System.in)){
while(true){
String snippet = reader.nextLine();
if ( "EXIT".equals(snippet)){
break;
}
List<SnippetEvent> events = myShell.eval(snippet);
events.stream().forEach(se -> {
System.out.print("Evaluation status: " + se.status());
System.out.println(" Evaluation result: " + se.value());
});
}
}
System.out.println("Snippets processed: ");
myShell.snippets().forEach(s -> {
String msg = String.format("%s -> %s", s.kind(), s.source());
System.out.println(msg);
});
System.out.println("Methods: ");
myShell.methods().forEach(m -> System.out.println(m.name() + " " + m.signature()));
System.out.println("Variables: ");
myShell.variables().forEach(v -> System.out.println(v.typeName() + " " + v.name()));
myShell.close();
}
示例10
@Override
public JShell.Builder customizeJShell(JShell.Builder b) {
b = super.customizeJShell(b);
JavaPlatform pl = ShellProjectUtils.findPlatform(getProject());
if (!ShellProjectUtils.isModularJDK(pl)) {
return b;
}
List<String> addReads = new ArrayList<>();
addReads.add("--add-reads:java.jshell=ALL-UNNAMED");
return b.remoteVMOptions(addReads.toArray(new String[addReads.size()]));
}
示例11
protected void resetState() {
closeState();
// Initialize tool id mapping
mainNamespace = new NameSpace("main", "");
startNamespace = new NameSpace("start", "s");
errorNamespace = new NameSpace("error", "e");
mapSnippet = new LinkedHashMap<>();
currentNameSpace = startNamespace;
// Reset the replayable history, saving the old for restore
replayableHistoryPrevious = replayableHistory;
replayableHistory = new ArrayList<>();
state = createJShellInstance();
shutdownSubscription = state.onShutdown((JShell deadState) -> {
if (deadState == state) {
hardmsg("jshell.msg.terminated");
live = false;
}
});
analysis = state.sourceCodeAnalysis();
live = true;
if (!feedbackInitialized) {
// One time per run feedback initialization
feedbackInitialized = true;
initFeedback();
}
if (cmdlineClasspath != null) {
state.addToClasspath(cmdlineClasspath);
}
startUpRun(startup);
currentNameSpace = mainNamespace;
}
示例12
protected JShell.Builder makeBuilder() {
return JShell.builder()
.in(userin)
.out(userout)
.err(usererr)
.tempVariableNameGenerator(()-> "$" + currentNameSpace.tidNext())
.idGenerator((sn, i) -> (currentNameSpace == startNamespace || state.status(sn).isActive())
? currentNameSpace.tid(sn)
: errorNamespace.tid(sn))
.remoteVMOptions(remoteVMOptions.stream().toArray(String[]::new))
.compilerOptions(compilerOptions.stream().toArray(String[]::new));
}
示例13
protected void closeState() {
live = false;
JShell oldState = state;
if (oldState != null) {
oldState.unsubscribe(shutdownSubscription); // No notification
oldState.close();
}
}
示例14
synchronized void unsubscribe() {
JShell s = shellRef.get();
if (sub == null || s == null) {
return;
}
s.unsubscribe(sub);
}
示例15
JShell getJShell() {
assert evaluator.isRequestProcessorThread();
if (shell == null) {
initJShell();
}
return shell;
}
示例16
@Override
protected JShell createJShellInstance() {
JShell shell = super.createJShellInstance();
try {
setupJShellClasspath(shell);
} catch (ExecutionControlException ex) {
Exceptions.printStackTrace(ex);
}
synchronized (ShellSession.this) {
snippetRegistry = new SnippetRegistry(
shell, bridgeImpl, workRoot, editorWorkRoot,
snippetRegistry);
// replace for fresh instance !
JShell oldShell = ShellSession.this.shell;
ShellSession.this.shell = shell;
if (oldShell != null) {
FORCE_CLOSE_RP.post(() -> {
propSupport.firePropertyChange(PROP_ENGINE, oldShell, shell);
});
}
}
this.subscription = shell.onSnippetEvent(this);
// it's possible that the shell's startup will terminate the session
if (!detached) {
shell.onShutdown(sh -> closedDelayed());
ignoreClose = false;
}
return shell;
}
示例17
public void stopExecutingCode() {
JShell shell = this.shell;
if (shell == null || !model.isExecute()) {
return;
}
shell.stop();
}
示例18
public SnippetRegistry(JShell state, ShellAccessBridge shellExecutor, FileObject persistentRoot, FileObject transientRoot,
SnippetRegistry previousRegistry) {
this.state = state;
this.persistentSnippetsRoot = persistentRoot;
this.transientSnippetsRoot = transientRoot;
this.shellExecutor = shellExecutor;
this.counter = previousRegistry == null ?
new AtomicInteger(0) :
previousRegistry.counter;
if (previousRegistry != null) {
copyFrom(previousRegistry);
}
}
示例19
/**
* Generates a wrapping for a text without declaring a new Snippet
* @param state JShell instance
* @param input source text
* @return wrapped source
*/
public static SnippetWrapping wrapInput(JShell state, String input) {
if (input.trim().isEmpty()) {
input = input + ";"; // NOI18N
}
List<SnippetWrapper> wraps = state.sourceCodeAnalysis().wrappers(input);
if (wraps.size() != 1) {
return null;
}
return new WrappedWrapper(null, wraps.get(0), state);
}
示例20
/**
* Tests if any of the specified debug flags are enabled.
*
* @param state the JShell instance
* @param flag the {@code DBG_*} bits to check
* @return true if any of the flags are enabled
*/
public static boolean isDebugEnabled(JShell state, int flag) {
if (debugMap == null) {
return false;
}
Integer flags = debugMap.get(state);
if (flags == null) {
return false;
}
return (flags & flag) != 0;
}
示例21
private void closeState() {
live = false;
JShell oldState = state;
if (oldState != null) {
state = null;
analysis = null;
oldState.unsubscribe(shutdownSubscription); // No notification
oldState.close();
}
}
示例22
private void scheduleStop(String src) throws InterruptedException {
JShell state = getState();
isStopped = false;
StringWriter writer = new StringWriter();
PrintWriter out = new PrintWriter(writer);
Thread t = new Thread(() -> {
int i = 1;
int n = 30;
synchronized (lock) {
do {
state.stop();
if (!isStopped) {
out.println("Not stopped. Try again: " + i);
try {
lock.wait(1000);
} catch (InterruptedException ignored) {
}
}
} while (i++ < n && !isStopped);
if (!isStopped) {
System.err.println(writer.toString());
fail("Evaluation was not stopped: '" + src + "'");
}
}
});
t.start();
assertEval(src);
synchronized (lock) {
out.println("Evaluation was stopped successfully: '" + src + "'");
isStopped = true;
lock.notify();
}
// wait until the background thread finishes to prevent from calling 'stop' on closed state.
t.join();
}
示例23
static JShell state(boolean isLaunch, String host) {
ExecutionControlProvider ecp = new JdiExecutionControlProvider();
Map<String,String> pm = ecp.defaultParameters();
pm.put(JdiExecutionControlProvider.PARAM_REMOTE_AGENT, DyingRemoteAgent.class.getName());
pm.put(JdiExecutionControlProvider.PARAM_HOST_NAME, host==null? "" : host);
pm.put(JdiExecutionControlProvider.PARAM_LAUNCH, ""+isLaunch);
// turn on logging of launch failures
Logger.getLogger("jdk.jshell.execution").setLevel(Level.ALL);
return JShell.builder()
.executionEngine(ecp, pm)
.build();
}
示例24
public void badOptionListenTest() {
try {
// turn on logging of launch failures
Logger.getLogger("jdk.jshell.execution").setLevel(Level.ALL);
JShell.builder()
.executionEngine("jdi:hostname(BattyRumbleBuckets-Snurfle-99-Blip)")
.build();
} catch (IllegalStateException ex) {
assertTrue(ex.getMessage().startsWith(EXPECTED_ERROR), ex.getMessage());
return;
}
fail("Expected IllegalStateException");
}
示例25
public void badOptionLaunchTest() {
try {
// turn on logging of launch failures
Logger.getLogger("jdk.jshell.execution").setLevel(Level.ALL);
JShell.builder()
.executionEngine("jdi:launch(true)")
.remoteVMOptions("-BadBadOption")
.build();
} catch (IllegalStateException ex) {
assertTrue(ex.getMessage().startsWith(EXPECTED_ERROR), ex.getMessage());
return;
}
fail("Expected IllegalStateException");
}
示例26
static JShell state(boolean isLaunch, String host) {
ExecutionControlProvider ecp = new JdiExecutionControlProvider();
Map<String,String> pm = ecp.defaultParameters();
pm.put(JdiExecutionControlProvider.PARAM_REMOTE_AGENT, HangingRemoteAgent.class.getName());
pm.put(JdiExecutionControlProvider.PARAM_HOST_NAME, host==null? "" : host);
pm.put(JdiExecutionControlProvider.PARAM_LAUNCH, ""+isLaunch);
pm.put(JdiExecutionControlProvider.PARAM_TIMEOUT, ""+TIMEOUT);
// turn on logging of launch failures
Logger.getLogger("jdk.jshell.execution").setLevel(Level.ALL);
return JShell.builder()
.executionEngine(ecp, pm)
.build();
}
示例27
public void badOptionListenTest() {
try {
// turn on logging of launch failures
Logger.getLogger("jdk.jshell.execution").setLevel(Level.ALL);
JShell.builder()
.executionEngine("jdi")
.remoteVMOptions("-BadBadOption")
.build();
} catch (IllegalStateException ex) {
assertTrue(ex.getMessage().contains(EXPECTED_ERROR), ex.getMessage());
return;
}
fail("Expected IllegalStateException");
}
示例28
public JShell.Builder getBuilder() {
TestingInputStream inStream = new TestingInputStream();
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
ByteArrayOutputStream errStream = new ByteArrayOutputStream();
return JShell.builder()
.in(inStream)
.out(new PrintStream(outStream))
.err(new PrintStream(errStream));
}
示例29
public void testResetTempNameGenerator() {
JShell.Builder builder = getBuilder().tempVariableNameGenerator(() -> {
throw new AssertionError("Should not be called");
});
try (JShell jShell = builder.tempVariableNameGenerator(null).build()) {
jShell.eval("2 + 2");
}
}
示例30
public void testIdGenerator() {
JShell.Builder builder = getBuilder().idGenerator(((snippet, id) -> "custom" + id));
try (JShell jShell = builder.build()) {
List<SnippetEvent> eval = jShell.eval("int a, b;");
checkIds(eval);
checkIds(jShell.drop(eval.get(0).snippet()));
}
}