cox.jmatt.java.MathTools.demo
Class ScriptPanel

java.lang.Object
  extended by java.awt.Component
      extended by java.awt.Container
          extended by java.awt.Panel
              extended by cox.jmatt.java.MathTools.demo.ScriptPanel
All Implemented Interfaces:
java.awt.event.ActionListener, java.awt.image.ImageObserver, java.awt.MenuContainer, java.io.Serializable, java.util.EventListener, javax.accessibility.Accessible

public class ScriptPanel
extends java.awt.Panel
implements java.awt.event.ActionListener

ScriptPanel provides a very minimal scripting framework for the MathTools packages. It uses the javax.scripting.* API. The default ScriptPanel can be used as-is but it is also easily extended. The getEngineLoader(), scriptStarting() and scriptEnded() methods are designed to be overridden. The scriptStarting() method is called before script execution and has a chance to veto execution. The scriptEnded() method is called after the script stops, whether through completion or Exception.

If a custom ClassLoader is required, override getEngineLoader(). By default this method returns null. If, however, the '[]Enable URLClassLoader' box is checked, ScriptPanel attempts to build an URLClassLoader around the list of URLs provided on the URL Loader Panel.

For a list of the tools exposed and their names see CapCom.installStandardObjects().

Additionally, ScriptPanel sets the Global Pizza from the Pizza Panel before the script is executed. This makes parameters available through Console's getProperty() methods. The '[]Enable Console.setAuthenticator()' checkbox is used to set the CapCom.allowConsoleAuthenticatorAccess field.

When the script succeeds there are options for its return Object. The default implementation of scriptEnded() calls toString() on the (non-null!) return Object and prints it to the console. If the []processMathObject checkbox is enabled, the 'raw' return Object is processed via CapCom.processMathObject() prior to being String'ed. If a BasicMathPrinter is in place the String content of the returned Object is sent to the clipboard.

See Also:
Serialized Form

Nested Class Summary
 
Nested classes/interfaces inherited from class java.awt.Panel
java.awt.Panel.AccessibleAWTPanel
 
Nested classes/interfaces inherited from class java.awt.Container
java.awt.Container.AccessibleAWTContainer
 
Nested classes/interfaces inherited from class java.awt.Component
java.awt.Component.AccessibleAWTComponent, java.awt.Component.BaselineResizeBehavior, java.awt.Component.BltBufferStrategy, java.awt.Component.FlipBufferStrategy
 
Field Summary
static java.lang.String KEY_CONFIG
          This is the constant key used to select the Script Configuration panel in the main display area.
static java.lang.String KEY_PIZZA
          This is the constant key used to select the Script Pizza (Parameters) panel in the main display area.
static java.lang.String KEY_SCRIPT
          This is the constant key used to select the Script Source panel in the main display area.
static java.lang.String KEY_URL
          This is the constant key used to select the URL ClassLoader panel in the display area.
 
Fields inherited from class java.awt.Component
BOTTOM_ALIGNMENT, CENTER_ALIGNMENT, LEFT_ALIGNMENT, RIGHT_ALIGNMENT, TOP_ALIGNMENT
 
Fields inherited from interface java.awt.image.ImageObserver
ABORT, ALLBITS, ERROR, FRAMEBITS, HEIGHT, PROPERTIES, SOMEBITS, WIDTH
 
Constructor Summary
ScriptPanel()
           
ScriptPanel(java.awt.Dialog pParent)
          Create a ScriptPanel anchored to a Dialog.
ScriptPanel(java.awt.Frame pParent)
          Create a ScriptPanel anchored to a Frame.
 
Method Summary
 void actionPerformed(java.awt.event.ActionEvent aev)
          Handle all button clicks.
 void checkEnvironment()
          This method runs a check on the MathTools environment.
 void clearPizza(boolean pOkToClear)
          Clear the parameter area.
 void clearScript(boolean pOkToClear)
          Clear the script area.
 javax.script.ScriptEngine configureEngine(javax.script.ScriptEngine pEngine)
          Override this method to configure the ScriptEngine used to execute the script.
 void deliverPizza()
          Parse the Script Pizza area into a Properties object and set it as the Global Pizza.
 void extractPizza()
          Extract parameters from the Script Panel and put them into the Pizza Panel.
 java.lang.ClassLoader getEngineLoader()
          ScriptPanel calls this method before instaitiating a ScriptEngineFactory.
 java.lang.String getScript()
          Fetch the script from the Script Area.
 boolean isClassLoaderEnabled()
          Call this method to check the state of the '[]Enable URLClassLoader' box.
 void loadFile(java.lang.String pKey)
          Load a script or pizza from a FileDialog.
 void loadFile(java.lang.String pFile, java.lang.String pKey)
          Load a script or pizza from a file.
 void runScript()
          This method is called when the [Run Script] button is clicked.
 java.awt.Panel scriptConfigPanel()
          The Script Config Panel has all the configuration options necessary to run ScriptPanel.
 void scriptEnded(java.lang.Object pRetObj, java.lang.Throwable pError)
          This method is called when a script ends, whether normally or otherwise.
 java.awt.Panel scriptPizzaPanel()
          The Script Pizza panel holds a parameter panel.
 java.awt.Panel scriptSourcePanel()
          The Script Source panel holds the script plus machinery to run and otherwise support it.
 boolean scriptStarting()
          This method is called after the ScriptEngine is created but before the script is executed.
 void selectPanel(java.lang.String pKey)
          Specifically select one of the panels to show.
 void setScript(java.lang.String pScript)
          Put a script in the Script Area.
 java.awt.Panel standardGUI()
          Standard GUI is provided to allow FULL construction before messing with the CardLayout.
 
Methods inherited from class java.awt.Panel
addNotify, getAccessibleContext
 
Methods inherited from class java.awt.Container
add, add, add, add, add, addContainerListener, addImpl, addPropertyChangeListener, addPropertyChangeListener, applyComponentOrientation, areFocusTraversalKeysSet, countComponents, deliverEvent, doLayout, findComponentAt, findComponentAt, getAlignmentX, getAlignmentY, getComponent, getComponentAt, getComponentAt, getComponentCount, getComponents, getComponentZOrder, getContainerListeners, getFocusTraversalKeys, getFocusTraversalPolicy, getInsets, getLayout, getListeners, getMaximumSize, getMinimumSize, getMousePosition, getPreferredSize, insets, invalidate, isAncestorOf, isFocusCycleRoot, isFocusCycleRoot, isFocusTraversalPolicyProvider, isFocusTraversalPolicySet, layout, list, list, locate, minimumSize, paint, paintComponents, paramString, preferredSize, print, printComponents, processContainerEvent, processEvent, remove, remove, removeAll, removeContainerListener, removeNotify, setComponentZOrder, setFocusCycleRoot, setFocusTraversalKeys, setFocusTraversalPolicy, setFocusTraversalPolicyProvider, setFont, setLayout, transferFocusBackward, transferFocusDownCycle, update, validate, validateTree
 
Methods inherited from class java.awt.Component
action, add, addComponentListener, addFocusListener, addHierarchyBoundsListener, addHierarchyListener, addInputMethodListener, addKeyListener, addMouseListener, addMouseMotionListener, addMouseWheelListener, bounds, checkImage, checkImage, coalesceEvents, contains, contains, createImage, createImage, createVolatileImage, createVolatileImage, disable, disableEvents, dispatchEvent, enable, enable, enableEvents, enableInputMethods, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, firePropertyChange, getBackground, getBaseline, getBaselineResizeBehavior, getBounds, getBounds, getColorModel, getComponentListeners, getComponentOrientation, getCursor, getDropTarget, getFocusCycleRootAncestor, getFocusListeners, getFocusTraversalKeysEnabled, getFont, getFontMetrics, getForeground, getGraphics, getGraphicsConfiguration, getHeight, getHierarchyBoundsListeners, getHierarchyListeners, getIgnoreRepaint, getInputContext, getInputMethodListeners, getInputMethodRequests, getKeyListeners, getLocale, getLocation, getLocation, getLocationOnScreen, getMouseListeners, getMouseMotionListeners, getMousePosition, getMouseWheelListeners, getName, getParent, getPeer, getPropertyChangeListeners, getPropertyChangeListeners, getSize, getSize, getToolkit, getTreeLock, getWidth, getX, getY, gotFocus, handleEvent, hasFocus, hide, imageUpdate, inside, isBackgroundSet, isCursorSet, isDisplayable, isDoubleBuffered, isEnabled, isFocusable, isFocusOwner, isFocusTraversable, isFontSet, isForegroundSet, isLightweight, isMaximumSizeSet, isMinimumSizeSet, isOpaque, isPreferredSizeSet, isShowing, isValid, isVisible, keyDown, keyUp, list, list, list, location, lostFocus, mouseDown, mouseDrag, mouseEnter, mouseExit, mouseMove, mouseUp, move, nextFocus, paintAll, postEvent, prepareImage, prepareImage, printAll, processComponentEvent, processFocusEvent, processHierarchyBoundsEvent, processHierarchyEvent, processInputMethodEvent, processKeyEvent, processMouseEvent, processMouseMotionEvent, processMouseWheelEvent, remove, removeComponentListener, removeFocusListener, removeHierarchyBoundsListener, removeHierarchyListener, removeInputMethodListener, removeKeyListener, removeMouseListener, removeMouseMotionListener, removeMouseWheelListener, removePropertyChangeListener, removePropertyChangeListener, repaint, repaint, repaint, repaint, requestFocus, requestFocus, requestFocusInWindow, requestFocusInWindow, reshape, resize, resize, setBackground, setBounds, setBounds, setComponentOrientation, setCursor, setDropTarget, setEnabled, setFocusable, setFocusTraversalKeysEnabled, setForeground, setIgnoreRepaint, setLocale, setLocation, setLocation, setMaximumSize, setMinimumSize, setName, setPreferredSize, setSize, setSize, setVisible, show, show, size, toString, transferFocus, transferFocusUpCycle
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Field Detail

KEY_SCRIPT

public static final java.lang.String KEY_SCRIPT
This is the constant key used to select the Script Source panel in the main display area.

See Also:
Constant Field Values

KEY_PIZZA

public static final java.lang.String KEY_PIZZA
This is the constant key used to select the Script Pizza (Parameters) panel in the main display area.

See Also:
Constant Field Values

KEY_CONFIG

public static final java.lang.String KEY_CONFIG
This is the constant key used to select the Script Configuration panel in the main display area.

See Also:
Constant Field Values

KEY_URL

public static final java.lang.String KEY_URL
This is the constant key used to select the URL ClassLoader panel in the display area.

See Also:
Constant Field Values
Constructor Detail

ScriptPanel

public ScriptPanel()

ScriptPanel

public ScriptPanel(java.awt.Frame pParent)
Create a ScriptPanel anchored to a Frame. This provides an anchor for the FileDialog used to load things.

Parameters:
pParent - The Frame used to anchor a FileDialog.

ScriptPanel

public ScriptPanel(java.awt.Dialog pParent)
Create a ScriptPanel anchored to a Dialog. This provides an anchor for the FileDialog used to load things.

Parameters:
pParent - The Dialog used to anchor a FileDialog.
Method Detail

standardGUI

public final java.awt.Panel standardGUI()
Standard GUI is provided to allow FULL construction before messing with the CardLayout. To do so in one step: '(new ScriptPanel()).standardGUI();'. ScriptPanel automatically adds a Frame-anchored instance of URLLoaderPanel under KEY_URL.


scriptSourcePanel

public final java.awt.Panel scriptSourcePanel()
The Script Source panel holds the script plus machinery to run and otherwise support it. It is added to the CardLayout using KEY_SCRIPT.


scriptPizzaPanel

public final java.awt.Panel scriptPizzaPanel()
The Script Pizza panel holds a parameter panel. When the script is executed this is set as the Global Pizza. Select using KEY_PIZZA.


scriptConfigPanel

public final java.awt.Panel scriptConfigPanel()
The Script Config Panel has all the configuration options necessary to run ScriptPanel. Select with KEY_CONFIG.


selectPanel

public void selectPanel(java.lang.String pKey)
Specifically select one of the panels to show.

Parameters:
pKey - One of the KEY_ constants to select a panel.

checkEnvironment

public void checkEnvironment()
This method runs a check on the MathTools environment. It checks available XML tools (SAX, DOM etc.) and scripting languages (ScriptEngineManager). The results are printed and sent to the clipboard via processMathObject().


actionPerformed

public void actionPerformed(java.awt.event.ActionEvent aev)
Handle all button clicks. When overriding this method, be sure to call super.actiionPerformed() to keep the panel working!

Specified by:
actionPerformed in interface java.awt.event.ActionListener

clearScript

public void clearScript(boolean pOkToClear)
Clear the script area. The default implementation clears on the state of the '[]Lock all clear functions' Checkbox.

Parameters:
pOkToClear - true to REALLY clear the script area, false not to.

clearPizza

public void clearPizza(boolean pOkToClear)
Clear the parameter area. The default implementation clears on the state of the '[]Lock all clear functions' Checkbox.

Parameters:
pOkToClear - true to REALLY clear the pizza area, false not to.

deliverPizza

public void deliverPizza()
Parse the Script Pizza area into a Properties object and set it as the Global Pizza.


extractPizza

public void extractPizza()
Extract parameters from the Script Panel and put them into the Pizza Panel. This is done according to the 'prefix' TextField next to the [Extract] Button. Anything starting with that is extracted, the prefix stripped and the rest placed into the Pizza Panel. The default value is '#PARAM'.


loadFile

public void loadFile(java.lang.String pKey)
Load a script or pizza from a FileDialog. This method only works if its ScriptPanel was created around a Frame or a Dialog.

Parameters:
pKey - The KEY_ constant determining where to load.

loadFile

public void loadFile(java.lang.String pFile,
                     java.lang.String pKey)
Load a script or pizza from a file. This method expects a text file as it will attempt to create a FileReader and copy it to the Script Area. Any Exceptions are reported at the Error level. If the filename or key is null or empty this method returns silently. The pKey parameter determines where to send the load: KEY_SCRIPT loads a script, KEY_PIZZA loads into the parameter panel. If pKey is not valid or not recognized the load goes to CapCom.println();

Parameters:
pFile - The name of the file to load.
pKey - The place to send the loaded file.

getScript

public java.lang.String getScript()
Fetch the script from the Script Area.


setScript

public void setScript(java.lang.String pScript)
Put a script in the Script Area.


runScript

public void runScript()

This method is called when the [Run Script] button is clicked. It first calls scriptStarting(). If scriptStarting() returns true, script execution continues. First a ScriptEngineFactory is instantiated using the provided ClassLoader, if provided. A ScriptEngine is then created using the method selected on the Config panel. If the data field is null or empty a Javascript engine is created. If this fails, the process stops with an Error message.

The next method call is to scriptStarting(). If it returns false the process stops. Otherwise, the standard Objects are added via the Engine's put() method. Once that is done, the script is executed using the engine's eval() method. This part of the code is in a try/catch block so any Exceptions thrown by the script won't crash the entire application. Instead, if an Exception is thrown, it is reported to scriptEnded().

The exact sequence in which things happen is:

  1. The script is checked for validity. If it is null or empty this method returns silently.
  2. CapCom's MathClassLoader is set from the URLLoaderPanel.
  3. A ScriptEngineManager is instantiated, using getEngineLoader() if it provides one.
  4. A ScriptEngine is created by the method selected. If the TextField is empty, a Javascript engine is attempted.
  5. configureEngine() is called.
  6. The Global Pizza is set from the Pizza Panel.
  7. scriptStarting() is called. If it returns false execution stops and no Exception is thrown.
  8. The Standard Objects are put() into the ScriptEngine via CapCom.installStandardObjects().
  9. Set CapCom allowConsoleAuthenticatorAccess and allowAccessories.
  10. The script is executed via ScriptEngine.eval().
  11. MathDBC.closeAll() is called, regardless of any Exception thrown.
  12. MathFileIO.closeAll() is called. This happens regardless of any Exception thrown.
  13. The scriptEnded() method is called with the return value from the script and null for the Exception.

If the script itself is null or empty none of this happens! runScript() returns silently. If an Exception occurs anywhere in the process (except false from scriptStarting()) the scriptEnded() method is called immediately with null for the Object and the Exception that was thrown.


isClassLoaderEnabled

public final boolean isClassLoaderEnabled()
Call this method to check the state of the '[]Enable URLClassLoader' box.


getEngineLoader

public java.lang.ClassLoader getEngineLoader()
ScriptPanel calls this method before instaitiating a ScriptEngineFactory. If the '[]Enable URLClassLoader' box is unchecked or an error occurs this method returns null. The return value, if not null, is used to create a ScriptEngineFactory. If the 'Enable' box is checked, the ClassLoader returned is the one stored by CapCom.

Returns:
A ClassLoader to use for creating ScriptEngineFactories or null to use the default.

configureEngine

public javax.script.ScriptEngine configureEngine(javax.script.ScriptEngine pEngine)
Override this method to configure the ScriptEngine used to execute the script. Specifically, if extra Objects are needed by the script this is the place to install them. The ScriptEngine parameter is the one created from the options selected and ScriptPanel expects a valid engine to be returned. If the return value is null it will be detected and execution will stop. If the parameter supplied is null, engine creation failed. The default implementation returns the ScriptEngine unchanged. NOTE: installStandardObjects() is called AFTER this method, so any Object stored under one of the Standard names will be overwritten.

Parameters:
pEngine - The ScriptEngine created to execute the script.
Returns:
The freshly-configured ScriptEngine to execute the script.

scriptStarting

public boolean scriptStarting()
This method is called after the ScriptEngine is created but before the script is executed. Override it to do pre-script stuff and, possibly, veto execution of the script. The default implementation prints a Debug message and returns true.

Returns:
true to continue running the script, false to abort.

scriptEnded

public void scriptEnded(java.lang.Object pRetObj,
                        java.lang.Throwable pError)

This method is called when a script ends, whether normally or otherwise. If it ends normally, the Object parameter contains whatever the script itself returned. If execution of the script threw an Exception, the Object parameter is null and the Exception is passed. Unless scriptStarting() returns false or there is no script, this method WILL be called.

The default implementation reports any Exceptions at Error level. If the []processMathObject Checkbox is enabled, the Object returned from the script is sent to CapCom.processMathObject() and its return value replaces that of the 'raw' return Object. For BasicMathPrinter this sends the String content to the clipboard. If the Object present after all of this is null, this is reported at Debug level, otherwise its toString() method is called and printed.

NOTE: If the 'raw' return Object is null this method checks CapCom for anything stored using the MathConsole.sReturn() method. If that Object is not null it replaces pRetObj for processing.

Parameters:
pRetObj - The Object a successful execution returns, which may be null.
pError - The Exception thrown if something awful happens. If this is the case, pRetObj is automatically null.