001 /* 002 * Sonar, open source software quality management tool. 003 * Copyright (C) 2008-2011 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.server.ui; 021 022 import org.apache.commons.lang.StringUtils; 023 import org.sonar.api.ServerExtension; 024 import org.sonar.api.utils.Logs; 025 import org.sonar.api.web.CodeColorizerFormat; 026 import org.sonar.colorizer.CodeColorizer; 027 import org.sonar.colorizer.HtmlOptions; 028 import org.sonar.colorizer.Tokenizer; 029 030 import java.io.StringReader; 031 import java.util.Collections; 032 import java.util.HashMap; 033 import java.util.List; 034 import java.util.Map; 035 036 public class CodeColorizers implements ServerExtension { 037 038 private Map<String, CodeColorizerFormat> formatPerLanguage; 039 040 public CodeColorizers(List<CodeColorizerFormat> formats) { 041 formatPerLanguage = new HashMap<String, CodeColorizerFormat>(); 042 for (CodeColorizerFormat format : formats) { 043 formatPerLanguage.put(format.getLanguageKey(), format); 044 } 045 046 Logs.INFO.info("Code colorizer, supported languages: " + StringUtils.join(formatPerLanguage.keySet(), ",")); 047 } 048 049 public String toHtml(String code, String language) { 050 List<Tokenizer> tokenizers; 051 CodeColorizerFormat format = formatPerLanguage.get(language); 052 if (format == null) { 053 tokenizers = Collections.emptyList(); 054 } else { 055 tokenizers = format.getTokenizers(); 056 } 057 return new CodeColorizer(tokenizers).toHtml(new StringReader(code), HtmlOptions.ONLY_SYNTAX); 058 } 059 }