View Javadoc
1   ////////////////////////////////////////////////////////////////////////////////
2   // checkstyle: Checks Java source code for adherence to a set of rules.
3   // Copyright (C) 2001-2018 the original author or authors.
4   //
5   // This library is free software; you can redistribute it and/or
6   // modify it under the terms of the GNU Lesser General Public
7   // License as published by the Free Software Foundation; either
8   // version 2.1 of the License, or (at your option) any later version.
9   //
10  // This library is distributed in the hope that it will be useful,
11  // but WITHOUT ANY WARRANTY; without even the implied warranty of
12  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  // Lesser General Public License for more details.
14  //
15  // You should have received a copy of the GNU Lesser General Public
16  // License along with this library; if not, write to the Free Software
17  // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
18  ////////////////////////////////////////////////////////////////////////////////
19  
20  package com.puppycrawl.tools.checkstyle;
21  
22  import java.io.BufferedInputStream;
23  import java.io.IOException;
24  import java.io.InputStream;
25  import java.net.URL;
26  import java.util.ArrayDeque;
27  import java.util.Deque;
28  import java.util.Enumeration;
29  import java.util.Iterator;
30  import java.util.LinkedHashSet;
31  import java.util.Set;
32  
33  import javax.xml.parsers.ParserConfigurationException;
34  
35  import org.xml.sax.Attributes;
36  import org.xml.sax.InputSource;
37  import org.xml.sax.SAXException;
38  
39  import com.google.common.io.Closeables;
40  import com.puppycrawl.tools.checkstyle.api.CheckstyleException;
41  import com.puppycrawl.tools.checkstyle.utils.CommonUtils;
42  
43  /**
44   * Loads a list of package names from a package name XML file.
45   * @author Rick Giles
46   */
47  public final class PackageNamesLoader
48      extends XmlLoader {
49  
50      /** The public ID for the configuration dtd. */
51      private static final String DTD_PUBLIC_ID =
52          "-//Puppy Crawl//DTD Package Names 1.0//EN";
53  
54      /** The resource for the configuration dtd. */
55      private static final String DTD_RESOURCE_NAME =
56          "com/puppycrawl/tools/checkstyle/packages_1_0.dtd";
57  
58      /** Name of default checkstyle package names resource file.
59       * The file must be in the classpath.
60       */
61      private static final String CHECKSTYLE_PACKAGES =
62          "checkstyle_packages.xml";
63  
64      /** Qualified name for element 'package'. */
65      private static final String PACKAGE_ELEMENT_NAME = "package";
66  
67      /** The temporary stack of package name parts. */
68      private final Deque<String> packageStack = new ArrayDeque<>();
69  
70      /** The fully qualified package names. */
71      private final Set<String> packageNames = new LinkedHashSet<>();
72  
73      /**
74       * Creates a new {@code PackageNamesLoader} instance.
75       * @throws ParserConfigurationException if an error occurs
76       * @throws SAXException if an error occurs
77       */
78      private PackageNamesLoader()
79              throws ParserConfigurationException, SAXException {
80          super(DTD_PUBLIC_ID, DTD_RESOURCE_NAME);
81      }
82  
83      @Override
84      public void startElement(String uri,
85                               String localName,
86                               String qName,
87                               Attributes attributes) {
88          if (PACKAGE_ELEMENT_NAME.equals(qName)) {
89              //push package name, name is mandatory attribute with not empty value by DTD
90              final String name = attributes.getValue("name");
91              packageStack.push(name);
92          }
93      }
94  
95      /**
96       * Creates a full package name from the package names on the stack.
97       * @return the full name of the current package.
98       */
99      private String getPackageName() {
100         final StringBuilder buf = new StringBuilder(256);
101         final Iterator<String> iterator = packageStack.descendingIterator();
102         while (iterator.hasNext()) {
103             final String subPackage = iterator.next();
104             buf.append(subPackage);
105             if (!CommonUtils.endsWithChar(subPackage, '.') && iterator.hasNext()) {
106                 buf.append('.');
107             }
108         }
109         return buf.toString();
110     }
111 
112     @Override
113     public void endElement(String uri,
114                            String localName,
115                            String qName) {
116         if (PACKAGE_ELEMENT_NAME.equals(qName)) {
117             packageNames.add(getPackageName());
118             packageStack.pop();
119         }
120     }
121 
122     /**
123      * Returns the set of package names, compiled from all
124      * checkstyle_packages.xml files found on the given class loaders
125      * classpath.
126      * @param classLoader the class loader for loading the
127      *          checkstyle_packages.xml files.
128      * @return the set of package names.
129      * @throws CheckstyleException if an error occurs.
130      */
131     public static Set<String> getPackageNames(ClassLoader classLoader)
132             throws CheckstyleException {
133         final Set<String> result;
134         try {
135             //create the loader outside the loop to prevent PackageObjectFactory
136             //being created anew for each file
137             final PackageNamesLoader namesLoader = new PackageNamesLoader();
138 
139             final Enumeration<URL> packageFiles = classLoader.getResources(CHECKSTYLE_PACKAGES);
140 
141             while (packageFiles.hasMoreElements()) {
142                 processFile(packageFiles.nextElement(), namesLoader);
143             }
144 
145             result = namesLoader.packageNames;
146         }
147         catch (IOException ex) {
148             throw new CheckstyleException("unable to get package file resources", ex);
149         }
150         catch (ParserConfigurationException | SAXException ex) {
151             throw new CheckstyleException("unable to open one of package files", ex);
152         }
153 
154         return result;
155     }
156 
157     /**
158      * Reads the file provided and parses it with package names loader.
159      * @param packageFile file from package
160      * @param namesLoader package names loader
161      * @throws SAXException if an error while parsing occurs
162      * @throws CheckstyleException if unable to open file
163      */
164     private static void processFile(URL packageFile, PackageNamesLoader namesLoader)
165             throws SAXException, CheckstyleException {
166         InputStream stream = null;
167         try {
168             stream = new BufferedInputStream(packageFile.openStream());
169             final InputSource source = new InputSource(stream);
170             namesLoader.parseInputSource(source);
171         }
172         catch (IOException ex) {
173             throw new CheckstyleException("unable to open " + packageFile, ex);
174         }
175         finally {
176             Closeables.closeQuietly(stream);
177         }
178     }
179 
180 }