001/////////////////////////////////////////////////////////////////////////////////////////////// 002// checkstyle: Checks Java source code and other text files for adherence to a set of rules. 003// Copyright (C) 2001-2026 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.IOException; 023import java.util.ArrayDeque; 024import java.util.ArrayList; 025import java.util.Arrays; 026import java.util.Collection; 027import java.util.Deque; 028import java.util.Iterator; 029import java.util.List; 030import java.util.Locale; 031import java.util.Map; 032import java.util.Optional; 033 034import javax.xml.parsers.ParserConfigurationException; 035 036import org.xml.sax.Attributes; 037import org.xml.sax.InputSource; 038import org.xml.sax.SAXException; 039import org.xml.sax.SAXParseException; 040 041import com.puppycrawl.tools.checkstyle.api.CheckstyleException; 042import com.puppycrawl.tools.checkstyle.api.Configuration; 043import com.puppycrawl.tools.checkstyle.api.SeverityLevel; 044import com.puppycrawl.tools.checkstyle.utils.CommonUtil; 045 046/** 047 * Loads a configuration from a standard configuration XML file. 048 * 049 */ 050@SuppressWarnings("UnrecognisedJavadocTag") 051public final class ConfigurationLoader { 052 053 /** 054 * Enum to specify behaviour regarding ignored modules. 055 */ 056 public enum IgnoredModulesOptions { 057 058 /** 059 * Omit ignored modules. 060 */ 061 OMIT, 062 063 /** 064 * Execute ignored modules. 065 */ 066 EXECUTE, 067 068 } 069 070 /** The new public ID for version 1_3 of the configuration dtd. */ 071 public static final String DTD_PUBLIC_CS_ID_1_3 = 072 "-//Checkstyle//DTD Checkstyle Configuration 1.3//EN"; 073 074 /** The resource for version 1_3 of the configuration dtd. */ 075 public static final String DTD_CONFIGURATION_NAME_1_3 = 076 "com/puppycrawl/tools/checkstyle/configuration_1_3.dtd"; 077 078 /** Format of message for sax parse exception. */ 079 private static final String SAX_PARSE_EXCEPTION_FORMAT = "%s - %s:%s:%s"; 080 081 /** The public ID for version 1_0 of the configuration dtd. */ 082 private static final String DTD_PUBLIC_ID_1_0 = 083 "-//Puppy Crawl//DTD Check Configuration 1.0//EN"; 084 085 /** The new public ID for version 1_0 of the configuration dtd. */ 086 private static final String DTD_PUBLIC_CS_ID_1_0 = 087 "-//Checkstyle//DTD Checkstyle Configuration 1.0//EN"; 088 089 /** The resource for version 1_0 of the configuration dtd. */ 090 private static final String DTD_CONFIGURATION_NAME_1_0 = 091 "com/puppycrawl/tools/checkstyle/configuration_1_0.dtd"; 092 093 /** The public ID for version 1_1 of the configuration dtd. */ 094 private static final String DTD_PUBLIC_ID_1_1 = 095 "-//Puppy Crawl//DTD Check Configuration 1.1//EN"; 096 097 /** The new public ID for version 1_1 of the configuration dtd. */ 098 private static final String DTD_PUBLIC_CS_ID_1_1 = 099 "-//Checkstyle//DTD Checkstyle Configuration 1.1//EN"; 100 101 /** The resource for version 1_1 of the configuration dtd. */ 102 private static final String DTD_CONFIGURATION_NAME_1_1 = 103 "com/puppycrawl/tools/checkstyle/configuration_1_1.dtd"; 104 105 /** The public ID for version 1_2 of the configuration dtd. */ 106 private static final String DTD_PUBLIC_ID_1_2 = 107 "-//Puppy Crawl//DTD Check Configuration 1.2//EN"; 108 109 /** The new public ID for version 1_2 of the configuration dtd. */ 110 private static final String DTD_PUBLIC_CS_ID_1_2 = 111 "-//Checkstyle//DTD Checkstyle Configuration 1.2//EN"; 112 113 /** The resource for version 1_2 of the configuration dtd. */ 114 private static final String DTD_CONFIGURATION_NAME_1_2 = 115 "com/puppycrawl/tools/checkstyle/configuration_1_2.dtd"; 116 117 /** The public ID for version 1_3 of the configuration dtd. */ 118 private static final String DTD_PUBLIC_ID_1_3 = 119 "-//Puppy Crawl//DTD Check Configuration 1.3//EN"; 120 121 /** Prefix for the exception when unable to parse resource. */ 122 private static final String UNABLE_TO_PARSE_EXCEPTION_PREFIX = "unable to parse" 123 + " configuration stream"; 124 125 /** Dollar sign literal. */ 126 private static final char DOLLAR_SIGN = '$'; 127 /** Dollar sign string. */ 128 private static final String DOLLAR_SIGN_STRING = String.valueOf(DOLLAR_SIGN); 129 130 /** Static map of DTD IDs to resource names. */ 131 private static final Map<String, String> ID_TO_RESOURCE_NAME_MAP = Map.ofEntries( 132 Map.entry(DTD_PUBLIC_ID_1_0, DTD_CONFIGURATION_NAME_1_0), 133 Map.entry(DTD_PUBLIC_ID_1_1, DTD_CONFIGURATION_NAME_1_1), 134 Map.entry(DTD_PUBLIC_ID_1_2, DTD_CONFIGURATION_NAME_1_2), 135 Map.entry(DTD_PUBLIC_ID_1_3, DTD_CONFIGURATION_NAME_1_3), 136 Map.entry(DTD_PUBLIC_CS_ID_1_0, DTD_CONFIGURATION_NAME_1_0), 137 Map.entry(DTD_PUBLIC_CS_ID_1_1, DTD_CONFIGURATION_NAME_1_1), 138 Map.entry(DTD_PUBLIC_CS_ID_1_2, DTD_CONFIGURATION_NAME_1_2), 139 Map.entry(DTD_PUBLIC_CS_ID_1_3, DTD_CONFIGURATION_NAME_1_3) 140 ); 141 142 /** The SAX document handler. */ 143 private final InternalLoader saxHandler; 144 145 /** Property resolver. */ 146 private final PropertyResolver overridePropsResolver; 147 148 /** Flags if modules with the severity 'ignore' should be omitted. */ 149 private final boolean omitIgnoredModules; 150 151 /** The thread mode configuration. */ 152 private final ThreadModeSettings threadModeSettings; 153 154 /** 155 * Creates a new {@code ConfigurationLoader} instance. 156 * 157 * @param overrideProps resolver for overriding properties 158 * @param omitIgnoredModules {@code true} if ignored modules should be omitted 159 * @param threadModeSettings the thread mode configuration 160 * @throws ParserConfigurationException if an error occurs 161 * @throws SAXException if an error occurs 162 */ 163 private ConfigurationLoader(final PropertyResolver overrideProps, 164 final boolean omitIgnoredModules, 165 final ThreadModeSettings threadModeSettings) 166 throws ParserConfigurationException, SAXException { 167 saxHandler = new InternalLoader(); 168 overridePropsResolver = overrideProps; 169 this.omitIgnoredModules = omitIgnoredModules; 170 this.threadModeSettings = threadModeSettings; 171 } 172 173 /** 174 * Parses the specified input source loading the configuration information. 175 * The stream wrapped inside the source, if any, is NOT 176 * explicitly closed after parsing, it is the responsibility of the caller to close the stream. 177 * 178 * @param source the source that contains the configuration data 179 * @return the check configurations 180 * @throws IOException if an error occurs 181 * @throws SAXException if an error occurs 182 */ 183 private Configuration parseInputSource(InputSource source) 184 throws IOException, SAXException { 185 saxHandler.parseInputSource(source); 186 return saxHandler.configuration; 187 } 188 189 /** 190 * Returns the module configurations in a specified file. 191 * 192 * @param config location of config file, can be either a URL or a filename 193 * @param overridePropsResolver overriding properties 194 * @return the check configurations 195 * @throws CheckstyleException if an error occurs 196 */ 197 public static Configuration loadConfiguration(String config, 198 PropertyResolver overridePropsResolver) 199 throws CheckstyleException { 200 return loadConfiguration(config, overridePropsResolver, IgnoredModulesOptions.EXECUTE); 201 } 202 203 /** 204 * Returns the module configurations in a specified file. 205 * 206 * @param config location of config file, can be either a URL or a filename 207 * @param overridePropsResolver overriding properties 208 * @param threadModeSettings the thread mode configuration 209 * @return the check configurations 210 * @throws CheckstyleException if an error occurs 211 */ 212 public static Configuration loadConfiguration(String config, 213 PropertyResolver overridePropsResolver, ThreadModeSettings threadModeSettings) 214 throws CheckstyleException { 215 return loadConfiguration(config, overridePropsResolver, 216 IgnoredModulesOptions.EXECUTE, threadModeSettings); 217 } 218 219 /** 220 * Returns the module configurations in a specified file. 221 * 222 * @param config location of config file, can be either a URL or a filename 223 * @param overridePropsResolver overriding properties 224 * @param ignoredModulesOptions {@code OMIT} if modules with severity 225 * 'ignore' should be omitted, {@code EXECUTE} otherwise 226 * @return the check configurations 227 * @throws CheckstyleException if an error occurs 228 */ 229 public static Configuration loadConfiguration(String config, 230 PropertyResolver overridePropsResolver, 231 IgnoredModulesOptions ignoredModulesOptions) 232 throws CheckstyleException { 233 return loadConfiguration(config, overridePropsResolver, ignoredModulesOptions, 234 ThreadModeSettings.SINGLE_THREAD_MODE_INSTANCE); 235 } 236 237 /** 238 * Returns the module configurations from a specified input source. 239 * Note that if the source does wrap an open byte or character 240 * stream, clients are required to close that stream by themselves 241 * 242 * @param configSource the input stream to the Checkstyle configuration 243 * @param overridePropsResolver overriding properties 244 * @param ignoredModulesOptions {@code OMIT} if modules with severity 245 * 'ignore' should be omitted, {@code EXECUTE} otherwise 246 * @return the check configurations 247 * @throws CheckstyleException if an error occurs 248 */ 249 public static Configuration loadConfiguration(InputSource configSource, 250 PropertyResolver overridePropsResolver, 251 IgnoredModulesOptions ignoredModulesOptions) 252 throws CheckstyleException { 253 return loadConfiguration(configSource, overridePropsResolver, 254 ignoredModulesOptions, ThreadModeSettings.SINGLE_THREAD_MODE_INSTANCE); 255 } 256 257 /** 258 * Returns the module configurations in a specified file. 259 * 260 * @param config location of config file, can be either a URL or a filename 261 * @param overridePropsResolver overriding properties 262 * @param ignoredModulesOptions {@code OMIT} if modules with severity 263 * 'ignore' should be omitted, {@code EXECUTE} otherwise 264 * @param threadModeSettings the thread mode configuration 265 * @return the check configurations 266 * @throws CheckstyleException if an error occurs 267 */ 268 public static Configuration loadConfiguration(String config, 269 PropertyResolver overridePropsResolver, 270 IgnoredModulesOptions ignoredModulesOptions, 271 ThreadModeSettings threadModeSettings) 272 throws CheckstyleException { 273 return loadConfiguration(CommonUtil.sourceFromFilename(config), overridePropsResolver, 274 ignoredModulesOptions, threadModeSettings); 275 } 276 277 /** 278 * Returns the module configurations from a specified input source. 279 * Note that if the source does wrap an open byte or character 280 * stream, clients are required to close that stream by themselves 281 * 282 * @param configSource the input stream to the Checkstyle configuration 283 * @param overridePropsResolver overriding properties 284 * @param ignoredModulesOptions {@code OMIT} if modules with severity 285 * 'ignore' should be omitted, {@code EXECUTE} otherwise 286 * @param threadModeSettings the thread mode configuration 287 * @return the check configurations 288 * @throws CheckstyleException if an error occurs 289 * @noinspection WeakerAccess 290 * @noinspectionreason WeakerAccess - we avoid 'protected' when possible 291 */ 292 public static Configuration loadConfiguration(InputSource configSource, 293 PropertyResolver overridePropsResolver, 294 IgnoredModulesOptions ignoredModulesOptions, 295 ThreadModeSettings threadModeSettings) 296 throws CheckstyleException { 297 try { 298 final boolean omitIgnoreModules = ignoredModulesOptions == IgnoredModulesOptions.OMIT; 299 final ConfigurationLoader loader = 300 new ConfigurationLoader(overridePropsResolver, 301 omitIgnoreModules, threadModeSettings); 302 return loader.parseInputSource(configSource); 303 } 304 catch (final SAXParseException exc) { 305 final String message = String.format(Locale.ROOT, SAX_PARSE_EXCEPTION_FORMAT, 306 UNABLE_TO_PARSE_EXCEPTION_PREFIX, 307 exc.getMessage(), exc.getLineNumber(), exc.getColumnNumber()); 308 throw new CheckstyleException(message, exc); 309 } 310 catch (final ParserConfigurationException | IOException | SAXException exc) { 311 throw new CheckstyleException(UNABLE_TO_PARSE_EXCEPTION_PREFIX, exc); 312 } 313 } 314 315 /** 316 * Implements the SAX document handler interfaces, so they do not 317 * appear in the public API of the ConfigurationLoader. 318 */ 319 private final class InternalLoader extends XmlLoader { 320 321 /** Module elements. */ 322 private static final String MODULE = "module"; 323 /** Name attribute. */ 324 private static final String NAME = "name"; 325 /** Property element. */ 326 private static final String PROPERTY = "property"; 327 /** Value attribute. */ 328 private static final String VALUE = "value"; 329 /** Default attribute. */ 330 private static final String DEFAULT = "default"; 331 /** Name of the severity property. */ 332 private static final String SEVERITY = "severity"; 333 /** Name of the message element. */ 334 private static final String MESSAGE = "message"; 335 /** Name of the message element. */ 336 private static final String METADATA = "metadata"; 337 /** Name of the key attribute. */ 338 private static final String KEY = "key"; 339 340 /** The loaded configurations. */ 341 private final Deque<DefaultConfiguration> configStack = new ArrayDeque<>(); 342 343 /** The Configuration that is being built. */ 344 private Configuration configuration; 345 346 /** 347 * Creates a new InternalLoader. 348 * 349 * @throws ParserConfigurationException if an error occurs 350 * @throws SAXException if an error occurs 351 */ 352 private InternalLoader() 353 throws SAXException, ParserConfigurationException { 354 super(ID_TO_RESOURCE_NAME_MAP); 355 } 356 357 /** 358 * Replaces {@code ${xxx}} style constructions in the given value 359 * with the string value of the corresponding data types. 360 * 361 * <p>Code copied from 362 * <a href="https://github.com/apache/ant/blob/master/src/main/org/apache/tools/ant/ProjectHelper.java"> 363 * ant 364 * </a> 365 * 366 * @param value The string to be scanned for property references. Must not be {@code null}. 367 * @param defaultValue default to use if one of the properties in value 368 * cannot be resolved from props. 369 * 370 * @return the original string with the properties replaced. 371 * @throws CheckstyleException if the string contains an opening 372 * {@code ${} without a closing 373 * {@code }} 374 */ 375 private String replaceProperties( 376 String value, String defaultValue) 377 throws CheckstyleException { 378 379 final List<String> fragments = new ArrayList<>(); 380 final List<String> propertyRefs = new ArrayList<>(); 381 parsePropertyString(value, fragments, propertyRefs); 382 383 final StringBuilder sb = new StringBuilder(256); 384 final Iterator<String> fragmentsIterator = fragments.iterator(); 385 final Iterator<String> propertyRefsIterator = propertyRefs.iterator(); 386 while (fragmentsIterator.hasNext()) { 387 String fragment = fragmentsIterator.next(); 388 if (fragment == null) { 389 final String propertyName = propertyRefsIterator.next(); 390 fragment = overridePropsResolver.resolve(propertyName); 391 if (fragment == null) { 392 if (defaultValue != null) { 393 sb.replace(0, sb.length(), defaultValue); 394 break; 395 } 396 throw new CheckstyleException( 397 "Property ${" + propertyName + "} has not been set"); 398 } 399 } 400 sb.append(fragment); 401 } 402 403 return sb.toString(); 404 } 405 406 /** 407 * Parses a string containing {@code ${xxx}} style property 408 * references into two collections. The first one is a collection 409 * of text fragments, while the other is a set of string property names. 410 * {@code null} entries in the first collection indicate a property 411 * reference from the second collection. 412 * 413 * <p>Code copied from 414 * <a href="https://github.com/apache/ant/blob/master/src/main/org/apache/tools/ant/ProjectHelper.java"> 415 * ant 416 * </a> 417 * 418 * @param value Text to parse. Must not be {@code null}. 419 * @param fragments Collection to add text fragments to. 420 * Must not be {@code null}. 421 * @param propertyRefs Collection to add property names to. 422 * Must not be {@code null}. 423 * 424 * @throws CheckstyleException if the string contains an opening 425 * {@code ${} without a closing 426 * {@code }} 427 */ 428 private static void parsePropertyString(String value, 429 Collection<String> fragments, 430 Collection<String> propertyRefs) 431 throws CheckstyleException { 432 int prev = 0; 433 // search for the next instance of $ from the 'prev' position 434 int pos = value.indexOf(DOLLAR_SIGN, prev); 435 while (pos >= 0) { 436 // if there was any text before this, add it as a fragment 437 if (pos > 0) { 438 fragments.add(value.substring(prev, pos)); 439 } 440 // if we are at the end of the string, we tack on a $ 441 // then move past it 442 if (pos == value.length() - 1) { 443 fragments.add(DOLLAR_SIGN_STRING); 444 prev = pos + 1; 445 } 446 else if (value.charAt(pos + 1) == '{') { 447 // property found, extract its name or bail on a typo 448 final int endName = value.indexOf('}', pos); 449 if (endName == -1) { 450 throw new CheckstyleException("Syntax error in property: " 451 + value); 452 } 453 final String propertyName = value.substring(pos + 2, endName); 454 fragments.add(null); 455 propertyRefs.add(propertyName); 456 prev = endName + 1; 457 } 458 else { 459 if (value.charAt(pos + 1) == DOLLAR_SIGN) { 460 // backwards compatibility two $ map to one mode 461 fragments.add(DOLLAR_SIGN_STRING); 462 } 463 else { 464 // new behaviour: $X maps to $X for all values of X!='$' 465 fragments.add(value.substring(pos, pos + 2)); 466 } 467 prev = pos + 2; 468 } 469 470 // search for the next instance of $ from the 'prev' position 471 pos = value.indexOf(DOLLAR_SIGN, prev); 472 } 473 // no more $ signs found 474 // if there is any tail to the file, append it 475 if (prev < value.length()) { 476 fragments.add(value.substring(prev)); 477 } 478 } 479 480 @Override 481 public void startElement(String uri, 482 String localName, 483 String qName, 484 Attributes attributes) 485 throws SAXException { 486 if (MODULE.equals(qName)) { 487 // create configuration 488 final String originalName = attributes.getValue(NAME); 489 final String name = threadModeSettings.resolveName(originalName); 490 final DefaultConfiguration conf = 491 new DefaultConfiguration(name, threadModeSettings); 492 493 if (configStack.isEmpty()) { 494 // save top config 495 configuration = conf; 496 } 497 else { 498 // add configuration to it's parent 499 final DefaultConfiguration top = 500 configStack.peek(); 501 top.addChild(conf); 502 } 503 504 configStack.push(conf); 505 } 506 else if (PROPERTY.equals(qName)) { 507 // extract value and name 508 final String attributesValue = attributes.getValue(VALUE); 509 510 final String value; 511 try { 512 value = replaceProperties(attributesValue, attributes.getValue(DEFAULT)); 513 } 514 catch (final CheckstyleException exc) { 515 // -@cs[IllegalInstantiation] SAXException is in the overridden 516 // method signature 517 throw new SAXException(attributesValue, exc); 518 } 519 520 final String name = attributes.getValue(NAME); 521 522 // add to attributes of configuration 523 final DefaultConfiguration top = 524 configStack.peek(); 525 top.addProperty(name, value); 526 } 527 else if (MESSAGE.equals(qName)) { 528 // extract key and value 529 final String key = attributes.getValue(KEY); 530 final String value = attributes.getValue(VALUE); 531 532 // add to messages of configuration 533 final DefaultConfiguration top = configStack.peek(); 534 top.addMessage(key, value); 535 } 536 else { 537 if (!METADATA.equals(qName)) { 538 throw new IllegalStateException("Unknown name:" + qName + "."); 539 } 540 } 541 } 542 543 @Override 544 public void endElement(String uri, 545 String localName, 546 String qName) 547 throws SAXException { 548 if (MODULE.equals(qName)) { 549 final Configuration recentModule = 550 configStack.pop(); 551 552 // get severity attribute if it exists 553 Optional<SeverityLevel> level = Optional.empty(); 554 if (containsAttribute(recentModule, SEVERITY)) { 555 try { 556 final String severity = recentModule.getProperty(SEVERITY); 557 level = Optional.of(SeverityLevel.getInstance(severity)); 558 } 559 catch (final CheckstyleException exc) { 560 // -@cs[IllegalInstantiation] SAXException is in the overridden 561 // method signature 562 throw new SAXException( 563 "Problem during accessing '" + SEVERITY + "' attribute for " 564 + recentModule.getName(), exc); 565 } 566 } 567 568 // omit this module if these should be omitted and the module 569 // has the severity 'ignore' 570 final boolean omitModule = omitIgnoredModules 571 && level.isPresent() && level.get() == SeverityLevel.IGNORE; 572 573 if (omitModule && !configStack.isEmpty()) { 574 final DefaultConfiguration parentModule = configStack.peek(); 575 parentModule.removeChild(recentModule); 576 } 577 } 578 } 579 580 /** 581 * Util method to recheck attribute in module. 582 * 583 * @param module module to check 584 * @param attributeName name of attribute in module to find 585 * @return true if attribute is present in module 586 */ 587 private static boolean containsAttribute(Configuration module, String attributeName) { 588 final String[] names = module.getPropertyNames(); 589 final Optional<String> result = Arrays.stream(names) 590 .filter(name -> name.equals(attributeName)).findFirst(); 591 return result.isPresent(); 592 } 593 594 } 595 596}