001 /* 002 * Copyright (C) 2010 eXo Platform SAS. 003 * 004 * This is free software; you can redistribute it and/or modify it 005 * under the terms of the GNU Lesser General Public License as 006 * published by the Free Software Foundation; either version 2.1 of 007 * the License, or (at your option) any later version. 008 * 009 * This software is distributed in the hope that it will be useful, 010 * but WITHOUT ANY WARRANTY; without even the implied warranty of 011 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 012 * Lesser General Public License for more details. 013 * 014 * You should have received a copy of the GNU Lesser General Public 015 * License along with this software; if not, write to the Free 016 * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 017 * 02110-1301 USA, or see the FSF site: http://www.fsf.org. 018 */ 019 020 package org.crsh.command; 021 022 import groovy.lang.Closure; 023 import groovy.lang.GroovyObjectSupport; 024 import groovy.lang.MissingMethodException; 025 import groovy.lang.MissingPropertyException; 026 027 /** 028 * A base command that should be subclasses by Groovy commands. For this matter it inherits the 029 * {@link GroovyObjectSupport} class. 030 * 031 * @author <a href="mailto:julien.viet@exoplatform.com">Julien Viet</a> 032 * @version $Revision$ 033 */ 034 public abstract class GroovyCommand extends GroovyObjectSupport { 035 036 protected abstract CommandContext getContext(); 037 038 @Override 039 public final Object invokeMethod(String name, Object args) { 040 try { 041 return super.invokeMethod(name, args); 042 } 043 catch (MissingMethodException e) { 044 CommandContext context = getContext(); 045 Object o = context.getAttributes().get(name); 046 if (o instanceof Closure) { 047 Closure closure = (Closure)o; 048 if (args instanceof Object[]) { 049 Object[] array = (Object[])args; 050 if (array.length == 0) { 051 return closure.call(); 052 } else { 053 return closure.call(array); 054 } 055 } else { 056 return closure.call(args); 057 } 058 } else { 059 throw e; 060 } 061 } 062 } 063 064 @Override 065 public final Object getProperty(String property) { 066 try { 067 return super.getProperty(property); 068 } 069 catch (MissingPropertyException e) { 070 CommandContext context = getContext(); 071 return context.getAttributes().get(property); 072 } 073 } 074 075 @Override 076 public final void setProperty(String property, Object newValue) { 077 try { 078 super.setProperty(property, newValue); 079 } 080 catch (MissingPropertyException e) { 081 CommandContext context = getContext(); 082 context.getAttributes().put(property, newValue); 083 } 084 } 085 }