001: package org.osbl.agent.model.action;
002:
003: import org.osbl.agent.model.Action;
004: import org.osbl.agent.model.Rule;
005: import org.osbl.agent.model.RuleContext;
006:
007: import bsh.EvalError;
008: import bsh.Interpreter;
009:
010: /**
011: * This Action executes a Beanshell script.
012: *
013: * Scripts access the target object through the pre-defined "subject" variable.
014: *
015: * @author Sebastian Nozzi.
016: */
017: public class BeanShellAction implements Action {
018:
019: /** The script. */
020: private String script;
021:
022: /**
023: * Instantiates a new BeanSellAction with a given script.
024: *
025: * @param script the beanshell script
026: */
027: public BeanShellAction(String script) {
028: setScript(script);
029: }
030:
031: /**
032: * Instantiates a new BeanSellAction. It will contain an empty script.
033: */
034: public BeanShellAction() {
035: this ("");
036: }
037:
038: /**
039: * Gets the script.
040: *
041: * @return the script
042: */
043: public String getScript() {
044: return script;
045: }
046:
047: /**
048: * Sets the script.
049: *
050: * @param script the new script
051: */
052: public void setScript(String script) {
053:
054: this .script = script;
055: }
056:
057: /*
058: * (non-Javadoc)
059: *
060: * @see org.osbl.agent.model.action.Action#execute(org.osbl.agent.model.RuleContext)
061: */
062: public void execute(RuleContext context) {
063:
064: // Only attemp to execute the script if there is something to begin with
065: if (script != null && script.equals("") == false) {
066:
067: // Instantiate a BeanShell interpreter
068: Interpreter bsh = new Interpreter();
069:
070: try {
071: // Predefine variable "subject" with our subjectInstance...
072: // the script can thus reference a variable "subject" and access its
073: // methods and fields.
074: bsh.set("subject", context.getTargetObject());
075:
076: // Evaluate the script, return value is of no interest to us.
077: bsh.eval(script);
078:
079: } catch (EvalError e) {
080: e.printStackTrace();
081: }
082: }
083: }
084:
085: /* (non-Javadoc)
086: * @see java.lang.Object#equals(java.lang.Object)
087: */
088: public boolean equals(Object obj) {
089:
090: if (this == obj)
091: return true;
092:
093: if (obj instanceof BeanShellAction == false)
094: return false;
095:
096: BeanShellAction other = (BeanShellAction) obj;
097:
098: return Rule.propertyEquals(script, other.script);
099: }
100:
101: }
|