CheckResourceKeys.java revision 2942:08092deced3f
1/*
2 * Copyright (c) 2010, 2015, Oracle and/or its affiliates. All rights reserved.
3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 *
5 * This code is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 only, as
7 * published by the Free Software Foundation.
8 *
9 * This code is distributed in the hope that it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
12 * version 2 for more details (a copy is included in the LICENSE file that
13 * accompanied this code).
14 *
15 * You should have received a copy of the GNU General Public License version
16 * 2 along with this work; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
18 *
19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
20 * or visit www.oracle.com if you need additional information or have any
21 * questions.
22 */
23
24/*
25 * @test
26 * @bug 8000612
27 * @summary need test program to validate javadoc resource bundles
28 * @modules jdk.jdeps/com.sun.tools.classfile
29 */
30
31import java.io.*;
32import java.util.*;
33import javax.tools.*;
34import com.sun.tools.classfile.*;
35
36/**
37 * Compare string constants in javadoc classes against keys in javadoc resource bundles.
38 */
39public class CheckResourceKeys {
40    /**
41     * Main program.
42     * Options:
43     * -finddeadkeys
44     *      look for keys in resource bundles that are no longer required
45     * -findmissingkeys
46     *      look for keys in resource bundles that are missing
47     *
48     * @throws Exception if invoked by jtreg and errors occur
49     */
50    public static void main(String... args) throws Exception {
51        CheckResourceKeys c = new CheckResourceKeys();
52        if (c.run(args))
53            return;
54
55        if (is_jtreg())
56            throw new Exception(c.errors + " errors occurred");
57        else
58            System.exit(1);
59    }
60
61    static boolean is_jtreg() {
62        return (System.getProperty("test.src") != null);
63    }
64
65    /**
66     * Main entry point.
67     */
68    boolean run(String... args) throws Exception {
69        boolean findDeadKeys = false;
70        boolean findMissingKeys = false;
71
72        if (args.length == 0) {
73            if (is_jtreg()) {
74                findDeadKeys = true;
75                findMissingKeys = true;
76            } else {
77                System.err.println("Usage: java CheckResourceKeys <options>");
78                System.err.println("where options include");
79                System.err.println("  -finddeadkeys      find keys in resource bundles which are no longer required");
80                System.err.println("  -findmissingkeys   find keys in resource bundles that are required but missing");
81                return true;
82            }
83        } else {
84            for (String arg: args) {
85                if (arg.equalsIgnoreCase("-finddeadkeys"))
86                    findDeadKeys = true;
87                else if (arg.equalsIgnoreCase("-findmissingkeys"))
88                    findMissingKeys = true;
89                else
90                    error("bad option: " + arg);
91            }
92        }
93
94        if (errors > 0)
95            return false;
96
97        Set<String> codeKeys = getCodeKeys();
98        Set<String> resourceKeys = getResourceKeys();
99
100        System.err.println("found " + codeKeys.size() + " keys in code");
101        System.err.println("found " + resourceKeys.size() + " keys in resource bundles");
102
103        if (findDeadKeys)
104            findDeadKeys(codeKeys, resourceKeys);
105
106        if (findMissingKeys)
107            findMissingKeys(codeKeys, resourceKeys);
108
109        return (errors == 0);
110    }
111
112    /**
113     * Find keys in resource bundles which are probably no longer required.
114     * A key is required if there is a string in the code that is a resource key,
115     * or if the key is well-known according to various pragmatic rules.
116     */
117    void findDeadKeys(Set<String> codeKeys, Set<String> resourceKeys) {
118        for (String rk: resourceKeys) {
119            if (codeKeys.contains(rk))
120                continue;
121
122            error("Resource key not found in code: " + rk);
123        }
124    }
125
126    /**
127     * For all strings in the code that look like they might be
128     * a resource key, verify that a key exists.
129     */
130    void findMissingKeys(Set<String> codeKeys, Set<String> resourceKeys) {
131        for (String ck: codeKeys) {
132            if (resourceKeys.contains(ck))
133                continue;
134            error("No resource for \"" + ck + "\"");
135        }
136    }
137
138    /**
139     * Get the set of strings from (most of) the javadoc classfiles.
140     */
141    Set<String> getCodeKeys() throws IOException {
142        Set<String> results = new TreeSet<String>();
143        JavaCompiler c = ToolProvider.getSystemJavaCompiler();
144        try (JavaFileManager fm = c.getStandardFileManager(null, null, null)) {
145            JavaFileManager.Location javadocLoc = findJavadocLocation(fm);
146            String[] pkgs = {
147                "com.sun.tools.doclets",
148                "com.sun.tools.javadoc"
149            };
150            for (String pkg: pkgs) {
151                for (JavaFileObject fo: fm.list(javadocLoc,
152                        pkg, EnumSet.of(JavaFileObject.Kind.CLASS), true)) {
153                    String name = fo.getName();
154                    // ignore resource files
155                    if (name.matches(".*resources.[A-Za-z_0-9]+\\.class.*"))
156                        continue;
157                    scan(fo, results);
158                }
159            }
160
161            // special handling for code strings synthesized in
162            // com.sun.tools.doclets.internal.toolkit.util.Util.getTypeName
163            String[] extras = {
164                "AnnotationType", "Class", "Enum", "Error", "Exception", "Interface"
165            };
166            for (String s: extras) {
167                if (results.contains("doclet." + s))
168                    results.add("doclet." + s.toLowerCase());
169            }
170
171            // special handling for code strings synthesized in
172            // com.sun.tools.javadoc.Messager
173            results.add("javadoc.error.msg");
174            results.add("javadoc.note.msg");
175            results.add("javadoc.note.pos.msg");
176            results.add("javadoc.warning.msg");
177
178            return results;
179        }
180    }
181
182    // depending on how the test is run, javadoc may be on bootclasspath or classpath
183    JavaFileManager.Location findJavadocLocation(JavaFileManager fm) {
184        JavaFileManager.Location[] locns =
185            { StandardLocation.PLATFORM_CLASS_PATH, StandardLocation.CLASS_PATH };
186        try {
187            for (JavaFileManager.Location l: locns) {
188                JavaFileObject fo = fm.getJavaFileForInput(l,
189                    "com.sun.tools.javadoc.Main", JavaFileObject.Kind.CLASS);
190                if (fo != null) {
191                    System.err.println("found javadoc in " + l);
192                    return l;
193                }
194            }
195        } catch (IOException e) {
196            throw new Error(e);
197        }
198        throw new IllegalStateException("Cannot find javadoc");
199    }
200
201    /**
202     * Get the set of strings from a class file.
203     * Only strings that look like they might be a resource key are returned.
204     */
205    void scan(JavaFileObject fo, Set<String> results) throws IOException {
206        //System.err.println("scan " + fo.getName());
207        InputStream in = fo.openInputStream();
208        try {
209            ClassFile cf = ClassFile.read(in);
210            for (ConstantPool.CPInfo cpinfo: cf.constant_pool.entries()) {
211                if (cpinfo.getTag() == ConstantPool.CONSTANT_Utf8) {
212                    String v = ((ConstantPool.CONSTANT_Utf8_info) cpinfo).value;
213                    if (v.matches("(doclet|main|javadoc|tag)\\.[A-Za-z0-9-_.]+"))
214                        results.add(v);
215                }
216            }
217        } catch (ConstantPoolException ignore) {
218        } finally {
219            in.close();
220        }
221    }
222
223    /**
224     * Get the set of keys from the javadoc resource bundles.
225     */
226    Set<String> getResourceKeys() {
227        String[] names = {
228                "com.sun.tools.doclets.formats.html.resources.standard",
229                "com.sun.tools.doclets.internal.toolkit.resources.doclets",
230                "com.sun.tools.javadoc.resources.javadoc",
231        };
232        Set<String> results = new TreeSet<String>();
233        for (String name : names) {
234            ResourceBundle b = ResourceBundle.getBundle(name);
235            results.addAll(b.keySet());
236        }
237        return results;
238    }
239
240    /**
241     * Report an error.
242     */
243    void error(String msg) {
244        System.err.println("Error: " + msg);
245        errors++;
246    }
247
248    int errors;
249}
250