001////////////////////////////////////////////////////////////////////////////////
002// checkstyle: Checks Java source code for adherence to a set of rules.
003// Copyright (C) 2001-2017 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.api;
021
022import java.io.IOException;
023import java.io.InputStream;
024import java.util.HashMap;
025import java.util.Map;
026
027import javax.xml.parsers.ParserConfigurationException;
028import javax.xml.parsers.SAXParserFactory;
029
030import org.xml.sax.InputSource;
031import org.xml.sax.SAXException;
032import org.xml.sax.SAXParseException;
033import org.xml.sax.XMLReader;
034import org.xml.sax.helpers.DefaultHandler;
035
036/**
037 * Contains the common implementation of a loader, for loading a configuration
038 * from an XML file.
039 * <p>
040 * The error handling policy can be described as being austere, dead set,
041 * disciplinary, dour, draconian, exacting, firm, forbidding, grim, hard, hard-
042 * boiled, harsh, harsh, in line, iron-fisted, no-nonsense, oppressive,
043 * persnickety, picky, prudish, punctilious, puritanical, rigid, rigorous,
044 * scrupulous, set, severe, square, stern, stickler, straight, strait-laced,
045 * stringent, stuffy, stuffy, tough, unpermissive, unsparing and uptight.
046 * </p>
047 *
048 * @author Oliver Burn
049 * @noinspection ThisEscapedInObjectConstruction
050 */
051public abstract class AbstractLoader
052    extends DefaultHandler {
053    /** Maps public id to resolve to resource name for the DTD. */
054    private final Map<String, String> publicIdToResourceNameMap;
055    /** Parser to read XML files. **/
056    private final XMLReader parser;
057
058    /**
059     * Creates a new instance.
060     * @param publicId the public ID for the DTD to resolve
061     * @param dtdResourceName the resource for the DTD
062     * @throws SAXException if an error occurs
063     * @throws ParserConfigurationException if an error occurs
064     */
065    protected AbstractLoader(String publicId, String dtdResourceName)
066            throws SAXException, ParserConfigurationException {
067        this(new HashMap<>(1));
068        publicIdToResourceNameMap.put(publicId, dtdResourceName);
069    }
070
071    /**
072     * Creates a new instance.
073     * @param publicIdToResourceNameMap maps public IDs to DTD resource names
074     * @throws SAXException if an error occurs
075     * @throws ParserConfigurationException if an error occurs
076     */
077    protected AbstractLoader(Map<String, String> publicIdToResourceNameMap)
078            throws SAXException, ParserConfigurationException {
079        this.publicIdToResourceNameMap = new HashMap<>(publicIdToResourceNameMap);
080        final SAXParserFactory factory = SAXParserFactory.newInstance();
081        FeaturesForVerySecureJavaInstallations.addFeaturesForVerySecureJavaInstallations(factory);
082        factory.setValidating(true);
083        factory.setNamespaceAware(true);
084        parser = factory.newSAXParser().getXMLReader();
085        parser.setContentHandler(this);
086        parser.setEntityResolver(this);
087        parser.setErrorHandler(this);
088    }
089
090    /**
091     * Parses the specified input source.
092     * @param inputSource the input source to parse.
093     * @throws IOException if an error occurs
094     * @throws SAXException in an error occurs
095     */
096    public void parseInputSource(InputSource inputSource)
097            throws IOException, SAXException {
098        parser.parse(inputSource);
099    }
100
101    @Override
102    public InputSource resolveEntity(String publicId, String systemId)
103            throws SAXException, IOException {
104        final InputSource inputSource;
105        if (publicIdToResourceNameMap.keySet().contains(publicId)) {
106            final String dtdResourceName =
107                    publicIdToResourceNameMap.get(publicId);
108            final ClassLoader loader =
109                getClass().getClassLoader();
110            final InputStream dtdIs =
111                loader.getResourceAsStream(dtdResourceName);
112
113            inputSource = new InputSource(dtdIs);
114        }
115        else {
116            inputSource = super.resolveEntity(publicId, systemId);
117        }
118        return inputSource;
119    }
120
121    @Override
122    public void error(SAXParseException exception) throws SAXException {
123        throw exception;
124    }
125
126    @Override
127    public void fatalError(SAXParseException exception) throws SAXException {
128        throw exception;
129    }
130
131    /**
132     * Used for setting specific for secure java installations features to SAXParserFactory.
133     * Pulled out as a separate class in order to suppress Pitest mutations.
134     */
135    public static final class FeaturesForVerySecureJavaInstallations {
136        /** Feature that enables loading external DTD when loading XML files. */
137        private static final String LOAD_EXTERNAL_DTD =
138                "http://apache.org/xml/features/nonvalidating/load-external-dtd";
139        /** Feature that enables including external general entities in XML files. */
140        private static final String EXTERNAL_GENERAL_ENTITIES =
141                "http://xml.org/sax/features/external-general-entities";
142
143        /** Stop instances being created. **/
144        private FeaturesForVerySecureJavaInstallations() {
145        }
146
147        /**
148         * Configures SAXParserFactory with features requered
149         * for exectution on very secured environments.
150         * @param factory factory to be configured with spectial features
151         * @throws SAXException if an error occurs
152         * @throws ParserConfigurationException if an error occurs
153         */
154        public static void addFeaturesForVerySecureJavaInstallations(SAXParserFactory factory)
155                throws SAXException, ParserConfigurationException {
156            factory.setFeature(LOAD_EXTERNAL_DTD, true);
157            factory.setFeature(EXTERNAL_GENERAL_ENTITIES, true);
158        }
159    }
160}