NativeHeaderTest.java 9.2 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274
/*
 * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
 */

/*
 * @test
 * @bug 7150368
 * @summary javac should include basic ability to generate native headers
 */

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.tools.StandardJavaFileManager;
import javax.tools.StandardLocation;

import com.sun.source.util.JavacTask;
import com.sun.tools.javac.api.JavacTool;

public class NativeHeaderTest {
    public static void main(String... args) throws Exception {
        new NativeHeaderTest().run();
    }

    /** How to invoke javac. */
    enum RunKind {
        /** Use the command line entry point. */
        CMD,
        /** Use the JavaCompiler API. */
        API
    };

    /** Which classes for which to generate headers. */
    enum GenKind {
        /** Just classes with native methods or the marker annotation. */
        SIMPLE,
        /** All appropriate classes within the top level class. */
        FULL
    };

    // ---------- Test cases, invoked reflectively via run. ----------

    @Test
    void simpleTest(RunKind rk, GenKind gk) throws Exception {
        List<File> files = new ArrayList<File>();
        files.add(createFile("p/C.java",
                "class C { native void m(); }"));

        Set<String> expect = createSet("C.h");

        test(rk, gk, files, expect);
    }

    @Test
    void nestedClassTest(RunKind rk, GenKind gk) throws Exception {
        List<File> files = new ArrayList<File>();
        files.add(createFile("p/C.java",
                "class C { static class Inner { native void m(); } }"));

        Set<String> expect = createSet("C_Inner.h");
        if (gk == GenKind.FULL) expect.add("C.h");

        test(rk, gk, files, expect);
    }

    @Test
    void localClassTest(RunKind rk, GenKind gk) throws Exception {
        List<File> files = new ArrayList<File>();
        files.add(createFile("p/C.java",
                "class C { native void m(); void m2() { class Local { } } }"));

        Set<String> expect = createSet("C.h");

        test(rk, gk, files, expect);
    }

    @Test
    void syntheticClassTest(RunKind rk, GenKind gk) throws Exception {
        List<File> files = new ArrayList<File>();
        files.add(createFile("p/C.java",
                "class C {\n"
                + "    private C() { }\n"
                + "    class Inner extends C { native void m(); }\n"
                + "}"));

        Set<String> expect = createSet("C_Inner.h");
        if (gk == GenKind.FULL) expect.add("C.h");

        test(rk, gk, files, expect);

        // double check the synthetic class was generated
        checkEqual("generatedClasses",
                createSet("C.class", "C$1.class", "C$Inner.class"),
                createSet(classesDir.list()));
    }

    @Test
    void annoTest(RunKind rk, GenKind gk) throws Exception {
        List<File> files = new ArrayList<File>();
        files.add(createFile("p/C.java",
                "@javax.tools.annotation.GenerateNativeHeader class C { }"));

        Set<String> expect = createSet("C.h");

        test(rk, gk, files, expect);
    }

    @Test
    void annoNestedClassTest(RunKind rk, GenKind gk) throws Exception {
        List<File> files = new ArrayList<File>();
        files.add(createFile("p/C.java",
                "class C { @javax.tools.annotation.GenerateNativeHeader class Inner { } }"));

        Set<String> expect = createSet("C_Inner.h");
        if (gk == GenKind.FULL) expect.add("C.h");

        test(rk, gk, files, expect);
    }

    /**
     * The worker method for each test case.
     * Compile the files and verify that exactly the expected set of header files
     * is generated.
     */
    void test(RunKind rk, GenKind gk, List<File> files, Set<String> expect) throws Exception {
        List<String> args = new ArrayList<String>();
        if (gk == GenKind.FULL)
            args.add("-XDjavah:full");

        switch (rk) {
            case CMD:
                args.add("-d");
                args.add(classesDir.getPath());
                args.add("-h");
                args.add(headersDir.getPath());
                for (File f: files)
                    args.add(f.getPath());
                int rc = com.sun.tools.javac.Main.compile(args.toArray(new String[args.size()]));
                if (rc != 0)
                    throw new Exception("compilation failed, rc=" + rc);
                break;

            case API:
                fm.setLocation(StandardLocation.SOURCE_PATH, Arrays.asList(srcDir));
                fm.setLocation(StandardLocation.CLASS_OUTPUT, Arrays.asList(classesDir));
                fm.setLocation(StandardLocation.NATIVE_HEADER_OUTPUT, Arrays.asList(headersDir));
                JavacTask task = javac.getTask(null, fm, null, args, null,
                        fm.getJavaFileObjectsFromFiles(files));
                if (!task.call())
                    throw new Exception("compilation failed");
                break;
        }

        Set<String> found = createSet(headersDir.list());
        checkEqual("header files", expect, found);
    }

    /** Marker annotation for test cases. */
    @Retention(RetentionPolicy.RUNTIME)
    @interface Test { }

    /** Combo test to run all test cases in all modes. */
    void run() throws Exception {
        javac = JavacTool.create();
        fm = javac.getStandardFileManager(null, null, null);

        for (RunKind rk: RunKind.values()) {
            for (GenKind gk: GenKind.values()) {
                for (Method m: getClass().getDeclaredMethods()) {
                    Annotation a = m.getAnnotation(Test.class);
                    if (a != null) {
                        init(rk, gk, m.getName());
                        try {
                            m.invoke(this, new Object[] { rk, gk });
                        } catch (InvocationTargetException e) {
                            Throwable cause = e.getCause();
                            throw (cause instanceof Exception) ? ((Exception) cause) : e;
                        }
                        System.err.println();
                    }
                }
            }
        }
        System.err.println(testCount + " tests" + ((errorCount == 0) ? "" : ", " + errorCount + " errors"));
        if (errorCount > 0)
            throw new Exception(errorCount + " errors found");
    }

    /**
     * Init directories for a test case.
     */
    void init(RunKind rk, GenKind gk, String name) throws IOException {
        System.err.println("Test " + rk + " " + gk + " " + name);
        testCount++;

        testDir = new File(rk.toString().toLowerCase() + "_" + gk.toString().toLowerCase() + "-" + name);
        srcDir = new File(testDir, "src");
        srcDir.mkdirs();
        classesDir = new File(testDir, "classes");
        classesDir.mkdirs();
        headersDir = new File(testDir, "headers");
        headersDir.mkdirs();
    }

    /** Create a source file with given body text. */
    File createFile(String path, final String body) throws IOException {
        File f = new File(srcDir, path);
        f.getParentFile().mkdirs();
        try (FileWriter out = new FileWriter(f)) {
            out.write(body);
        }
        return f;
    }

    /** Convenience method to create a set of items. */
    <T> Set<T> createSet(T... items) {
        return new HashSet<T>(Arrays.asList(items));
    }

    /** Convenience method to check two values are equal, and report an error if not. */
    <T> void checkEqual(String label, T expect, T found) {
        if ((found == null) ? (expect == null) : found.equals(expect))
            return;
        System.err.println("Error: mismatch");
        System.err.println("  expected: " + expect);
        System.err.println("     found: " + found);
        errorCount++;
    }

    // Shared across API test cases
    JavacTool javac;
    StandardJavaFileManager fm;

    // Directories set up by init
    File testDir;
    File srcDir;
    File classesDir;
    File headersDir;

    // Statistics
    int testCount;
    int errorCount;
}