001//////////////////////////////////////////////////////////////////////////////// 002// checkstyle: Checks Java source code for adherence to a set of rules. 003// Copyright (C) 2001-2020 the original author or authors. 004// 005// This library is free software; you can redistribute it and/or 006// modify it under the terms of the GNU Lesser General Public 007// License as published by the Free Software Foundation; either 008// version 2.1 of the License, or (at your option) any later version. 009// 010// This library is distributed in the hope that it will be useful, 011// but WITHOUT ANY WARRANTY; without even the implied warranty of 012// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 013// Lesser General Public License for more details. 014// 015// You should have received a copy of the GNU Lesser General Public 016// License along with this library; if not, write to the Free Software 017// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 018//////////////////////////////////////////////////////////////////////////////// 019 020package com.puppycrawl.tools.checkstyle; 021 022import java.io.OutputStream; 023import java.io.OutputStreamWriter; 024import java.io.PrintWriter; 025import java.io.StringWriter; 026import java.nio.charset.StandardCharsets; 027import java.util.ArrayList; 028import java.util.Collections; 029import java.util.List; 030import java.util.Map; 031import java.util.concurrent.ConcurrentHashMap; 032 033import com.puppycrawl.tools.checkstyle.api.AuditEvent; 034import com.puppycrawl.tools.checkstyle.api.AuditListener; 035import com.puppycrawl.tools.checkstyle.api.AutomaticBean; 036import com.puppycrawl.tools.checkstyle.api.SeverityLevel; 037import com.puppycrawl.tools.checkstyle.utils.CommonUtil; 038 039/** 040 * Simple XML logger. 041 * It outputs everything in UTF-8 (default XML encoding is UTF-8) in case 042 * we want to localize error messages or simply that file names are 043 * localized and takes care about escaping as well. 044 045 */ 046// -@cs[AbbreviationAsWordInName] We can not change it as, 047// check's name is part of API (used in configurations). 048public class XMLLogger 049 extends AutomaticBean 050 implements AuditListener { 051 052 /** Decimal radix. */ 053 private static final int BASE_10 = 10; 054 055 /** Hex radix. */ 056 private static final int BASE_16 = 16; 057 058 /** Some known entities to detect. */ 059 private static final String[] ENTITIES = {"gt", "amp", "lt", "apos", 060 "quot", }; 061 062 /** Close output stream in auditFinished. */ 063 private final boolean closeStream; 064 065 /** The writer lock object. */ 066 private final Object writerLock = new Object(); 067 068 /** Holds all messages for the given file. */ 069 private final Map<String, FileMessages> fileMessages = 070 new ConcurrentHashMap<>(); 071 072 /** 073 * Helper writer that allows easy encoding and printing. 074 */ 075 private final PrintWriter writer; 076 077 /** 078 * Creates a new {@code XMLLogger} instance. 079 * Sets the output to a defined stream. 080 * @param outputStream the stream to write logs to. 081 * @param outputStreamOptions if {@code CLOSE} stream should be closed in auditFinished() 082 */ 083 public XMLLogger(OutputStream outputStream, OutputStreamOptions outputStreamOptions) { 084 writer = new PrintWriter(new OutputStreamWriter(outputStream, StandardCharsets.UTF_8)); 085 if (outputStreamOptions == null) { 086 throw new IllegalArgumentException("Parameter outputStreamOptions can not be null"); 087 } 088 closeStream = outputStreamOptions == OutputStreamOptions.CLOSE; 089 } 090 091 @Override 092 protected void finishLocalSetup() { 093 // No code by default 094 } 095 096 @Override 097 public void auditStarted(AuditEvent event) { 098 writer.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); 099 100 final String version = XMLLogger.class.getPackage().getImplementationVersion(); 101 102 writer.println("<checkstyle version=\"" + version + "\">"); 103 } 104 105 @Override 106 public void auditFinished(AuditEvent event) { 107 writer.println("</checkstyle>"); 108 if (closeStream) { 109 writer.close(); 110 } 111 else { 112 writer.flush(); 113 } 114 } 115 116 @Override 117 public void fileStarted(AuditEvent event) { 118 fileMessages.put(event.getFileName(), new FileMessages()); 119 } 120 121 @Override 122 public void fileFinished(AuditEvent event) { 123 final String fileName = event.getFileName(); 124 final FileMessages messages = fileMessages.get(fileName); 125 126 synchronized (writerLock) { 127 writeFileMessages(fileName, messages); 128 } 129 130 fileMessages.remove(fileName); 131 } 132 133 /** 134 * Prints the file section with all file errors and exceptions. 135 * @param fileName The file name, as should be printed in the opening file tag. 136 * @param messages The file messages. 137 */ 138 private void writeFileMessages(String fileName, FileMessages messages) { 139 writeFileOpeningTag(fileName); 140 if (messages != null) { 141 for (AuditEvent errorEvent : messages.getErrors()) { 142 writeFileError(errorEvent); 143 } 144 for (Throwable exception : messages.getExceptions()) { 145 writeException(exception); 146 } 147 } 148 writeFileClosingTag(); 149 } 150 151 /** 152 * Prints the "file" opening tag with the given filename. 153 * @param fileName The filename to output. 154 */ 155 private void writeFileOpeningTag(String fileName) { 156 writer.println("<file name=\"" + encode(fileName) + "\">"); 157 } 158 159 /** 160 * Prints the "file" closing tag. 161 */ 162 private void writeFileClosingTag() { 163 writer.println("</file>"); 164 } 165 166 @Override 167 public void addError(AuditEvent event) { 168 if (event.getSeverityLevel() != SeverityLevel.IGNORE) { 169 final String fileName = event.getFileName(); 170 if (fileName == null || !fileMessages.containsKey(fileName)) { 171 synchronized (writerLock) { 172 writeFileError(event); 173 } 174 } 175 else { 176 final FileMessages messages = fileMessages.get(fileName); 177 messages.addError(event); 178 } 179 } 180 } 181 182 /** 183 * Outputs the given event to the writer. 184 * @param event An event to print. 185 */ 186 private void writeFileError(AuditEvent event) { 187 writer.print("<error" + " line=\"" + event.getLine() + "\""); 188 if (event.getColumn() > 0) { 189 writer.print(" column=\"" + event.getColumn() + "\""); 190 } 191 writer.print(" severity=\"" 192 + event.getSeverityLevel().getName() 193 + "\""); 194 writer.print(" message=\"" 195 + encode(event.getMessage()) 196 + "\""); 197 writer.print(" source=\""); 198 if (event.getModuleId() == null) { 199 writer.print(encode(event.getSourceName())); 200 } 201 else { 202 writer.print(encode(event.getModuleId())); 203 } 204 writer.println("\"/>"); 205 } 206 207 @Override 208 public void addException(AuditEvent event, Throwable throwable) { 209 final String fileName = event.getFileName(); 210 if (fileName == null || !fileMessages.containsKey(fileName)) { 211 synchronized (writerLock) { 212 writeException(throwable); 213 } 214 } 215 else { 216 final FileMessages messages = fileMessages.get(fileName); 217 messages.addException(throwable); 218 } 219 } 220 221 /** 222 * Writes the exception event to the print writer. 223 * @param throwable The 224 */ 225 private void writeException(Throwable throwable) { 226 writer.println("<exception>"); 227 writer.println("<![CDATA["); 228 229 final StringWriter stringWriter = new StringWriter(); 230 final PrintWriter printer = new PrintWriter(stringWriter); 231 throwable.printStackTrace(printer); 232 writer.println(encode(stringWriter.toString())); 233 234 writer.println("]]>"); 235 writer.println("</exception>"); 236 } 237 238 /** 239 * Escape <, > & ' and " as their entities. 240 * @param value the value to escape. 241 * @return the escaped value if necessary. 242 */ 243 public static String encode(String value) { 244 final StringBuilder sb = new StringBuilder(256); 245 for (int i = 0; i < value.length(); i++) { 246 final char chr = value.charAt(i); 247 switch (chr) { 248 case '<': 249 sb.append("<"); 250 break; 251 case '>': 252 sb.append(">"); 253 break; 254 case '\'': 255 sb.append("'"); 256 break; 257 case '\"': 258 sb.append("""); 259 break; 260 case '&': 261 sb.append("&"); 262 break; 263 case '\r': 264 break; 265 case '\n': 266 sb.append(" "); 267 break; 268 default: 269 if (Character.isISOControl(chr)) { 270 // true escape characters need '&' before but it also requires XML 1.1 271 // until https://github.com/checkstyle/checkstyle/issues/5168 272 sb.append("#x"); 273 sb.append(Integer.toHexString(chr)); 274 sb.append(';'); 275 } 276 else { 277 sb.append(chr); 278 } 279 break; 280 } 281 } 282 return sb.toString(); 283 } 284 285 /** 286 * Finds whether the given argument is character or entity reference. 287 * @param ent the possible entity to look for. 288 * @return whether the given argument a character or entity reference 289 */ 290 public static boolean isReference(String ent) { 291 boolean reference = false; 292 293 if (ent.charAt(0) == '&' && CommonUtil.endsWithChar(ent, ';')) { 294 if (ent.charAt(1) == '#') { 295 // prefix is "&#" 296 int prefixLength = 2; 297 298 int radix = BASE_10; 299 if (ent.charAt(2) == 'x') { 300 prefixLength++; 301 radix = BASE_16; 302 } 303 try { 304 Integer.parseInt( 305 ent.substring(prefixLength, ent.length() - 1), radix); 306 reference = true; 307 } 308 catch (final NumberFormatException ignored) { 309 reference = false; 310 } 311 } 312 else { 313 final String name = ent.substring(1, ent.length() - 1); 314 for (String element : ENTITIES) { 315 if (name.equals(element)) { 316 reference = true; 317 break; 318 } 319 } 320 } 321 } 322 323 return reference; 324 } 325 326 /** 327 * The registered file messages. 328 */ 329 private static class FileMessages { 330 331 /** The file error events. */ 332 private final List<AuditEvent> errors = Collections.synchronizedList(new ArrayList<>()); 333 334 /** The file exceptions. */ 335 private final List<Throwable> exceptions = Collections.synchronizedList(new ArrayList<>()); 336 337 /** 338 * Returns the file error events. 339 * @return the file error events. 340 */ 341 public List<AuditEvent> getErrors() { 342 return Collections.unmodifiableList(errors); 343 } 344 345 /** 346 * Adds the given error event to the messages. 347 * @param event the error event. 348 */ 349 public void addError(AuditEvent event) { 350 errors.add(event); 351 } 352 353 /** 354 * Returns the file exceptions. 355 * @return the file exceptions. 356 */ 357 public List<Throwable> getExceptions() { 358 return Collections.unmodifiableList(exceptions); 359 } 360 361 /** 362 * Adds the given exception to the messages. 363 * @param throwable the file exception 364 */ 365 public void addException(Throwable throwable) { 366 exceptions.add(throwable); 367 } 368 369 } 370 371}