001 /* 002 * Copyright (C) 2012 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 package org.crsh.lang.impl.groovy.closure; 020 021 import groovy.lang.GroovyObjectSupport; 022 import org.codehaus.groovy.runtime.InvokerHelper; 023 import org.crsh.command.CommandContext; 024 import org.crsh.lang.impl.groovy.Helper; 025 import org.crsh.shell.impl.command.InvocationContextImpl; 026 import org.crsh.util.SafeCallable; 027 028 /** @author Julien Viet */ 029 class ClosureDelegate extends GroovyObjectSupport { 030 031 /** . */ 032 private final CommandContext context; 033 034 /** . */ 035 private final Object owner; 036 037 public ClosureDelegate(CommandContext context, Object owner) { 038 this.context = context; 039 this.owner = owner; 040 } 041 042 public CommandContext getContext() { 043 return context; 044 } 045 046 @Override 047 public Object getProperty(String property) { 048 if ("context".equals(property)) { 049 return context; 050 } else { 051 Object value = Helper.resolveProperty(new InvocationContextImpl(context), property); 052 if (value != null) { 053 return value; 054 } else { 055 value = InvokerHelper.getProperty(owner, property); 056 } 057 return value; 058 } 059 } 060 061 @Override 062 public Object invokeMethod(String name, Object args) { 063 SafeCallable runnable = Helper.resolveMethodInvocation(new InvocationContextImpl(context), name, args); 064 if (runnable != null) { 065 return runnable.call(); 066 } else { 067 return InvokerHelper.invokeMethod(owner, name, args); 068 } 069 } 070 }