001/*
002 * SonarQube, open source software quality management tool.
003 * Copyright (C) 2008-2013 SonarSource
004 * mailto:contact AT sonarsource DOT com
005 *
006 * SonarQube is free software; you can redistribute it and/or
007 * modify it under the terms of the GNU Lesser General Public
008 * License as published by the Free Software Foundation; either
009 * version 3 of the License, or (at your option) any later version.
010 *
011 * SonarQube is distributed in the hope that it will be useful,
012 * but WITHOUT ANY WARRANTY; without even the implied warranty of
013 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
014 * Lesser General Public License for more details.
015 *
016 * You should have received a copy of the GNU Lesser General Public License
017 * along with this program; if not, write to the Free Software Foundation,
018 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
019 */
020package org.sonar.channel;
021
022import java.util.regex.Matcher;
023import java.util.regex.Pattern;
024
025/**
026 * The RegexChannel can be used to be called each time the next characters in the character stream match a regular expression
027 */
028public abstract class RegexChannel<O> extends Channel<O> {
029
030  private final StringBuilder tmpBuilder = new StringBuilder();
031  private final Matcher matcher;
032
033  /**
034   * Create a RegexChannel object with the required regular expression
035   *
036   * @param regex
037   *          regular expression to be used to try matching the next characters in the stream
038   */
039  public RegexChannel(String regex) {
040    matcher = Pattern.compile(regex).matcher("");
041  }
042
043  @Override
044  public final boolean consume(CodeReader code, O output) {
045    if (code.popTo(matcher, tmpBuilder) > 0) {
046      consume(tmpBuilder, output);
047      tmpBuilder.delete(0, tmpBuilder.length());
048      return true;
049    }
050    return false;
051  }
052
053  /**
054   * The consume method is called each time the regular expression used to create the RegexChannel object matches the next characters in the
055   * character streams.
056   *
057   * @param token
058   *          the token consumed in the character stream and matching the regular expression
059   * @param the
060   *          OUPUT object which can be optionally fed
061   */
062  protected abstract void consume(CharSequence token, O output);
063
064}