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.impl.script;
020
021import org.crsh.shell.ErrorKind;
022import org.crsh.shell.impl.command.spi.CommandException;
023import org.crsh.util.Utils;
024
025/**
026 * @author Julien Viet
027 */
028public class Token {
029
030  /** . */
031  public final String value;
032
033  /** . */
034  public final Token next;
035
036  public Token(String value, Token next) {
037    if (value == null) {
038      throw new NullPointerException("No null value");
039    }
040    this.value = value;
041    this.next = next;
042  }
043
044  public PipeLineFactory createFactory() throws CommandException {
045    if (next != null) {
046      PipeLineFactory nextFactory = next.createFactory();
047      if (nextFactory != null) {
048        return new PipeLineFactory(value, nextFactory);
049      } else {
050        throw new CommandException(ErrorKind.SYNTAX, "");
051      }
052    } else {
053      return Utils.notBlank(value) ? new PipeLineFactory(value, null) : null;
054    }
055  }
056
057  public Token getLast() {
058    return next != null ? next.getLast() : this;
059  }
060
061  public static Token parse(CharSequence s) {
062    return parse(s, 0);
063  }
064
065  public static Token parse(final CharSequence s, final int index) {
066    Character lastQuote = null;
067    int pos = index;
068    while (pos < s.length()) {
069      char c = s.charAt(pos);
070      if (lastQuote == null) {
071        if (c == '|') {
072          break;
073        } else if (c == '"' || c == '\'') {
074          lastQuote = c;
075        }
076      } else {
077        if (lastQuote == c) {
078          lastQuote = null;
079        }      }
080      pos++;
081    }
082    Token next = pos < s.length() ? parse(s, pos + 1) : null;
083    return new Token(s.subSequence(index, pos).toString(), next);
084  }
085}