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.BufferedInputStream;
023import java.io.IOException;
024import java.io.InputStream;
025import java.net.URL;
026import java.util.ArrayDeque;
027import java.util.Collections;
028import java.util.Deque;
029import java.util.Enumeration;
030import java.util.HashMap;
031import java.util.Iterator;
032import java.util.LinkedHashSet;
033import java.util.Map;
034import java.util.Set;
035
036import javax.xml.parsers.ParserConfigurationException;
037
038import org.xml.sax.Attributes;
039import org.xml.sax.InputSource;
040import org.xml.sax.SAXException;
041
042import com.puppycrawl.tools.checkstyle.api.CheckstyleException;
043
044/**
045 * Loads a list of package names from a package name XML file.
046 */
047public final class PackageNamesLoader extends XmlLoader {
048
049    /** The public ID for the configuration dtd. */
050    private static final String DTD_PUBLIC_ID =
051        "-//Puppy Crawl//DTD Package Names 1.0//EN";
052
053    /** The new public ID for the configuration dtd. */
054    private static final String DTD_PUBLIC_CS_ID =
055        "-//Checkstyle//DTD Package Names Configuration 1.0//EN";
056
057    /** The resource for the configuration dtd. */
058    private static final String DTD_RESOURCE_NAME =
059        "com/puppycrawl/tools/checkstyle/packages_1_0.dtd";
060
061    /**
062     * Name of default checkstyle package names resource file.
063     * The file must be in the classpath.
064     */
065    private static final String CHECKSTYLE_PACKAGES =
066        "checkstyle_packages.xml";
067
068    /** Qualified name for element 'package'. */
069    private static final String PACKAGE_ELEMENT_NAME = "package";
070
071    /** The temporary stack of package name parts. */
072    private final Deque<String> packageStack = new ArrayDeque<>();
073
074    /** The fully qualified package names. */
075    private final Set<String> packageNames = new LinkedHashSet<>();
076
077    /**
078     * Creates a new {@code PackageNamesLoader} instance.
079     *
080     * @throws ParserConfigurationException if an error occurs
081     * @throws SAXException if an error occurs
082     */
083    private PackageNamesLoader()
084            throws ParserConfigurationException, SAXException {
085        super(createIdToResourceNameMap());
086    }
087
088    @Override
089    public void startElement(String uri,
090                             String localName,
091                             String qName,
092                             Attributes attributes) {
093        if (PACKAGE_ELEMENT_NAME.equals(qName)) {
094            // push package name, name is mandatory attribute with not empty value by DTD
095            final String name = attributes.getValue("name");
096            packageStack.push(name);
097        }
098    }
099
100    /**
101     * Creates a full package name from the package names on the stack.
102     *
103     * @return the full name of the current package.
104     */
105    private String getPackageName() {
106        final StringBuilder buf = new StringBuilder(256);
107        final Iterator<String> iterator = packageStack.descendingIterator();
108        while (iterator.hasNext()) {
109            final String subPackage = iterator.next();
110            buf.append(subPackage);
111            if (!subPackage.endsWith(".") && iterator.hasNext()) {
112                buf.append('.');
113            }
114        }
115        return buf.toString();
116    }
117
118    @Override
119    public void endElement(String uri,
120                           String localName,
121                           String qName) {
122        if (PACKAGE_ELEMENT_NAME.equals(qName)) {
123            packageNames.add(getPackageName());
124            packageStack.pop();
125        }
126    }
127
128    /**
129     * Returns the set of package names, compiled from all
130     * checkstyle_packages.xml files found on the given class loaders classpath.
131     *
132     * @param classLoader the class loader for loading the checkstyle_packages.xml files.
133     * @return the set of package names.
134     * @throws CheckstyleException if an error occurs.
135     */
136    public static Set<String> getPackageNames(ClassLoader classLoader)
137            throws CheckstyleException {
138        final Set<String> result;
139        try {
140            // create the loader outside the loop to prevent PackageObjectFactory
141            // being created anew for each file
142            final PackageNamesLoader namesLoader = new PackageNamesLoader();
143
144            final Enumeration<URL> packageFiles = classLoader.getResources(CHECKSTYLE_PACKAGES);
145
146            while (packageFiles.hasMoreElements()) {
147                processFile(packageFiles.nextElement(), namesLoader);
148            }
149
150            result = namesLoader.packageNames;
151        }
152        catch (IOException exc) {
153            throw new CheckstyleException("unable to get package file resources with "
154                    + classLoader.getClass().getName(), exc);
155        }
156        catch (ParserConfigurationException | SAXException exc) {
157            throw new CheckstyleException("unable to open one of package files with "
158                    + classLoader.getClass().getName(), exc);
159        }
160
161        return Collections.unmodifiableSet(result);
162    }
163
164    /**
165     * Reads the file provided and parses it with package names loader.
166     *
167     * @param packageFile file from package
168     * @param namesLoader package names loader
169     * @throws CheckstyleException if unable to open file
170     * @throws SAXException if an error while parsing occurs
171     */
172    private static void processFile(URL packageFile, PackageNamesLoader namesLoader)
173            throws SAXException, CheckstyleException {
174        try (InputStream stream = new BufferedInputStream(packageFile.openStream())) {
175            final InputSource source = new InputSource(stream);
176            namesLoader.parseInputSource(source);
177        }
178        catch (IOException exc) {
179            throw new CheckstyleException("unable to open " + packageFile, exc);
180        }
181    }
182
183    /**
184     * Creates mapping between local resources and dtd ids.
185     *
186     * @return map between local resources and dtd ids.
187     */
188    private static Map<String, String> createIdToResourceNameMap() {
189        final Map<String, String> map = new HashMap<>();
190        map.put(DTD_PUBLIC_ID, DTD_RESOURCE_NAME);
191        map.put(DTD_PUBLIC_CS_ID, DTD_RESOURCE_NAME);
192        return map;
193    }
194
195}