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.groovy.closure;
020
021 import groovy.lang.Closure;
022 import org.crsh.command.CommandContext;
023 import org.crsh.command.CommandInvoker;
024
025 import java.io.IOException;
026
027 /** @author Julien Viet */
028 public class ClosureInvoker extends CommandInvoker<Object, Object> {
029
030 /** . */
031 private final Closure closure;
032
033 /** . */
034 private final Class<?> type;
035
036 /** . */
037 private CommandContext<? super Object> consumer;
038
039 public ClosureInvoker(Closure closure) {
040
041 // Resolve the closure consumed type
042 final Class<?> type;
043 Class[] parameterTypes = closure.getParameterTypes();
044 if (parameterTypes != null && parameterTypes.length > 0) {
045 type = parameterTypes[0];
046 } else {
047 type = Object.class;
048 }
049
050 //
051 this.type = type;
052 this.closure = closure;
053 }
054
055 public Class<Object> getProducedType() {
056 return Object.class;
057 }
058 public Class<Object> getConsumedType() {
059 return Object.class;
060 }
061 public void provide(Object element) throws IOException {
062 if (type.isInstance(element)) {
063 Object ret = closure.call(element);
064 if (ret != null) {
065 consumer.provide(ret);
066 }
067 }
068 }
069
070 public void open(CommandContext<? super Object> consumer) {
071 this.consumer = consumer;
072 ClosureDelegate delegate = new ClosureDelegate(consumer, closure.getOwner());
073 closure.setResolveStrategy(Closure.DELEGATE_FIRST);
074 closure.setDelegate(delegate);
075 }
076
077 public void flush() throws IOException {
078 consumer.flush();
079 }
080
081 public void close() {
082 consumer = null;
083 }
084 }