提交 f9b20744 编写于 作者: S sundar

8014519: scriptpad sample does not work with nashorn

Reviewed-by: attila, jlaskey
Contributed-by: rieberandreas@gmail.com
上级 733e7b93
/* /*
* Copyright (c) 2006, 2011, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2006, 2013, Oracle and/or its affiliates. All rights reserved.
* *
* Redistribution and use in source and binary forms, with or without * Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions * modification, are permitted provided that the following conditions
...@@ -75,7 +75,7 @@ public class Main { ...@@ -75,7 +75,7 @@ public class Main {
*/ */
InputStream is = Main.class.getResourceAsStream("/resources/" + name); InputStream is = Main.class.getResourceAsStream("/resources/" + name);
// current script file name for better error messages // current script file name for better error messages
engine.put(ScriptEngine.NAME, name); engine.put(ScriptEngine.FILENAME, name);
// evaluate the script in the InputStream // evaluate the script in the InputStream
engine.eval(new InputStreamReader(is)); engine.eval(new InputStreamReader(is));
} }
......
/* /*
* Copyright (c) 2006, 2011, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2006, 2013, Oracle and/or its affiliates. All rights reserved.
* *
* Redistribution and use in source and binary forms, with or without * Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions * modification, are permitted provided that the following conditions
...@@ -37,7 +37,6 @@ ...@@ -37,7 +37,6 @@
* this sample code. * this sample code.
*/ */
/* /*
* This script can be loaded in jrunscript to start scriptpad. * This script can be loaded in jrunscript to start scriptpad.
* *
...@@ -48,4 +47,3 @@ load("conc.js"); ...@@ -48,4 +47,3 @@ load("conc.js");
load("gui.js"); load("gui.js");
load("scriptpad.js"); load("scriptpad.js");
load("mm.js"); load("mm.js");
/* /*
* Copyright (c) 2006, 2011, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2006, 2013, Oracle and/or its affiliates. All rights reserved.
* *
* Redistribution and use in source and binary forms, with or without * Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions * modification, are permitted provided that the following conditions
...@@ -37,7 +37,6 @@ ...@@ -37,7 +37,6 @@
* this sample code. * this sample code.
*/ */
/* /*
* Concurrency utilities for JavaScript. These are based on * Concurrency utilities for JavaScript. These are based on
* java.lang and java.util.concurrent API. The following functions * java.lang and java.util.concurrent API. The following functions
...@@ -46,6 +45,35 @@ ...@@ -46,6 +45,35 @@
* objects exported from here. * objects exported from here.
*/ */
// shortcut for j.u.c lock classes
var Lock = java.util.concurrent.locks.ReentrantLock;
var RWLock = java.util.concurrent.locks.ReentrantReadWriteLock;
// check if there is a build in sync function, define one if missing
if (typeof sync === "undefined") {
var sync = function(func, obj) {
if (arguments.length < 1 || arguments.length > 2 ) {
throw "sync(function [,object]) parameter count mismatch";
}
var syncobj = (arguments.length == 2 ? obj : this);
if (!syncobj._syncLock) {
syncobj._syncLock = new Lock();
}
return function() {
syncobj._syncLock.lock();
try {
func.apply(null, arguments);
} finally {
syncobj._syncLock.unlock();
}
};
};
sync.docString = "synchronize a function, optionally on an object";
}
/** /**
* Wrapper for java.lang.Object.wait * Wrapper for java.lang.Object.wait
* *
...@@ -58,7 +86,6 @@ function wait(object) { ...@@ -58,7 +86,6 @@ function wait(object) {
} }
wait.docString = "convenient wrapper for java.lang.Object.wait method"; wait.docString = "convenient wrapper for java.lang.Object.wait method";
/** /**
* Wrapper for java.lang.Object.notify * Wrapper for java.lang.Object.notify
* *
...@@ -71,7 +98,6 @@ function notify(object) { ...@@ -71,7 +98,6 @@ function notify(object) {
} }
notify.docString = "convenient wrapper for java.lang.Object.notify method"; notify.docString = "convenient wrapper for java.lang.Object.notify method";
/** /**
* Wrapper for java.lang.Object.notifyAll * Wrapper for java.lang.Object.notifyAll
* *
...@@ -84,7 +110,6 @@ function notifyAll(object) { ...@@ -84,7 +110,6 @@ function notifyAll(object) {
} }
notifyAll.docString = "convenient wrapper for java.lang.Object.notifyAll method"; notifyAll.docString = "convenient wrapper for java.lang.Object.notifyAll method";
/** /**
* Creates a java.lang.Runnable from a given script * Creates a java.lang.Runnable from a given script
* function. * function.
...@@ -97,7 +122,7 @@ Function.prototype.runnable = function() { ...@@ -97,7 +122,7 @@ Function.prototype.runnable = function() {
func.apply(null, args); func.apply(null, args);
} }
} }
} };
/** /**
* Executes the function on a new Java Thread. * Executes the function on a new Java Thread.
...@@ -106,7 +131,7 @@ Function.prototype.thread = function() { ...@@ -106,7 +131,7 @@ Function.prototype.thread = function() {
var t = new java.lang.Thread(this.runnable.apply(this, arguments)); var t = new java.lang.Thread(this.runnable.apply(this, arguments));
t.start(); t.start();
return t; return t;
} };
/** /**
* Executes the function on a new Java daemon Thread. * Executes the function on a new Java daemon Thread.
...@@ -116,7 +141,7 @@ Function.prototype.daemon = function() { ...@@ -116,7 +141,7 @@ Function.prototype.daemon = function() {
t.setDaemon(true); t.setDaemon(true);
t.start(); t.start();
return t; return t;
} };
/** /**
* Creates a java.util.concurrent.Callable from a given script * Creates a java.util.concurrent.Callable from a given script
...@@ -128,7 +153,7 @@ Function.prototype.callable = function() { ...@@ -128,7 +153,7 @@ Function.prototype.callable = function() {
return new java.util.concurrent.Callable() { return new java.util.concurrent.Callable() {
call: function() { return func.apply(null, args); } call: function() { return func.apply(null, args); }
} }
} };
/** /**
* Registers the script function so that it will be called exit. * Registers the script function so that it will be called exit.
...@@ -137,7 +162,7 @@ Function.prototype.atexit = function () { ...@@ -137,7 +162,7 @@ Function.prototype.atexit = function () {
var args = arguments; var args = arguments;
java.lang.Runtime.getRuntime().addShutdownHook( java.lang.Runtime.getRuntime().addShutdownHook(
new java.lang.Thread(this.runnable.apply(this, args))); new java.lang.Thread(this.runnable.apply(this, args)));
} };
/** /**
* Executes the function asynchronously. * Executes the function asynchronously.
...@@ -152,13 +177,9 @@ Function.prototype.future = (function() { ...@@ -152,13 +177,9 @@ Function.prototype.future = (function() {
(function() { theExecutor.shutdown(); }).atexit(); (function() { theExecutor.shutdown(); }).atexit();
return function() { return function() {
return theExecutor.submit(this.callable.apply(this, arguments)); return theExecutor.submit(this.callable.apply(this, arguments));
} };
})(); })();
// shortcut for j.u.c lock classes
var Lock = java.util.concurrent.locks.ReentrantLock;
var RWLock = java.util.concurrent.locks.ReentrantReadWriteLock;
/** /**
* Executes a function after acquiring given lock. On return, * Executes a function after acquiring given lock. On return,
* (normal or exceptional), lock is released. * (normal or exceptional), lock is released.
...@@ -179,7 +200,7 @@ Function.prototype.sync = function (lock) { ...@@ -179,7 +200,7 @@ Function.prototype.sync = function (lock) {
} finally { } finally {
lock.unlock(); lock.unlock();
} }
} };
/** /**
* Causes current thread to sleep for specified * Causes current thread to sleep for specified
...@@ -192,6 +213,39 @@ function sleep(interval) { ...@@ -192,6 +213,39 @@ function sleep(interval) {
} }
sleep.docString = "wrapper for java.lang.Thread.sleep method"; sleep.docString = "wrapper for java.lang.Thread.sleep method";
/**
* Schedules a task to be executed once in N milliseconds specified.
*
* @param callback function or expression to evaluate
* @param interval in milliseconds to sleep
* @return timeout ID (which is nothing but Thread instance)
*/
function setTimeout(callback, interval) {
if (! (callback instanceof Function) && typeof callback !== "function") {
callback = new Function(callback);
}
// start a new thread that sleeps given time
// and calls callback in an infinite loop
return (function() {
try {
sleep(interval);
} catch (x) { }
callback();
}).daemon();
}
setTimeout.docString = "calls given callback once after specified interval";
/**
* Cancels a timeout set earlier.
* @param tid timeout ID returned from setTimeout
*/
function clearTimeout(tid) {
// we just interrupt the timer thread
tid.interrupt();
}
clearTimeout.docString = "interrupt a setTimeout timer";
/** /**
* Schedules a task to be executed once in * Schedules a task to be executed once in
* every N milliseconds specified. * every N milliseconds specified.
...@@ -200,8 +254,8 @@ sleep.docString = "wrapper for java.lang.Thread.sleep method"; ...@@ -200,8 +254,8 @@ sleep.docString = "wrapper for java.lang.Thread.sleep method";
* @param interval in milliseconds to sleep * @param interval in milliseconds to sleep
* @return timeout ID (which is nothing but Thread instance) * @return timeout ID (which is nothing but Thread instance)
*/ */
function setTimeout(callback, interval) { function setInterval(callback, interval) {
if (! (callback instanceof Function)) { if (! (callback instanceof Function) && typeof callback !== "function") {
callback = new Function(callback); callback = new Function(callback);
} }
...@@ -209,21 +263,26 @@ function setTimeout(callback, interval) { ...@@ -209,21 +263,26 @@ function setTimeout(callback, interval) {
// and calls callback in an infinite loop // and calls callback in an infinite loop
return (function() { return (function() {
while (true) { while (true) {
try {
sleep(interval); sleep(interval);
} catch (x) {
break;
}
callback(); callback();
} }
}).daemon(); }).daemon();
} }
setTimeout.docString = "calls given callback once after specified interval" setInterval.docString = "calls given callback every specified interval";
/** /**
* Cancels a timeout set earlier. * Cancels a timeout set earlier.
* @param tid timeout ID returned from setTimeout * @param tid timeout ID returned from setTimeout
*/ */
function clearTimeout(tid) { function clearInterval(tid) {
// we just interrupt the timer thread // we just interrupt the timer thread
tid.interrupt(); tid.interrupt();
} }
clearInterval.docString = "interrupt a setInterval timer";
/** /**
* Simple access to thread local storage. * Simple access to thread local storage.
...@@ -240,7 +299,7 @@ function clearTimeout(tid) { ...@@ -240,7 +299,7 @@ function clearTimeout(tid) {
*/ */
var __thread = (function () { var __thread = (function () {
var map = new Object(); var map = new Object();
return new JSAdapter() { return new JSAdapter({
__has__: function(name) { __has__: function(name) {
return map[name] != undefined; return map[name] != undefined;
}, },
...@@ -265,6 +324,6 @@ var __thread = (function () { ...@@ -265,6 +324,6 @@ var __thread = (function () {
map[name].set(null); map[name].set(null);
} }
} }
} });
})(); })();
/* /*
* Copyright (c) 2006, 2011, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2006, 2013, Oracle and/or its affiliates. All rights reserved.
* *
* Redistribution and use in source and binary forms, with or without * Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions * modification, are permitted provided that the following conditions
...@@ -37,7 +37,6 @@ ...@@ -37,7 +37,6 @@
* this sample code. * this sample code.
*/ */
/* /*
* Few user interface utilities. * Few user interface utilities.
*/ */
...@@ -58,7 +57,7 @@ Function.prototype.invokeLater = function() { ...@@ -58,7 +57,7 @@ Function.prototype.invokeLater = function() {
func.apply(func, args); func.apply(func, args);
} }
}); });
} };
/** /**
* Swing invokeAndWait - invokes given function in AWT event thread * Swing invokeAndWait - invokes given function in AWT event thread
...@@ -73,7 +72,7 @@ Function.prototype.invokeAndWait = function() { ...@@ -73,7 +72,7 @@ Function.prototype.invokeAndWait = function() {
func.apply(func, args); func.apply(func, args);
} }
}); });
} };
/** /**
* Am I running in AWT event dispatcher thread? * Am I running in AWT event dispatcher thread?
...@@ -97,10 +96,12 @@ function fileDialog(curDir, save) { ...@@ -97,10 +96,12 @@ function fileDialog(curDir, save) {
if (curDir == undefined) { if (curDir == undefined) {
curDir = new java.io.File("."); curDir = new java.io.File(".");
} }
var JFileChooser = javax.swing.JFileChooser; var JFileChooser = javax.swing.JFileChooser;
var dialog = new JFileChooser(curDir); var dialog = new JFileChooser(curDir);
var res = save? dialog.showSaveDialog(window): var res = save ? dialog.showSaveDialog(window):
dialog.showOpenDialog(window); dialog.showOpenDialog(window);
if (res == JFileChooser.APPROVE_OPTION) { if (res == JFileChooser.APPROVE_OPTION) {
result = dialog.getSelectedFile(); result = dialog.getSelectedFile();
} else { } else {
...@@ -113,6 +114,7 @@ function fileDialog(curDir, save) { ...@@ -113,6 +114,7 @@ function fileDialog(curDir, save) {
} else { } else {
_fileDialog.invokeAndWait(); _fileDialog.invokeAndWait();
} }
return result; return result;
} }
fileDialog.docString = "show a file dialog box"; fileDialog.docString = "show a file dialog box";
...@@ -124,19 +126,21 @@ fileDialog.docString = "show a file dialog box"; ...@@ -124,19 +126,21 @@ fileDialog.docString = "show a file dialog box";
* @param color default color [optional] * @param color default color [optional]
* @return choosen color or default color * @return choosen color or default color
*/ */
function colorDialog(title, color) { function colorDialog(title, color) {
var result; var result;
function _colorDialog() { function _colorDialog() {
if (title == undefined) { if (title == undefined) {
title = "Choose Color"; title = "Choose Color";
} }
if (color == undefined) { if (color == undefined) {
color = java.awt.Color.BLACK; color = java.awt.Color.BLACK;
} }
var chooser = new javax.swing.JColorChooser(); var chooser = new javax.swing.JColorChooser();
var res = chooser.showDialog(window, title, color); var res = chooser.showDialog(window, title, color);
result = res? res : color; result = res ? res : color;
} }
if (isEventThread()) { if (isEventThread()) {
...@@ -144,6 +148,7 @@ function colorDialog(title, color) { ...@@ -144,6 +148,7 @@ function colorDialog(title, color) {
} else { } else {
_colorDialog.invokeAndWait(); _colorDialog.invokeAndWait();
} }
return result; return result;
} }
colorDialog.docString = "shows a color chooser dialog box"; colorDialog.docString = "shows a color chooser dialog box";
...@@ -156,15 +161,15 @@ colorDialog.docString = "shows a color chooser dialog box"; ...@@ -156,15 +161,15 @@ colorDialog.docString = "shows a color chooser dialog box";
* @param msgType type of message box [constants in JOptionPane] * @param msgType type of message box [constants in JOptionPane]
*/ */
function msgBox(msg, title, msgType) { function msgBox(msg, title, msgType) {
function _msgBox() { function _msgBox() {
var JOptionPane = javax.swing.JOptionPane; var JOptionPane = javax.swing.JOptionPane;
if (msg === undefined) msg = "undefined"; if (msg === undefined) msg = "undefined";
if (msg === null) msg = "null"; if (msg === null) msg = "null";
if (title == undefined) title = msg; if (title == undefined) title = msg;
if (msgType == undefined) type = JOptionPane.INFORMATION_MESSAGE; if (msgType == undefined) msgType = JOptionPane.INFORMATION_MESSAGE;
JOptionPane.showMessageDialog(window, msg, title, msgType); JOptionPane.showMessageDialog(window, msg, title, msgType);
} }
if (isEventThread()) { if (isEventThread()) {
_msgBox(); _msgBox();
} else { } else {
...@@ -197,7 +202,6 @@ function error(msg, title) { ...@@ -197,7 +202,6 @@ function error(msg, title) {
} }
error.docString = "shows an error message box to the user"; error.docString = "shows an error message box to the user";
/** /**
* Shows a warning alert box * Shows a warning alert box
* *
...@@ -210,7 +214,6 @@ function warn(msg, title) { ...@@ -210,7 +214,6 @@ function warn(msg, title) {
} }
warn.docString = "shows a warning message box to the user"; warn.docString = "shows a warning message box to the user";
/** /**
* Shows a prompt dialog box * Shows a prompt dialog box
* *
...@@ -225,11 +228,13 @@ function prompt(question, answer) { ...@@ -225,11 +228,13 @@ function prompt(question, answer) {
if (answer == undefined) answer = ""; if (answer == undefined) answer = "";
result = JOptionPane.showInputDialog(window, question, answer); result = JOptionPane.showInputDialog(window, question, answer);
} }
if (isEventThread()) { if (isEventThread()) {
_prompt(); _prompt();
} else { } else {
_prompt.invokeAndWait(); _prompt.invokeAndWait();
} }
return result; return result;
} }
prompt.docString = "shows a prompt box to the user and returns the answer"; prompt.docString = "shows a prompt box to the user and returns the answer";
...@@ -244,16 +249,19 @@ prompt.docString = "shows a prompt box to the user and returns the answer"; ...@@ -244,16 +249,19 @@ prompt.docString = "shows a prompt box to the user and returns the answer";
function confirm(msg, title) { function confirm(msg, title) {
var result; var result;
var JOptionPane = javax.swing.JOptionPane; var JOptionPane = javax.swing.JOptionPane;
function _confirm() { function _confirm() {
if (title == undefined) title = msg; if (title == undefined) title = msg;
var optionType = JOptionPane.YES_NO_OPTION; var optionType = JOptionPane.YES_NO_OPTION;
result = JOptionPane.showConfirmDialog(window, msg, title, optionType); result = JOptionPane.showConfirmDialog(window, msg, title, optionType);
} }
if (isEventThread()) { if (isEventThread()) {
_confirm(); _confirm();
} else { } else {
_confirm.invokeAndWait(); _confirm.invokeAndWait();
} }
return result == JOptionPane.YES_OPTION; return result == JOptionPane.YES_OPTION;
} }
confirm.docString = "shows a confirmation message box to the user"; confirm.docString = "shows a confirmation message box to the user";
......
/* /*
* Copyright (c) 2006, 2011, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2006, 2013, Oracle and/or its affiliates. All rights reserved.
* *
* Redistribution and use in source and binary forms, with or without * Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions * modification, are permitted provided that the following conditions
...@@ -37,7 +37,6 @@ ...@@ -37,7 +37,6 @@
* this sample code. * this sample code.
*/ */
/* /*
* This is a collection of utilities for Monitoring * This is a collection of utilities for Monitoring
* and management API. * and management API.
...@@ -78,7 +77,7 @@ function mbeanConnection() { ...@@ -78,7 +77,7 @@ function mbeanConnection() {
return mmConnection; return mmConnection;
} }
mbeanConnection.docString = "returns the current MBeanServer connection" mbeanConnection.docString = "returns the current MBeanServer connection";
/** /**
* Returns a platform MXBean proxy for given MXBean name and interface class * Returns a platform MXBean proxy for given MXBean name and interface class
...@@ -102,7 +101,6 @@ function objectName(objName) { ...@@ -102,7 +101,6 @@ function objectName(objName) {
} }
objectName.docString = "creates JMX ObjectName for a given String"; objectName.docString = "creates JMX ObjectName for a given String";
/** /**
* Creates a new (M&M) Attribute object * Creates a new (M&M) Attribute object
* *
...@@ -146,7 +144,6 @@ function queryNames(objName, query) { ...@@ -146,7 +144,6 @@ function queryNames(objName, query) {
} }
queryNames.docString = "returns QueryNames using given ObjectName and optional query"; queryNames.docString = "returns QueryNames using given ObjectName and optional query";
/** /**
* Queries with given ObjectName and QueryExp. * Queries with given ObjectName and QueryExp.
* QueryExp may be null. * QueryExp may be null.
...@@ -220,7 +217,6 @@ function getMBeanAttribute(objName, attrName) { ...@@ -220,7 +217,6 @@ function getMBeanAttribute(objName, attrName) {
} }
getMBeanAttribute.docString = "returns a single Attribute of given ObjectName"; getMBeanAttribute.docString = "returns a single Attribute of given ObjectName";
// sets MBean attributes // sets MBean attributes
function setMBeanAttributes(objName, attrList) { function setMBeanAttributes(objName, attrList) {
objName = objectName(objName); objName = objectName(objName);
...@@ -237,7 +233,6 @@ function setMBeanAttribute(objName, attrName, attrValue) { ...@@ -237,7 +233,6 @@ function setMBeanAttribute(objName, attrName, attrValue) {
} }
setMBeanAttribute.docString = "sets a single Attribute of given ObjectName"; setMBeanAttribute.docString = "sets a single Attribute of given ObjectName";
// invokes an operation on given MBean // invokes an operation on given MBean
function invokeMBean(objName, operation, params, signature) { function invokeMBean(objName, operation, params, signature) {
objName = objectName(objName); objName = objectName(objName);
...@@ -260,16 +255,17 @@ invokeMBean.docString = "invokes MBean operation on given ObjectName"; ...@@ -260,16 +255,17 @@ invokeMBean.docString = "invokes MBean operation on given ObjectName";
* will be of type FutureTask. When you need value, call 'get' on it. * will be of type FutureTask. When you need value, call 'get' on it.
*/ */
function mbean(objName, async) { function mbean(objName, async) {
var index;
objName = objectName(objName); objName = objectName(objName);
var info = mbeanInfo(objName); var info = mbeanInfo(objName);
var attrs = info.attributes; var attrs = info.attributes;
var attrMap = new Object; var attrMap = new Object;
for (var index in attrs) { for (index in attrs) {
attrMap[attrs[index].name] = attrs[index]; attrMap[attrs[index].name] = attrs[index];
} }
var opers = info.operations; var opers = info.operations;
var operMap = new Object; var operMap = new Object;
for (var index in opers) { for (index in opers) {
operMap[opers[index].name] = opers[index]; operMap[opers[index].name] = opers[index];
} }
...@@ -307,7 +303,7 @@ function mbean(objName, async) { ...@@ -307,7 +303,7 @@ function mbean(objName, async) {
} else { } else {
return invokeMBean(objName, name, params, sigNames); return invokeMBean(objName, name, params, sigNames);
} }
} };
} else { } else {
return undefined; return undefined;
} }
......
/* /*
* Copyright (c) 2006, 2011, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2006, 2013, Oracle and/or its affiliates. All rights reserved.
* *
* Redistribution and use in source and binary forms, with or without * Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions * modification, are permitted provided that the following conditions
...@@ -37,7 +37,6 @@ ...@@ -37,7 +37,6 @@
* this sample code. * this sample code.
*/ */
/* /*
* This script creates a simple Notepad-like interface, which * This script creates a simple Notepad-like interface, which
* serves as a simple script editor, runner. * serves as a simple script editor, runner.
...@@ -47,6 +46,11 @@ ...@@ -47,6 +46,11 @@
* gui.js -> for basic GUI functions * gui.js -> for basic GUI functions
*/ */
/*
* globalThis is used for actionHelpGlobals() and showFrame().
*/
var globalThis = this;
/* /*
* JavaImporter helps in avoiding pollution of JavaScript * JavaImporter helps in avoiding pollution of JavaScript
* global namespace. We can import multiple Java packages * global namespace. We can import multiple Java packages
...@@ -57,21 +61,12 @@ var guiPkgs = new JavaImporter(java.awt, java.awt.event, ...@@ -57,21 +61,12 @@ var guiPkgs = new JavaImporter(java.awt, java.awt.event,
javax.swing, javax.swing.undo, javax.swing, javax.swing.undo,
javax.swing.event, javax.swing.text); javax.swing.event, javax.swing.text);
with (guiPkgs) { // main entry point of the scriptpad application
var main = function() {
/*
* within this "with" statement all Java classes in
* packages defined in "guiPkgs" can be used as simple
* names instead of the fully qualified names.
*/
// main entry point of the scriptpad application
function main() {
function createEditor() { function createEditor() {
var c = new JTextArea(); var c = new guiPkgs.JTextArea();
c.setDragEnabled(true); c.setDragEnabled(true);
c.setFont(new Font("monospaced", Font.PLAIN, 12)); c.setFont(new guiPkgs.Font("monospaced", guiPkgs.Font.PLAIN, 12));
return c; return c;
} }
...@@ -100,8 +95,7 @@ with (guiPkgs) { ...@@ -100,8 +95,7 @@ with (guiPkgs) {
return; return;
} }
if (confirm( if (confirm("Do you want to save the changes?",
"Do you want to save the changes?",
"The document has changed")) { "The document has changed")) {
actionSave(); actionSave();
} }
...@@ -113,12 +107,17 @@ with (guiPkgs) { ...@@ -113,12 +107,17 @@ with (guiPkgs) {
function setDocListener() { function setDocListener() {
var doc = editor.getDocument(); var doc = editor.getDocument();
docChanged = false; docChanged = false;
doc.addDocumentListener(new DocumentListener() { doc.addDocumentListener( new guiPkgs.DocumentListener() {
equals: function(o) { return this === o; }, equals: function(o) {
toString: function() { return "doc listener"; }, return this === o; },
changeUpdate: function() { docChanged = true; }, toString: function() {
insertUpdate: function() { docChanged = true; }, return "doc listener"; },
removeUpdate: function() { docChanged = true; }, changeUpdate: function() {
docChanged = true; },
insertUpdate: function() {
docChanged = true; },
removeUpdate: function() {
docChanged = true; }
}); });
} }
...@@ -127,10 +126,10 @@ with (guiPkgs) { ...@@ -127,10 +126,10 @@ with (guiPkgs) {
// "File" menu // "File" menu
// create a "new" document // create a "new" document
function actionNew(){ function actionNew() {
checkDocChanged(); checkDocChanged();
curFileName = null; curFileName = null;
editor.setDocument(new PlainDocument()); editor.setDocument(new guiPkgs.PlainDocument());
setDocListener(); setDocListener();
frame.setTitle(defaultTitle); frame.setTitle(defaultTitle);
editor.revalidate(); editor.revalidate();
...@@ -143,10 +142,11 @@ with (guiPkgs) { ...@@ -143,10 +142,11 @@ with (guiPkgs) {
if (f == null) { if (f == null) {
return; return;
} }
if (f.isFile() && f.canRead()) { if (f.isFile() && f.canRead()) {
frame.setTitle(f.getName() + titleSuffix); frame.setTitle(f.getName() + titleSuffix);
editor.setDocument(new PlainDocument()); editor.setDocument(new guiPkgs.PlainDocument());
var progress = new JProgressBar(); var progress = new guiPkgs.JProgressBar();
progress.setMinimum(0); progress.setMinimum(0);
progress.setMaximum(f.length()); progress.setMaximum(f.length());
var doc = editor.getDocument(); var doc = editor.getDocument();
...@@ -178,9 +178,9 @@ with (guiPkgs) { ...@@ -178,9 +178,9 @@ with (guiPkgs) {
try { try {
var u = new java.net.URL(url); var u = new java.net.URL(url);
editor.setDocument(new PlainDocument()); editor.setDocument(new guiPkgs.PlainDocument());
frame.setTitle(url + titleSuffix); frame.setTitle(url + titleSuffix);
var progress = new JProgressBar(); var progress = new guiPkgs.JProgressBar();
progress.setMinimum(0); progress.setMinimum(0);
progress.setIndeterminate(true); progress.setIndeterminate(true);
var doc = editor.getDocument(); var doc = editor.getDocument();
...@@ -207,22 +207,25 @@ with (guiPkgs) { ...@@ -207,22 +207,25 @@ with (guiPkgs) {
var doc = editor.getDocument(); var doc = editor.getDocument();
frame.setTitle(file.getName() + titleSuffix); frame.setTitle(file.getName() + titleSuffix);
curFileName = file; curFileName = file;
var progress = new JProgressBar(); var progress = new guiPkgs.JProgressBar();
progress.setMinimum(0); progress.setMinimum(0);
progress.setMaximum(file.length()); progress.setMaximum(file.length());
var out = new java.io.FileWriter(file); var out = new java.io.FileWriter(file);
var text = new Segment(); var text = new guiPkgs.Segment();
text.setPartialReturn(true); text.setPartialReturn(true);
var charsLeft = doc.getLength(); var charsLeft = doc.getLength();
var offset = 0; var offset = 0;
var min;
while (charsLeft > 0) { while (charsLeft > 0) {
doc.getText(offset, java.lang.Math.min(4096, charsLeft), text); doc.getText(offset, Math.min(4096, charsLeft), text);
out.write(text.array, text.offset, text.count); out.write(text.array, text.offset, text.count);
charsLeft -= text.count; charsLeft -= text.count;
offset += text.count; offset += text.count;
progress.setValue(offset); progress.setValue(offset);
java.lang.Thread.sleep(10); java.lang.Thread.sleep(10);
} }
out.flush(); out.flush();
out.close(); out.close();
docChanged = false; docChanged = false;
...@@ -282,15 +285,15 @@ with (guiPkgs) { ...@@ -282,15 +285,15 @@ with (guiPkgs) {
var script = doc.getText(0, doc.getLength()); var script = doc.getText(0, doc.getLength());
var oldFile = engine.get(javax.script.ScriptEngine.FILENAME); var oldFile = engine.get(javax.script.ScriptEngine.FILENAME);
try { try {
if (this.engine == undefined) { if (engine == undefined) {
var m = new javax.script.ScriptEngineManager(); var m = new javax.script.ScriptEngineManager();
engine = m.getEngineByName("js"); engine = m.getEngineByName("nashorn");
} }
engine.put(javax.script.ScriptEngine.FILENAME, frame.title); engine.put(javax.script.ScriptEngine.FILENAME, frame.title);
engine.eval(script, context); engine.eval(script, context);
} catch (e) { } catch (e) {
error(e, "Script Error"); error(e, "Script Error");
// e.rhinoException.printStackTrace(); e.printStackTrace();
} finally { } finally {
engine.put(javax.script.ScriptEngine.FILENAME, oldFile); engine.put(javax.script.ScriptEngine.FILENAME, oldFile);
} }
...@@ -308,7 +311,7 @@ with (guiPkgs) { ...@@ -308,7 +311,7 @@ with (guiPkgs) {
// "hello world" // "hello world"
function actionHello() { function actionHello() {
showScript(arguments.callee.title, showScript(actionEval.title,
"alert('Hello, world');"); "alert('Hello, world');");
} }
actionHello.title = "Hello, World"; actionHello.title = "Hello, World";
...@@ -364,9 +367,9 @@ with (guiPkgs) { ...@@ -364,9 +367,9 @@ with (guiPkgs) {
" }\n" + " }\n" +
" };\n" + " };\n" +
"// use the above Runnable to create a Thread\n" + "// use the above Runnable to create a Thread\n" +
"java.lang.Thread(r).start();\n" + "new java.lang.Thread(r).start();\n" +
"// For simple one method interfaces, just pass script function\n" + "// For simple one method interfaces, just pass script function\n" +
"java.lang.Thread(function() { alert('world'); }).start();"); "new java.lang.Thread(function() { alert('world'); }).start();");
} }
actionJavaInterface.title = "Java Interfaces"; actionJavaInterface.title = "Java Interfaces";
...@@ -393,8 +396,8 @@ with (guiPkgs) { ...@@ -393,8 +396,8 @@ with (guiPkgs) {
*/ */
function actionHelpGlobals() { function actionHelpGlobals() {
var names = new java.util.ArrayList(); var names = new java.util.ArrayList();
for (var i in this) { for (var i in globalThis) {
var func = this[i]; var func = globalThis[i];
if (typeof(func) == "function" && if (typeof(func) == "function" &&
("docString" in func)) { ("docString" in func)) {
names.add(i); names.add(i);
...@@ -409,23 +412,23 @@ with (guiPkgs) { ...@@ -409,23 +412,23 @@ with (guiPkgs) {
helpDoc.append("<tr><td>"); helpDoc.append("<tr><td>");
helpDoc.append(name); helpDoc.append(name);
helpDoc.append("</td><td>"); helpDoc.append("</td><td>");
helpDoc.append(this[name].docString); helpDoc.append(globalThis[name].docString);
helpDoc.append("</td></tr>"); helpDoc.append("</td></tr>");
} }
helpDoc.append("</table>"); helpDoc.append("</table>");
var helpEditor = new JEditorPane(); var helpEditor = new guiPkgs.JEditorPane();
helpEditor.setContentType("text/html"); helpEditor.setContentType("text/html");
helpEditor.setEditable(false); helpEditor.setEditable(false);
helpEditor.setText(helpDoc.toString()); helpEditor.setText(helpDoc.toString());
var scroller = new JScrollPane(); var scroller = new guiPkgs.JScrollPane();
var port = scroller.getViewport(); var port = scroller.getViewport();
port.add(helpEditor); port.add(helpEditor);
var helpFrame = new JFrame("Help - Global Functions"); var helpFrame = new guiPkgs.JFrame("Help - Global Functions");
helpFrame.getContentPane().add("Center", scroller); helpFrame.getContentPane().add("Center", scroller);
helpFrame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); helpFrame.setDefaultCloseOperation(guiPkgs.WindowConstants.DISPOSE_ON_CLOSE);
helpFrame.pack(); helpFrame.pack();
helpFrame.setSize(500, 600); helpFrame.setSize(500, 600);
helpFrame.setVisible(true); helpFrame.setVisible(true);
...@@ -433,7 +436,7 @@ with (guiPkgs) { ...@@ -433,7 +436,7 @@ with (guiPkgs) {
// show a simple about message for scriptpad // show a simple about message for scriptpad
function actionAbout() { function actionAbout() {
alert("Scriptpad\nVersion 1.0", "Scriptpad"); alert("Scriptpad\nVersion 1.1", "Scriptpad");
} }
/* /*
...@@ -447,31 +450,31 @@ with (guiPkgs) { ...@@ -447,31 +450,31 @@ with (guiPkgs) {
{ {
menu: "File", menu: "File",
items: [ items: [
{ name: "New", action: actionNew , accel: KeyEvent.VK_N }, { name: "New", action: actionNew , accel: guiPkgs.KeyEvent.VK_N },
{ name: "Open...", action: actionOpen, accel: KeyEvent.VK_O }, { name: "Open...", action: actionOpen, accel: guiPkgs.KeyEvent.VK_O },
{ name: "Open URL...", action: actionOpenURL, accel: KeyEvent.VK_U }, { name: "Open URL...", action: actionOpenURL, accel: guiPkgs.KeyEvent.VK_U },
{ name: "Save", action: actionSave, accel: KeyEvent.VK_S }, { name: "Save", action: actionSave, accel: guiPkgs.KeyEvent.VK_S },
{ name: "Save As...", action: actionSaveAs }, { name: "Save As...", action: actionSaveAs },
{ name: "-" }, { name: "-" },
{ name: "Exit", action: actionExit } { name: "Exit", action: actionExit, accel: guiPkgs.KeyEvent.VK_Q }
] ]
}, },
{ {
menu: "Edit", menu: "Edit",
items: [ items: [
{ name: "Cut", action: actionCut, accel: KeyEvent.VK_X }, { name: "Cut", action: actionCut, accel: guiPkgs.KeyEvent.VK_X },
{ name: "Copy", action: actionCopy, accel: KeyEvent.VK_C }, { name: "Copy", action: actionCopy, accel: guiPkgs.KeyEvent.VK_C },
{ name: "Paste", action: actionPaste, accel: KeyEvent.VK_V }, { name: "Paste", action: actionPaste, accel: guiPkgs.KeyEvent.VK_V },
{ name: "-" }, { name: "-" },
{ name: "Select All", action: actionSelectAll, accel: KeyEvent.VK_A } { name: "Select All", action: actionSelectAll, accel: guiPkgs.KeyEvent.VK_A }
] ]
}, },
{ {
menu: "Tools", menu: "Tools",
items: [ items: [
{ name: "Run", action: actionRun, accel: KeyEvent.VK_R }, { name: "Run", action: actionRun, accel: guiPkgs.KeyEvent.VK_R }
] ]
}, },
...@@ -484,7 +487,7 @@ with (guiPkgs) { ...@@ -484,7 +487,7 @@ with (guiPkgs) {
{ name: actionJavaAccess.title, action: actionJavaAccess }, { name: actionJavaAccess.title, action: actionJavaAccess },
{ name: actionJavaBean.title, action: actionJavaBean }, { name: actionJavaBean.title, action: actionJavaBean },
{ name: actionJavaInterface.title, action: actionJavaInterface }, { name: actionJavaInterface.title, action: actionJavaInterface },
{ name: actionJavaImport.title, action: actionJavaImport }, { name: actionJavaImport.title, action: actionJavaImport }
] ]
}, },
...@@ -493,29 +496,29 @@ with (guiPkgs) { ...@@ -493,29 +496,29 @@ with (guiPkgs) {
items: [ items: [
{ name: "Global Functions", action: actionHelpGlobals }, { name: "Global Functions", action: actionHelpGlobals },
{ name: "-" }, { name: "-" },
{ name: "About Scriptpad", action: actionAbout }, { name: "About Scriptpad", action: actionAbout }
] ]
} }
]; ];
function setMenuAccelerator(mi, accel) { function setMenuAccelerator(mi, accel) {
var keyStroke = KeyStroke.getKeyStroke(accel, var keyStroke = guiPkgs.KeyStroke.getKeyStroke(accel,
Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(), false); guiPkgs.Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(), false);
mi.setAccelerator(keyStroke); mi.setAccelerator(keyStroke);
} }
// create a menubar using the above menu data // create a menubar using the above menu data
function createMenubar() { function createMenubar() {
var mb = new JMenuBar(); var mb = new guiPkgs.JMenuBar();
for (var m in menuData) { for (var m in menuData) {
var items = menuData[m].items; var items = menuData[m].items;
var menu = new JMenu(menuData[m].menu); var menu = new guiPkgs.JMenu(menuData[m].menu);
for (var i in items) { for (var i in items) {
if (items[i].name.equals("-")) { if (items[i].name.equals("-")) {
menu.addSeparator(); menu.addSeparator();
} else { } else {
var mi = new JMenuItem(items[i].name); var mi = new guiPkgs.JMenuItem(items[i].name);
var action = items[i].action; var action = items[i].action;
mi.addActionListener(action); mi.addActionListener(action);
var accel = items[i].accel; var accel = items[i].accel;
...@@ -525,8 +528,10 @@ with (guiPkgs) { ...@@ -525,8 +528,10 @@ with (guiPkgs) {
menu.add(mi); menu.add(mi);
} }
} }
mb.add(menu); mb.add(menu);
} }
return mb; return mb;
} }
...@@ -548,7 +553,7 @@ with (guiPkgs) { ...@@ -548,7 +553,7 @@ with (guiPkgs) {
return; return;
} }
var toolsMenu = frame.getJMenuBar().getMenu(toolsIndex); var toolsMenu = frame.getJMenuBar().getMenu(toolsIndex);
var mi = new JMenuItem(menuItem); var mi = new guiPkgs.JMenuItem(menuItem);
mi.addActionListener(action); mi.addActionListener(action);
if (accel) { if (accel) {
setMenuAccelerator(mi, accel); setMenuAccelerator(mi, accel);
...@@ -556,28 +561,27 @@ with (guiPkgs) { ...@@ -556,28 +561,27 @@ with (guiPkgs) {
toolsMenu.add(mi); toolsMenu.add(mi);
} }
// create Scriptpad frame // create Scriptpad frame
function createFrame() { function createFrame() {
frame = new JFrame(); frame = new guiPkgs.JFrame();
frame.setTitle(defaultTitle); frame.setTitle(defaultTitle);
frame.setBackground(Color.lightGray); frame.setBackground(guiPkgs.Color.lightGray);
frame.getContentPane().setLayout(new BorderLayout()); frame.getContentPane().setLayout(new guiPkgs.BorderLayout());
// create notepad panel // create notepad panel
var notepad = new JPanel(); var notepad = new guiPkgs.JPanel();
notepad.setBorder(BorderFactory.createEtchedBorder()); notepad.setBorder(guiPkgs.BorderFactory.createEtchedBorder());
notepad.setLayout(new BorderLayout()); notepad.setLayout(new guiPkgs.BorderLayout());
// create editor // create editor
editor = createEditor(); editor = createEditor();
var scroller = new JScrollPane(); var scroller = new guiPkgs.JScrollPane();
var port = scroller.getViewport(); var port = scroller.getViewport();
port.add(editor); port.add(editor);
// add editor to notepad panel // add editor to notepad panel
var panel = new JPanel(); var panel = new guiPkgs.JPanel();
panel.setLayout(new BorderLayout()); panel.setLayout(new guiPkgs.BorderLayout());
panel.add("Center", scroller); panel.add("Center", scroller);
notepad.add("Center", panel); notepad.add("Center", panel);
...@@ -586,7 +590,7 @@ with (guiPkgs) { ...@@ -586,7 +590,7 @@ with (guiPkgs) {
// set menu bar to frame and show the frame // set menu bar to frame and show the frame
frame.setJMenuBar(createMenubar()); frame.setJMenuBar(createMenubar());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setDefaultCloseOperation(guiPkgs.JFrame.EXIT_ON_CLOSE);
frame.pack(); frame.pack();
frame.setSize(500, 600); frame.setSize(500, 600);
} }
...@@ -594,7 +598,7 @@ with (guiPkgs) { ...@@ -594,7 +598,7 @@ with (guiPkgs) {
// show Scriptpad frame // show Scriptpad frame
function showFrame() { function showFrame() {
// set global variable by the name "window" // set global variable by the name "window"
this.window = frame; globalThis.window = frame;
// open new document // open new document
actionNew(); actionNew();
...@@ -616,8 +620,7 @@ with (guiPkgs) { ...@@ -616,8 +620,7 @@ with (guiPkgs) {
editor: editor, editor: editor,
addTool: addTool addTool: addTool
}; };
} };
}
/* /*
* Call the main and store Application object * Call the main and store Application object
...@@ -657,4 +660,3 @@ function loadUserInit() { ...@@ -657,4 +660,3 @@ function loadUserInit() {
} }
loadUserInit(); loadUserInit();
/* /*
* Copyright (c) 2006, 2011, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2006, 2013, Oracle and/or its affiliates. All rights reserved.
* *
* Redistribution and use in source and binary forms, with or without * Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions * modification, are permitted provided that the following conditions
...@@ -37,26 +37,24 @@ ...@@ -37,26 +37,24 @@
* this sample code. * this sample code.
*/ */
/* /*
* This function uses new Swing Desktop API in JDK 6. * This function uses new Swing Desktop API in JDK 6.
* To use this with scriptpad, open this in scriptpad * To use this with scriptpad, open this in scriptpad
* and use "Tools->Run Script" menu. * and use "Tools->Run Script" menu.
*/ */
function browse() { function browse() {
with (guiPkgs) {
var desktop = null; var desktop = null;
// Before more Desktop API is used, first check // Before more Desktop API is used, first check
// whether the API is supported by this particular // whether the API is supported by this particular
// virtual machine (VM) on this particular host. // virtual machine (VM) on this particular host.
if (Desktop.isDesktopSupported()) { if (java.awt.Desktop.isDesktopSupported()) {
desktop = Desktop.getDesktop(); desktop = java.awt.Desktop.getDesktop();
} else { } else {
alert("no desktop support"); alert("no desktop support");
return; return;
} }
if (desktop.isSupported(Desktop.Action.BROWSE)) { if (desktop.isSupported(java.awt.Desktop.Action.BROWSE)) {
var url = prompt("Address:"); var url = prompt("Address:");
if (url != null) { if (url != null) {
desktop.browse(new java.net.URI(url)); desktop.browse(new java.net.URI(url));
...@@ -64,11 +62,9 @@ function browse() { ...@@ -64,11 +62,9 @@ function browse() {
} else { } else {
alert("no browser support"); alert("no browser support");
} }
}
} }
if (this.application != undefined) { if (this.application != undefined) {
// add "Browse" menu item under "Tools" menu // add "Browse" menu item under "Tools" menu
this.application.addTool("Browse", browse); this.application.addTool("Browse", browse);
} }
/* /*
* Copyright (c) 2006, 2011, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2006, 2013, Oracle and/or its affiliates. All rights reserved.
* *
* Redistribution and use in source and binary forms, with or without * Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions * modification, are permitted provided that the following conditions
...@@ -37,7 +37,6 @@ ...@@ -37,7 +37,6 @@
* this sample code. * this sample code.
*/ */
/* /*
* This script adds "Insert File" mode menu item to "Tools" menu. * This script adds "Insert File" mode menu item to "Tools" menu.
* When selected, this menu shows a file dialog box and inserts * When selected, this menu shows a file dialog box and inserts
...@@ -48,18 +47,22 @@ if (this.application) { ...@@ -48,18 +47,22 @@ if (this.application) {
application.addTool("Insert File...", application.addTool("Insert File...",
function() { function() {
var file = fileDialog(); var file = fileDialog();
if (file) { if (file) {
var reader = new java.io.FileReader(file); var reader = new java.io.FileReader(file);
var arr = java.lang.reflect.Array.newInstance( var arr = java.lang.reflect.Array.newInstance(
java.lang.Character.TYPE, 8*1024); // 8K at a time java.lang.Character.TYPE, 8*1024); // 8K at a time
var buf = new java.lang.StringBuffer(); var buf = new java.lang.StringBuffer();
var numChars; var numChars;
while ((numChars = reader.read(arr, 0, arr.length)) > 0) { while ((numChars = reader.read(arr, 0, arr.length)) > 0) {
buf.append(arr, 0, numChars); buf.append(arr, 0, numChars);
} }
var pos = application.editor.caretPosition; var pos = application.editor.caretPosition;
var doc = application.editor.document; var doc = application.editor.document;
doc.insertString(pos, buf.toString(), null); doc.insertString(pos, buf.toString(), null);
} }
}) });
} }
/* /*
* Copyright (c) 2006, 2011, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2006, 2013, Oracle and/or its affiliates. All rights reserved.
* *
* Redistribution and use in source and binary forms, with or without * Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions * modification, are permitted provided that the following conditions
...@@ -37,19 +37,15 @@ ...@@ -37,19 +37,15 @@
* this sample code. * this sample code.
*/ */
/* /*
* This script adds "Line Wrap" mode menu item to "Tools" menu. * This script adds "Line Wrap" mode menu item to "Tools" menu.
* When selected, this menu toggles the current word wrap mode * When selected, this menu toggles the current word wrap mode
* of the editor. * of the editor.
*/ */
with (guiPkgs) {
function toggleLineWrap() { function toggleLineWrap() {
var wrap = application.editor.lineWrap; var wrap = application.editor.lineWrap;
application.editor.lineWrap = !wrap; application.editor.lineWrap = !wrap;
}
application.addTool("Line Wrap", toggleLineWrap);
} }
application.addTool("Line Wrap", toggleLineWrap);
/* /*
* Copyright (c) 2006, 2011, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2006, 2013, Oracle and/or its affiliates. All rights reserved.
* *
* Redistribution and use in source and binary forms, with or without * Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions * modification, are permitted provided that the following conditions
...@@ -37,32 +37,29 @@ ...@@ -37,32 +37,29 @@
* this sample code. * this sample code.
*/ */
/* /*
* This function uses new Swing Desktop API in JDK 6. * This function uses new Swing Desktop API in JDK 6.
* To use this with scriptpad, open this in scriptpad * To use this with scriptpad, open this in scriptpad
* and use "Tools->Run Script" menu. * and use "Tools->Run Script" menu.
*/ */
function mail() { function mail() {
with (guiPkgs) {
var desktop = null; var desktop = null;
// Before more Desktop API is used, first check // Before more Desktop API is used, first check
// whether the API is supported by this particular // whether the API is supported by this particular
// virtual machine (VM) on this particular host. // virtual machine (VM) on this particular host.
if (Desktop.isDesktopSupported()) { if (java.awt.Desktop.isDesktopSupported()) {
desktop = Desktop.getDesktop(); desktop = java.awt.Desktop.getDesktop();
} else { } else {
alert("no desktop support"); alert("no desktop support");
return; return;
} }
if (desktop.isSupported(Desktop.Action.MAIL)) { if (desktop.isSupported(java.awt.Desktop.Action.MAIL)) {
var mailTo = prompt("Mail To:"); var mailTo = prompt("Mail To:");
if (mailTo != null) { if (mailTo != null) {
desktop.mail(new java.net.URI("mailto", mailTo, null)); desktop.mail(new java.net.URI("mailto", mailTo, null));
} }
} }
}
} }
if (this.application != undefined) { if (this.application != undefined) {
......
/* /*
* Copyright (c) 2006, 2011, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2006, 2013, Oracle and/or its affiliates. All rights reserved.
* *
* Redistribution and use in source and binary forms, with or without * Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions * modification, are permitted provided that the following conditions
...@@ -37,29 +37,31 @@ ...@@ -37,29 +37,31 @@
* this sample code. * this sample code.
*/ */
// this checker function runs asynchronously // this checker function runs asynchronously
function memoryChecker(memoryBean, threshold, interval) { function memoryChecker(memoryBean, threshold, interval) {
while (true) { while (true) {
var memUsage = memoryBean.HeapMemoryUsage; var memUsage = memoryBean.HeapMemoryUsage;
var usage = memUsage.get("used") / (1024 * 1024); var usage = memUsage.get("used") / (1024 * 1024);
println(usage);
println("usage: " + usage);
if (usage > threshold) { if (usage > threshold) {
alert("Hey! heap usage threshold exceeded!"); alert("Hey! heap usage threshold exceeded!");
// after first alert just return. // after first alert just return.
return; return;
} }
java.lang.Thread.currentThread().sleep(interval);
java.lang.Thread.sleep(interval);
} }
} }
// add "Tools->Memory Monitor" menu item // add "Tools->Memory Monitor" menu item
if (this.application != undefined) { if (this.application != undefined) {
this.application.addTool("Memory Monitor", this.application.addTool("Memory Monitor",
function () { function () {
// show threshold box with default of 50 MB // show threshold box with default of 50 MB
var threshold = prompt("Threshold (mb)", 50); var threshold = prompt("Threshold (mb)", 50);
// show interval box with default of 1000 millisec. // show interval box with default of 1000 millisec.
var interval = prompt("Sample Interval (ms):", 1000); var interval = prompt("Sample Interval (ms):", 1000);
var memoryBean = mbean("java.lang:type=Memory"); var memoryBean = mbean("java.lang:type=Memory");
...@@ -69,4 +71,3 @@ if (this.application != undefined) { ...@@ -69,4 +71,3 @@ if (this.application != undefined) {
memoryChecker.future(memoryBean, threshold, interval); memoryChecker.future(memoryBean, threshold, interval);
}); });
} }
/* /*
* Copyright (c) 2006, 2011, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2006, 2013, Oracle and/or its affiliates. All rights reserved.
* *
* Redistribution and use in source and binary forms, with or without * Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions * modification, are permitted provided that the following conditions
...@@ -37,7 +37,6 @@ ...@@ -37,7 +37,6 @@
* this sample code. * this sample code.
*/ */
/* /*
* This script serves as a simple "monitored application". * This script serves as a simple "monitored application".
* Start this script using memory.bat or memory.sh in the * Start this script using memory.bat or memory.sh in the
...@@ -45,12 +44,11 @@ ...@@ -45,12 +44,11 @@
*/ */
java.lang.System.out.print("Enter a number and press enter:"); java.lang.System.out.print("Enter a number and press enter:");
java.lang.System["in"].read(); var input = java.lang.System["in"].read();
// allocate an integer array of "big enough" size! // allocate an integer array of "big enough" size!
var a = java.lang.reflect.Array.newInstance( var a = java.lang.reflect.Array.newInstance(
java.lang.Integer.TYPE, 1024*1024); java.lang.Integer.TYPE, input * 1024 * 1024);
// loop forever!
while (true);
// sleep some time...
java.lang.Thread.sleep(10*60*1000);
...@@ -30,7 +30,3 @@ ...@@ -30,7 +30,3 @@
# #
jrunscript -J-Dcom.sun.management.jmxremote.port=1090 -J-Dcom.sun.management.jmxremote.ssl=false -J-Dcom.sun.management.jmxremote.authenticate=false memory.js jrunscript -J-Dcom.sun.management.jmxremote.port=1090 -J-Dcom.sun.management.jmxremote.ssl=false -J-Dcom.sun.management.jmxremote.authenticate=false memory.js
/* /*
* Copyright (c) 2006, 2011, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2006, 2013, Oracle and/or its affiliates. All rights reserved.
* *
* Redistribution and use in source and binary forms, with or without * Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions * modification, are permitted provided that the following conditions
...@@ -37,7 +37,6 @@ ...@@ -37,7 +37,6 @@
* this sample code. * this sample code.
*/ */
/* /*
* This script adds "Selected Text Color" menu item to "Tools" menu. * This script adds "Selected Text Color" menu item to "Tools" menu.
* When selected, this menu changes the "selected text" color. * When selected, this menu changes the "selected text" color.
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册