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 020 package org.crsh.shell.impl.command; 021 022 import org.crsh.command.CommandInvoker; 023 import org.crsh.command.NoSuchCommandException; 024 import org.crsh.command.ShellCommand; 025 import org.crsh.text.Chunk; 026 027 import java.util.LinkedList; 028 import java.util.regex.Pattern; 029 030 /** 031 * A factory for a pipeline. 032 */ 033 public class PipeLineFactory { 034 035 /** . */ 036 final String line; 037 038 /** . */ 039 final String name; 040 041 /** . */ 042 final String rest; 043 044 /** . */ 045 final PipeLineFactory next; 046 047 public String getLine() { 048 return line; 049 } 050 051 PipeLineFactory(String line, PipeLineFactory next) { 052 053 Pattern p = Pattern.compile("^\\s*(\\S+)"); 054 java.util.regex.Matcher m = p.matcher(line); 055 String name = null; 056 String rest = null; 057 if (m.find()) { 058 name = m.group(1); 059 rest = line.substring(m.end()); 060 } 061 062 // 063 this.name = name; 064 this.rest = rest; 065 this.line = line; 066 this.next = next; 067 } 068 069 public CommandInvoker<Void, Chunk> create(CRaSHSession session) throws NoSuchCommandException { 070 071 // 072 LinkedList<CommandInvoker> pipes = new LinkedList<CommandInvoker>(); 073 for (PipeLineFactory current = this;current != null;current = current.next) { 074 CommandInvoker commandInvoker = null; 075 if (current.name != null) { 076 ShellCommand command = session.crash.getCommand(current.name); 077 if (command != null) { 078 commandInvoker = command.resolveInvoker(current.rest); 079 } 080 } 081 if (commandInvoker == null) { 082 throw new NoSuchCommandException(current.name); 083 } 084 pipes.add(commandInvoker); 085 } 086 087 // 088 return new PipeLine(pipes.toArray(new CommandInvoker[pipes.size()])); 089 } 090 091 PipeLineFactory getLast() { 092 if (next != null) { 093 return next.getLast(); 094 } 095 return this; 096 } 097 }