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 */ 019package org.crsh.lang.groovy.closure; 020 021import groovy.lang.GroovyObjectSupport; 022import groovy.lang.GroovyRuntimeException; 023import org.codehaus.groovy.runtime.InvokerHelper; 024import org.crsh.command.CommandContext; 025import org.crsh.shell.impl.command.InvocationContextImpl; 026 027import java.io.IOException; 028import java.lang.reflect.UndeclaredThrowableException; 029 030/** @author Julien Viet */ 031class ClosureDelegate extends GroovyObjectSupport { 032 033 /** . */ 034 private final CommandContext context; 035 036 /** . */ 037 private final Object owner; 038 039 public ClosureDelegate(CommandContext context, Object owner) { 040 this.context = context; 041 this.owner = owner; 042 } 043 044 public CommandContext getContext() { 045 return context; 046 } 047 048 @Override 049 public Object getProperty(String property) { 050 if ("context".equals(property)) { 051 return context; 052 } else { 053 Object value = InvokerHelper.getProperty(owner, property); 054 if (value instanceof PipeLineClosure) { 055 PipeLineClosure closure = (PipeLineClosure)value; 056 value = closure.bind(new InvocationContextImpl<Object>(context)); 057 } 058 return value; 059 } 060 } 061 062 @Override 063 public Object invokeMethod(String name, Object args) { 064 Object result = InvokerHelper.invokeMethod(owner, name, args); 065 if (result instanceof PipeLineInvoker) { 066 try { 067 PipeLineInvoker invoker = (PipeLineInvoker)result; 068 invoker.invoke(new InvocationContextImpl<Object>(context)); 069 return null; 070 } 071 catch (IOException e) { 072 throw new GroovyRuntimeException(e); 073 } 074 catch (UndeclaredThrowableException e) { 075 throw new GroovyRuntimeException(e.getCause()); 076 } 077 } else { 078 return result; 079 } 080 } 081}