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 org.codehaus.groovy.runtime.InvokerInvocationException;
022 import org.crsh.shell.impl.command.spi.CommandCreationException;
023 import org.crsh.shell.impl.command.spi.CommandInvoker;
024 import org.crsh.command.InvocationContext;
025 import org.crsh.command.ScriptException;
026 import org.crsh.shell.impl.command.pipeline.PipeLine;
027
028 import java.io.IOException;
029 import java.lang.reflect.UndeclaredThrowableException;
030 import java.util.LinkedList;
031
032 /** @author Julien Viet */
033 public class PipeLineInvoker {
034
035 /** . */
036 private final PipeLineClosure closure;
037
038 /** . */
039 private final Object[] args;
040
041 public PipeLineInvoker(PipeLineClosure closure, Object[] args) {
042 this.closure = closure;
043 this.args = args;
044 }
045
046 public void invoke(InvocationContext<Object> context) throws IOException, UndeclaredThrowableException {
047
048 //
049 PipeLineInvocationContext inner = new PipeLineInvocationContext(context, false);
050 LinkedList<CommandInvoker> pipe;
051 try {
052 pipe = closure.resolve2(args);
053 }
054 catch (CommandCreationException e) {
055 throw new UndeclaredThrowableException(e);
056 }
057 CommandInvoker[] array = pipe.toArray(new CommandInvoker[pipe.size()]);
058 PipeLine pipeLine = new PipeLine(array);
059
060 //
061 try {
062 pipeLine.open(inner);
063 pipeLine.flush();
064
065 }
066 catch (ScriptException e) {
067 Throwable cause = e.getCause();
068 if (cause != null) {
069 throw new InvokerInvocationException(cause);
070 } else {
071 throw e;
072 }
073 } finally {
074 // This is on purpose
075 pipeLine.close();
076 }
077 }
078 }