001////////////////////////////////////////////////////////////////////////////////
002// checkstyle: Checks Java source code for adherence to a set of rules.
003// Copyright (C) 2001-2018 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.filters;
021
022import java.io.FileNotFoundException;
023import java.io.IOException;
024import java.net.URI;
025import java.util.HashMap;
026import java.util.HashSet;
027import java.util.Locale;
028import java.util.Map;
029import java.util.Set;
030import java.util.regex.PatternSyntaxException;
031
032import javax.xml.parsers.ParserConfigurationException;
033
034import org.xml.sax.Attributes;
035import org.xml.sax.InputSource;
036import org.xml.sax.SAXException;
037
038import com.puppycrawl.tools.checkstyle.TreeWalkerFilter;
039import com.puppycrawl.tools.checkstyle.XmlLoader;
040import com.puppycrawl.tools.checkstyle.api.CheckstyleException;
041import com.puppycrawl.tools.checkstyle.api.FilterSet;
042import com.puppycrawl.tools.checkstyle.utils.CommonUtil;
043
044/**
045 * Loads a filter chain of suppressions.
046 */
047public final class SuppressionsLoader
048    extends XmlLoader {
049
050    /** The public ID for the configuration dtd. */
051    private static final String DTD_PUBLIC_ID_1_0 =
052        "-//Puppy Crawl//DTD Suppressions 1.0//EN";
053    /** The new public ID for version 1_0 configuration dtd. */
054    private static final String DTD_PUBLIC_CS_ID_1_0 =
055        "-//Checkstyle//DTD SuppressionFilter Configuration 1.0//EN";
056    /** The resource for the configuration dtd. */
057    private static final String DTD_SUPPRESSIONS_NAME_1_0 =
058        "com/puppycrawl/tools/checkstyle/suppressions_1_0.dtd";
059    /** The public ID for the configuration dtd. */
060    private static final String DTD_PUBLIC_ID_1_1 =
061        "-//Puppy Crawl//DTD Suppressions 1.1//EN";
062    /** The new public ID for version 1_1 configuration dtd. */
063    private static final String DTD_PUBLIC_CS_ID_1_1 =
064        "-//Checkstyle//DTD SuppressionFilter Configuration 1.1//EN";
065    /** The resource for the configuration dtd. */
066    private static final String DTD_SUPPRESSIONS_NAME_1_1 =
067        "com/puppycrawl/tools/checkstyle/suppressions_1_1.dtd";
068    /** The public ID for the configuration dtd. */
069    private static final String DTD_PUBLIC_ID_1_2 =
070        "-//Puppy Crawl//DTD Suppressions 1.2//EN";
071    /** The new public ID for version 1_2 configuration dtd. */
072    private static final String DTD_PUBLIC_CS_ID_1_2 =
073        "-//Checkstyle//DTD SuppressionFilter Configuration 1.2//EN";
074    /** The resource for the configuration dtd. */
075    private static final String DTD_SUPPRESSIONS_NAME_1_2 =
076        "com/puppycrawl/tools/checkstyle/suppressions_1_2.dtd";
077    /** The public ID for the configuration dtd. */
078    private static final String DTD_PUBLIC_ID_1_1_XPATH =
079        "-//Puppy Crawl//DTD Suppressions Xpath Experimental 1.1//EN";
080    /** The new public ID for version 1_1 configuration dtd. */
081    private static final String DTD_PUBLIC_CS_ID_1_1_XPATH =
082        "-//Checkstyle//DTD SuppressionXpathFilter Experimental Configuration 1.1//EN";
083    /** The resource for the configuration dtd. */
084    private static final String DTD_SUPPRESSIONS_NAME_1_1_XPATH =
085        "com/puppycrawl/tools/checkstyle/suppressions_1_1_xpath_experimental.dtd";
086    /** The public ID for the configuration dtd. */
087    private static final String DTD_PUBLIC_ID_1_2_XPATH =
088        "-//Puppy Crawl//DTD Suppressions Xpath Experimental 1.2//EN";
089    /** The new public ID for version 1_2 configuration dtd. */
090    private static final String DTD_PUBLIC_CS_ID_1_2_XPATH =
091        "-//Checkstyle//DTD SuppressionXpathFilter Experimental Configuration 1.2//EN";
092    /** The resource for the configuration dtd. */
093    private static final String DTD_SUPPRESSIONS_NAME_1_2_XPATH =
094        "com/puppycrawl/tools/checkstyle/suppressions_1_2_xpath_experimental.dtd";
095    /** File search error message. **/
096    private static final String UNABLE_TO_FIND_ERROR_MESSAGE = "Unable to find: ";
097    /** String literal for attribute name. **/
098    private static final String ATTRIBUTE_NAME_FILES = "files";
099    /** String literal for attribute name. **/
100    private static final String ATTRIBUTE_NAME_CHECKS = "checks";
101    /** String literal for attribute name. **/
102    private static final String ATTRIBUTE_NAME_MESSAGE = "message";
103    /** String literal for attribute name. **/
104    private static final String ATTRIBUTE_NAME_ID = "id";
105    /** String literal for attribute name. **/
106    private static final String ATTRIBUTE_NAME_QUERY = "query";
107    /** String literal for attribute name. **/
108    private static final String ATTRIBUTE_NAME_LINES = "lines";
109    /** String literal for attribute name. **/
110    private static final String ATTRIBUTE_NAME_COLUMNS = "columns";
111
112    /**
113     * The filter chain to return in getAFilterChain(),
114     * configured during parsing.
115     */
116    private final FilterSet filterChain = new FilterSet();
117
118    /**
119     * The set of the {@code TreeWalkerFilter} filters. Being filled during parsing.
120     */
121    private final Set<TreeWalkerFilter> treeWalkerFilters = new HashSet<>();
122
123    /**
124     * Creates a new {@code SuppressionsLoader} instance.
125     * @throws ParserConfigurationException if an error occurs
126     * @throws SAXException if an error occurs
127     */
128    private SuppressionsLoader()
129            throws ParserConfigurationException, SAXException {
130        super(createIdToResourceNameMap());
131    }
132
133    @Override
134    public void startElement(String namespaceUri,
135                             String localName,
136                             String qName,
137                             Attributes attributes)
138            throws SAXException {
139        if ("suppress".equals(qName)) {
140            //add SuppressElement filter to the filter chain
141            final SuppressElement suppress = getSuppressElement(attributes);
142            filterChain.addFilter(suppress);
143        }
144        else if ("suppress-xpath".equals(qName)) {
145            final XpathFilter filter = getXpathFilter(attributes);
146            treeWalkerFilters.add(filter);
147        }
148    }
149
150    /**
151     * Returns the suppress element, initialized from given attributes.
152     * @param attributes the attributes of xml-tag "<suppress></suppress>", specified inside
153     *                   suppression file.
154     * @return the suppress element
155     * @throws SAXException if an error occurs.
156     */
157    private static SuppressElement getSuppressElement(Attributes attributes) throws SAXException {
158        final String checks = attributes.getValue(ATTRIBUTE_NAME_CHECKS);
159        final String modId = attributes.getValue(ATTRIBUTE_NAME_ID);
160        final String message = attributes.getValue(ATTRIBUTE_NAME_MESSAGE);
161        if (checks == null && modId == null && message == null) {
162            // -@cs[IllegalInstantiation] SAXException is in the overridden method signature
163            throw new SAXException("missing checks or id or message attribute");
164        }
165        final SuppressElement suppress;
166        try {
167            final String files = attributes.getValue(ATTRIBUTE_NAME_FILES);
168            final String lines = attributes.getValue(ATTRIBUTE_NAME_LINES);
169            final String columns = attributes.getValue(ATTRIBUTE_NAME_COLUMNS);
170            suppress = new SuppressElement(files, checks, message, modId, lines, columns);
171        }
172        catch (final PatternSyntaxException ex) {
173            // -@cs[IllegalInstantiation] SAXException is in the overridden method signature
174            throw new SAXException("invalid files or checks or message format", ex);
175        }
176        return suppress;
177    }
178
179    /**
180     * Returns the xpath filter, initialized from given attributes.
181     * @param attributes the attributes of xml-tag "<suppress-xpath></suppress-xpath>",
182     *                   specified inside suppression file.
183     * @return the xpath filter
184     * @throws SAXException if an error occurs.
185     */
186    private static XpathFilter getXpathFilter(Attributes attributes) throws SAXException {
187        final String checks = attributes.getValue(ATTRIBUTE_NAME_CHECKS);
188        final String modId = attributes.getValue(ATTRIBUTE_NAME_ID);
189        final String message = attributes.getValue(ATTRIBUTE_NAME_MESSAGE);
190        if (checks == null && modId == null && message == null) {
191            // -@cs[IllegalInstantiation] SAXException is in the overridden method signature
192            throw new SAXException("missing checks or id or message attribute for suppress-xpath");
193        }
194        final XpathFilter filter;
195        try {
196            final String files = attributes.getValue(ATTRIBUTE_NAME_FILES);
197            final String xpathQuery = attributes.getValue(ATTRIBUTE_NAME_QUERY);
198            filter = new XpathFilter(files, checks, message, modId, xpathQuery);
199        }
200        catch (final PatternSyntaxException ex) {
201            // -@cs[IllegalInstantiation] SAXException is in the overridden method signature
202            throw new SAXException("invalid files or checks or message format for suppress-xpath",
203                    ex);
204        }
205        return filter;
206    }
207
208    /**
209     * Returns the suppression filters in a specified file.
210     * @param filename name of the suppressions file.
211     * @return the filter chain of suppression elements specified in the file.
212     * @throws CheckstyleException if an error occurs.
213     */
214    public static FilterSet loadSuppressions(String filename)
215            throws CheckstyleException {
216        // figure out if this is a File or a URL
217        final URI uri = CommonUtil.getUriByFilename(filename);
218        final InputSource source = new InputSource(uri.toString());
219        return loadSuppressions(source, filename);
220    }
221
222    /**
223     * Returns the suppression filters in a specified source.
224     * @param source the source for the suppressions.
225     * @param sourceName the name of the source.
226     * @return the filter chain of suppression elements in source.
227     * @throws CheckstyleException if an error occurs.
228     */
229    private static FilterSet loadSuppressions(
230            InputSource source, String sourceName)
231            throws CheckstyleException {
232        return getSuppressionLoader(source, sourceName).filterChain;
233    }
234
235    /**
236     * Returns the suppression {@code TreeWalker} filters in a specified file.
237     * @param filename name of the suppressions file.
238     * @return the set of xpath suppression elements specified in the file.
239     * @throws CheckstyleException if an error occurs.
240     */
241    public static Set<TreeWalkerFilter> loadXpathSuppressions(String filename)
242            throws CheckstyleException {
243        // figure out if this is a File or a URL
244        final URI uri = CommonUtil.getUriByFilename(filename);
245        final InputSource source = new InputSource(uri.toString());
246        return loadXpathSuppressions(source, filename);
247    }
248
249    /**
250     * Returns the suppression {@code TreeWalker} filters in a specified source.
251     * @param source the source for the suppressions.
252     * @param sourceName the name of the source.
253     * @return the set of xpath suppression elements specified in source.
254     * @throws CheckstyleException if an error occurs.
255     */
256    private static Set<TreeWalkerFilter> loadXpathSuppressions(
257            InputSource source, String sourceName)
258            throws CheckstyleException {
259        return getSuppressionLoader(source, sourceName).treeWalkerFilters;
260    }
261
262    /**
263     * Parses specified source and returns the suppression loader.
264     * @param source the source for the suppressions.
265     * @param sourceName the name of the source.
266     * @return the suppression loader
267     * @throws CheckstyleException if an error occurs.
268     */
269    private static SuppressionsLoader getSuppressionLoader(InputSource source, String sourceName)
270            throws CheckstyleException {
271        try {
272            final SuppressionsLoader suppressionsLoader =
273                new SuppressionsLoader();
274            suppressionsLoader.parseInputSource(source);
275            return suppressionsLoader;
276        }
277        catch (final FileNotFoundException ex) {
278            throw new CheckstyleException(UNABLE_TO_FIND_ERROR_MESSAGE + sourceName, ex);
279        }
280        catch (final ParserConfigurationException | SAXException ex) {
281            final String message = String.format(Locale.ROOT, "Unable to parse %s - %s",
282                    sourceName, ex.getMessage());
283            throw new CheckstyleException(message, ex);
284        }
285        catch (final IOException ex) {
286            throw new CheckstyleException("Unable to read " + sourceName, ex);
287        }
288        catch (final NumberFormatException ex) {
289            final String message = String.format(Locale.ROOT, "Number format exception %s - %s",
290                    sourceName, ex.getMessage());
291            throw new CheckstyleException(message, ex);
292        }
293    }
294
295    /**
296     * Creates mapping between local resources and dtd ids.
297     * @return map between local resources and dtd ids.
298     */
299    private static Map<String, String> createIdToResourceNameMap() {
300        final Map<String, String> map = new HashMap<>();
301        map.put(DTD_PUBLIC_ID_1_0, DTD_SUPPRESSIONS_NAME_1_0);
302        map.put(DTD_PUBLIC_ID_1_1, DTD_SUPPRESSIONS_NAME_1_1);
303        map.put(DTD_PUBLIC_ID_1_2, DTD_SUPPRESSIONS_NAME_1_2);
304        map.put(DTD_PUBLIC_ID_1_1_XPATH, DTD_SUPPRESSIONS_NAME_1_1_XPATH);
305        map.put(DTD_PUBLIC_ID_1_2_XPATH, DTD_SUPPRESSIONS_NAME_1_2_XPATH);
306        map.put(DTD_PUBLIC_CS_ID_1_0, DTD_SUPPRESSIONS_NAME_1_0);
307        map.put(DTD_PUBLIC_CS_ID_1_1, DTD_SUPPRESSIONS_NAME_1_1);
308        map.put(DTD_PUBLIC_CS_ID_1_2, DTD_SUPPRESSIONS_NAME_1_2);
309        map.put(DTD_PUBLIC_CS_ID_1_1_XPATH, DTD_SUPPRESSIONS_NAME_1_1_XPATH);
310        map.put(DTD_PUBLIC_CS_ID_1_2_XPATH, DTD_SUPPRESSIONS_NAME_1_2_XPATH);
311        return map;
312    }
313
314}