/*
* The MIT License
*
* Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package hudson.util.spring;
import groovy.lang.Binding;
import groovy.lang.Closure;
import groovy.lang.GroovyObject;
import groovy.lang.MissingMethodException;
import groovy.lang.MissingPropertyException;
import groovy.lang.Script;
/**
* {@link Script} that performs method invocations and property access like {@link Closure} does.
*
* <p>
* For example, when the script is:
*
* <pre>
* a = 1;
* b(2);
* <pre>
*
* <p>
* Using {@link ClosureScript} as the base class would run it as:
*
* <pre>
* delegate.a = 1;
* delegate.b(2);
* </pre>
*
* ... whereas in plain {@link Script}, this will be run as:
*
* <pre>
* binding.setProperty("a",1);
* ((Closure)binding.getProperty("b")).call(2);
* </pre>
*
* @author Kohsuke Kawaguchi
*/
// TODO: moved to stapler
public abstract class ClosureScript extends Script {
private GroovyObject delegate;
protected ClosureScript() {
super();
}
protected ClosureScript(Binding binding) {
super(binding);
}
/**
* Sets the delegation target.
*/
public void setDelegate(GroovyObject delegate) {
this.delegate = delegate;
}
@Override
public Object invokeMethod(String name, Object args) {
try {
return delegate.invokeMethod(name,args);
} catch (MissingMethodException mme) {
return super.invokeMethod(name, args);
}
}
@Override
public Object getProperty(String property) {
try {
return delegate.getProperty(property);
} catch (MissingPropertyException e) {
return super.getProperty(property);
}
}
@Override
public void setProperty(String property, Object newValue) {
try {
delegate.setProperty(property,newValue);
} catch (MissingPropertyException e) {
super.setProperty(property,newValue);
}
}
}