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 */ 020package org.sonar.colorizer; 021 022import java.util.HashMap; 023import java.util.Map; 024 025public class HtmlCodeBuilder implements Appendable { 026 027 private StringBuilder colorizedCode = new StringBuilder(); 028 private Map variables = new HashMap(); // stateful data 029 030 public Appendable append(CharSequence csq) { 031 for (int i = 0; i < csq.length(); i++) { 032 append(csq.charAt(i)); 033 } 034 return this; 035 } 036 037 public Appendable append(char c) { 038 if (c == '<') { 039 colorizedCode.append("<"); 040 } else if (c == '>') { 041 colorizedCode.append(">"); 042 } else { 043 colorizedCode.append(c); 044 } 045 return this; 046 } 047 048 public Appendable append(CharSequence csq, int start, int end) { 049 for (int i = start; i < end; i++) { 050 append(csq.charAt(i)); 051 } 052 return this; 053 } 054 055 public void appendWithoutTransforming(String htmlTag) { 056 colorizedCode.append(htmlTag); 057 } 058 059 @Override 060 public String toString() { 061 return colorizedCode.toString(); 062 } 063 064 public StringBuilder getColorizedCode() { 065 return colorizedCode; 066 } 067 068 /** 069 * Save a stateful variable. 070 * 071 * @param key 072 * can NOT be null 073 * @param value 074 * can be null 075 */ 076 public void setVariable(Object key, Object value) { 077 variables.put(key, value); 078 } 079 080 /** 081 * Get a stateful variable. Return null if not found. 082 */ 083 public Object getVariable(Object key) { 084 return variables.get(key); 085 } 086 087 /** 088 * Get a stateful variable. Return the default value if not found. 089 */ 090 public Object getVariable(Object key, Object defaultValue) { 091 Object result = variables.get(key); 092 if (result == null) { 093 result = defaultValue; 094 } 095 return result; 096 } 097 098 /** 099 * All stateful variables 100 */ 101 public Map getVariables() { 102 return variables; 103 } 104 105}