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.script;
020
021import org.crsh.command.SyntaxException;
022import org.crsh.util.Utils;
023
024/**
025 * @author Julien Viet
026 */
027public class Token {
028
029  /** . */
030  public final String value;
031
032  /** . */
033  public final Token next;
034
035  public Token(String value, Token next) {
036    this.value = value;
037    this.next = next;
038  }
039
040  public PipeLineFactory createFactory() throws SyntaxException {
041    if (next != null) {
042      if (value == null) {
043        throw new SyntaxException("");
044      } else {
045        PipeLineFactory nextFactory = next.createFactory();
046        if (nextFactory != null) {
047          return new PipeLineFactory(value, nextFactory);
048        } else {
049          throw new SyntaxException("");
050        }
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}