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