001 /*
002 * Sonar, open source software quality management tool.
003 * Copyright (C) 2008-2012 SonarSource
004 * mailto:contact AT sonarsource DOT com
005 *
006 * Sonar 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 * Sonar 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
017 * License along with Sonar; if not, write to the Free Software
018 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
019 */
020 package org.sonar.colorizer;
021
022 import org.sonar.channel.CodeReader;
023 import org.sonar.channel.EndMatcher;
024
025 /**
026 * Detect Java constant
027 */
028 public class JavaConstantTokenizer extends Tokenizer {
029
030 private final String tagBefore;
031 private final String tagAfter;
032 private static final int DOT = '.';
033
034 public JavaConstantTokenizer(String tagBefore, String tagAfter) {
035 this.tagBefore = tagBefore;
036 this.tagAfter = tagAfter;
037 }
038
039 private boolean hasNextToken(CodeReader code) {
040 int lastChar = code.lastChar();
041 if (isJavaConstantStart(code.peek()) && !Character.isJavaIdentifierPart(lastChar) && !Character.isJavaIdentifierStart(lastChar)
042 && lastChar != DOT) {
043 String constant = code.peekTo(endTokenMatcher);
044 int nextCharAfterConstant = code.peek(constant.length() + 1)[constant.length()];
045 if (nextCharAfterConstant != 0 && Character.isJavaIdentifierPart(nextCharAfterConstant)) {
046 return false;
047 }
048 return true;
049 }
050 return false;
051 }
052
053 @Override
054 public boolean consume(CodeReader code, HtmlCodeBuilder codeBuilder) {
055 if (hasNextToken(code)) {
056 codeBuilder.appendWithoutTransforming(tagBefore);
057 code.popTo(endTokenMatcher, codeBuilder);
058 codeBuilder.appendWithoutTransforming(tagAfter);
059 return true;
060 } else {
061 return false;
062 }
063 }
064
065 private boolean isJavaConstantStart(int character) {
066 return Character.isUpperCase(character);
067 }
068
069 private boolean isJavaConstantPart(int character) {
070 return Character.isUpperCase(character) || character == '_' || character == '-' || Character.isDigit(character);
071 }
072
073 private EndMatcher endTokenMatcher = new EndMatcher() {
074
075 public boolean match(int endFlag) {
076 return !isJavaConstantPart(endFlag);
077 }
078 };
079
080 }