< prev index next >

test/jdk/java/lang/invoke/lambda/LogGeneratedClassesTest.java

Print this page

  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 8023524 8304846
 27  * @summary tests logging generated classes for lambda

 28  * @library /java/nio/file
 29  * @modules jdk.compiler
 30  *          jdk.zipfs
 31  * @run testng LogGeneratedClassesTest

 32  */
 33 import java.io.File;
 34 import java.io.IOException;

 35 import java.util.ArrayList;
 36 import java.util.List;
 37 import java.util.function.Predicate;
 38 import java.nio.file.Files;
 39 import java.nio.file.Path;
 40 import java.nio.file.Paths;
 41 import java.nio.file.attribute.PosixFileAttributeView;
 42 


 43 import org.testng.annotations.AfterClass;
 44 import org.testng.annotations.BeforeClass;
 45 import org.testng.annotations.Test;
 46 import org.testng.SkipException;
 47 
 48 import static java.nio.file.attribute.PosixFilePermissions.*;

 49 import static org.testng.Assert.assertEquals;
 50 import static org.testng.Assert.assertFalse;
 51 import static org.testng.Assert.assertTrue;
 52 
 53 public class LogGeneratedClassesTest extends LUtils {
 54     static final Path DUMP_LAMBDA_PROXY_CLASS_FILES = Path.of("DUMP_LAMBDA_PROXY_CLASS_FILES");

 55     String longFQCN;
 56 
 57     @BeforeClass
 58     public void setup() throws IOException {
 59         final List<String> scratch = new ArrayList<>();
 60         scratch.clear();
 61         scratch.add("package com.example;");
 62         scratch.add("public class TestLambda {");
 63         scratch.add("    interface I {");
 64         scratch.add("        int foo();");
 65         scratch.add("    }");
 66         scratch.add("    public static void main(String[] args) {");
 67         scratch.add("        System.setSecurityManager(new SecurityManager());");
 68         scratch.add("        I lam = () -> 10;");
 69         scratch.add("        Runnable r = () -> {");
 70         scratch.add("            System.out.println(\"Runnable\");");
 71         scratch.add("        };");
 72         scratch.add("        r.run();");
 73         scratch.add("        System.out.println(\"Finish\");");
 74         scratch.add("    }");
 75         scratch.add("}");
 76 
 77         File test = new File("TestLambda.java");
 78         createFile(test, scratch);
 79         compile("-d", ".", test.getName());
 80 
 81         scratch.remove(0);
 82         scratch.remove(0);
 83         scratch.add(0, "public class LongPackageName {");
 84         StringBuilder sb = new StringBuilder("com.example.");
 85         // longer than 255 which exceed max length of most filesystems
 86         for (int i = 0; i < 30; i++) {
 87             sb.append("nonsense.");
 88         }
 89         sb.append("enough");
 90         longFQCN = sb.toString() + ".LongPackageName";
 91         sb.append(";");
 92         sb.insert(0, "package ");
 93         scratch.add(0, sb.toString());
 94         test = new File("LongPackageName.java");
 95         createFile(test, scratch);
 96         compile("-d", ".", test.getName());

 97     }
 98 
 99     @AfterClass
100     public void cleanup() throws IOException {
101         Files.delete(Paths.get("TestLambda.java"));
102         Files.delete(Paths.get("LongPackageName.java"));
103         TestUtil.removeAll(DUMP_LAMBDA_PROXY_CLASS_FILES);
104         TestUtil.removeAll(Paths.get("notDir"));
105         TestUtil.removeAll(Paths.get("dump"));
106         TestUtil.removeAll(Paths.get("dumpLong"));
107     }
108 
109     @Test
110     public void testNotLogging() {
111         TestResult tr = doExec(JAVA_CMD.getAbsolutePath(),
112                                "-cp", ".",
113                                "-Djava.security.manager=allow",
114                                "com.example.TestLambda");
115         tr.assertZero("Should still return 0");
116     }
117 
118     @Test
119     public void testLogging() throws IOException {
120         Path testDir = Path.of("dump");
121         Path dumpDir = testDir.resolve(DUMP_LAMBDA_PROXY_CLASS_FILES);
122         Files.createDirectory(testDir);
123         TestResult tr = doExec(JAVA_CMD.getAbsolutePath(),
124                                "-cp", "..",
125                                "-Duser.dir=" + testDir.toAbsolutePath(),
126                                "-Djava.security.manager=allow",
127                                "-Djdk.invoke.LambdaMetafactory.dumpProxyClassFiles",
128                                "com.example.TestLambda");


129         // 2 our own class files. We don't care about the others
130         assertEquals(Files.find(
131                         dumpDir,
132                         99,
133                         (p, a) -> p.startsWith(dumpDir.resolve("com/example"))
134                                 && a.isRegularFile()).count(),
135                       2, "Two lambda captured");
136         tr.assertZero("Should still return 0");
137     }
138 
139     @Test
140     public void testDumpDirNotExist() throws IOException {
141         Path testDir = Path.of("NotExist");
142         Path dumpDir = testDir.resolve(DUMP_LAMBDA_PROXY_CLASS_FILES);
143         Files.createDirectory(testDir);
144         TestUtil.removeAll(dumpDir);
145 
146         assertFalse(Files.exists(dumpDir));
147         TestResult tr = doExec(JAVA_CMD.getAbsolutePath(),
148                                "-cp", "..",
149                                "-Duser.dir=" + testDir.toAbsolutePath(),
150                                "-Djava.security.manager=allow",
151                                "-Djdk.invoke.LambdaMetafactory.dumpProxyClassFiles",
152                                "com.example.TestLambda");

153 
154         // The dump directory will be created if not exist
155         assertEquals(Files.find(
156                         dumpDir,
157                         99,
158                         (p, a) -> p.startsWith(dumpDir.resolve("com/example"))
159                                 && a.isRegularFile()).count(),
160                     2, "Two lambda captured");
161         tr.assertZero("Should still return 0");
162     }
163 
164     @Test
165     public void testDumpDirIsFile() throws IOException {
166         Path testDir = Path.of("notDir");
167         Path dumpFile = testDir.resolve(DUMP_LAMBDA_PROXY_CLASS_FILES);
168         Files.createDirectory(testDir);
169         Files.createFile(dumpFile);
170         assertTrue(Files.isRegularFile(dumpFile));
171         TestResult tr = doExec(JAVA_CMD.getAbsolutePath(),
172                                "-cp", "..",
173                                "-Duser.dir=" + testDir.toAbsolutePath(),
174                                "-Djava.security.manager=allow",
175                                "-Djdk.invoke.LambdaMetafactory.dumpProxyClassFiles",
176                                "com.example.TestLambda");
177         assertEquals(tr.testOutput.stream()
178                                   .filter(s -> s.contains("DUMP_LAMBDA_PROXY_CLASS_FILES is not a directory"))
179                                   .count(),
180                      1, "only show error once");
181         assertTrue(tr.exitValue != 0);
182     }
183 
184     private static boolean isWriteableDirectory(Path p) {
185         if (!Files.isDirectory(p)) {
186             return false;
187         }
188         Path test = p.resolve(Paths.get("test"));
189         try {
190             Files.createFile(test);
191             assertTrue(Files.exists(test));
192             return true;
193         } catch (IOException e) {
194             assertFalse(Files.exists(test));
195             return false;
196         } finally {
197             if (Files.exists(test)) {
198                 try {
199                     Files.delete(test);
200                 } catch (IOException e) {
201                     throw new Error(e);
202                 }
203             }
204         }
205     }
206 
207     @Test
208     public void testDumpDirNotWritable() throws IOException {
209         if (!Files.getFileStore(Paths.get("."))
210                   .supportsFileAttributeView(PosixFileAttributeView.class)) {
211             // No easy way to setup readonly directory without POSIX
212             // We would like to skip the test with a cause with
213             //     throw new SkipException("Posix not supported");
214             // but jtreg will report failure so we just pass the test
215             // which we can look at if jtreg changed its behavior
216             System.out.println("WARNING: POSIX is not supported. Skipping testDumpDirNotWritable test.");
217             return;
218         }
219 
220         Path testDir = Path.of("readOnly");
221         Path dumpDir = testDir.resolve(DUMP_LAMBDA_PROXY_CLASS_FILES);
222         Files.createDirectory(testDir);
223         Files.createDirectory(dumpDir,
224                               asFileAttribute(fromString("r-xr-xr-x")));
225         try {
226             if (isWriteableDirectory(dumpDir)) {
227                 // Skipping the test: it's allowed to write into read-only directory
228                 // (e.g. current user is super user).
229                 System.out.println("WARNING: The dump directory is writeable. Skipping testDumpDirNotWritable test.");
230                 return;
231             }
232 
233             TestResult tr = doExec(JAVA_CMD.getAbsolutePath(),
234                                    "-cp", "..",
235                                    "-Duser.dir=" + testDir.toAbsolutePath(),
236                                    "-Djava.security.manager=allow",
237                                    "-Djdk.invoke.LambdaMetafactory.dumpProxyClassFiles",
238                                    "com.example.TestLambda");
239             assertEquals(tr.testOutput.stream()
240                                       .filter(s -> s.contains("DUMP_LAMBDA_PROXY_CLASS_FILES is not writable"))
241                                       .count(),
242                          1, "only show error once");
243             assertTrue(tr.exitValue != 0);
244         } finally {
245             TestUtil.removeAll(testDir);
246         }
247     }
248 
249     @Test
250     public void testLoggingException() throws IOException {
251         Path testDir = Path.of("dumpLong");
252         Path dumpDir = testDir.resolve(DUMP_LAMBDA_PROXY_CLASS_FILES);
253         Files.createDirectories(dumpDir.resolve("com/example/nonsense"));
254         Files.createFile(dumpDir.resolve("com/example/nonsense/nonsense"));
255         TestResult tr = doExec(JAVA_CMD.getAbsolutePath(),
256                                "-cp", "..",
257                                "-Duser.dir=" + testDir.toAbsolutePath(),
258                                "-Djava.security.manager=allow",
259                                "-Djdk.invoke.LambdaMetafactory.dumpProxyClassFiles",
260                                longFQCN);
261         assertEquals(tr.testOutput.stream()


262                                   .filter(s -> s.startsWith("WARNING: Exception"))
263                                   .count(),
264                      2, "show error each capture");
265         // dumpLong/DUMP_LAMBDA_PROXY_CLASS_FILES/com/example/nonsense/nonsense
266         Path dumpPath = dumpDir.resolve("com/example/nonsense");
267         Predicate<Path> filter = p -> p.getParent() == null || dumpPath.startsWith(p) || p.startsWith(dumpPath);
268         boolean debug = true;
269         if (debug) {
270            Files.walk(dumpDir)
271                 .forEachOrdered(p -> {
272                     if (filter.test(p)) {
273                         System.out.println("accepted: " + p.toString());
274                     } else {
275                         System.out.println("filtered out: " + p.toString());
276                     }
277                  });
278         }
279         assertEquals(Files.walk(dumpDir)
280                 .filter(filter)
281                 .count(), 5, "Two lambda captured failed to log");
282         tr.assertZero("Should still return 0");
283     }
284 }

  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 8023524 8304846
 27  * @requires vm.flagless
 28  * @library /test/lib/
 29  * @library /java/nio/file
 30  * @modules jdk.compiler
 31  *          jdk.zipfs
 32  * @run testng LogGeneratedClassesTest
 33  * @summary tests logging generated classes for lambda
 34  */

 35 import java.io.IOException;
 36 import java.nio.charset.Charset;
 37 import java.util.ArrayList;
 38 import java.util.List;
 39 import java.util.function.Predicate;
 40 import java.nio.file.Files;
 41 import java.nio.file.Path;
 42 import java.nio.file.Paths;
 43 import java.nio.file.attribute.PosixFileAttributeView;
 44 
 45 import jdk.test.lib.compiler.CompilerUtils;
 46 import jdk.test.lib.process.OutputAnalyzer;
 47 import org.testng.annotations.AfterClass;
 48 import org.testng.annotations.BeforeClass;
 49 import org.testng.annotations.Test;

 50 
 51 import static java.nio.file.attribute.PosixFilePermissions.*;
 52 import static jdk.test.lib.process.ProcessTools.*;
 53 import static org.testng.Assert.assertEquals;
 54 import static org.testng.Assert.assertFalse;
 55 import static org.testng.Assert.assertTrue;
 56 
 57 public class LogGeneratedClassesTest {
 58     static final Path DUMP_LAMBDA_PROXY_CLASS_FILES = Path.of("DUMP_LAMBDA_PROXY_CLASS_FILES");
 59     static final Path CLASSES = Path.of("classes").toAbsolutePath();
 60     String longFQCN;
 61 
 62     @BeforeClass
 63     public void setup() throws IOException {
 64         final List<String> scratch = new ArrayList<>();
 65         scratch.clear();
 66         scratch.add("package com.example;");
 67         scratch.add("public class TestLambda {");
 68         scratch.add("    interface I {");
 69         scratch.add("        int foo();");
 70         scratch.add("    }");
 71         scratch.add("    public static void main(String[] args) {");
 72         scratch.add("        System.setSecurityManager(new SecurityManager());");
 73         scratch.add("        I lam = () -> 10;");
 74         scratch.add("        Runnable r = () -> {");
 75         scratch.add("            System.out.println(\"Runnable\");");
 76         scratch.add("        };");
 77         scratch.add("        r.run();");
 78         scratch.add("        System.out.println(\"Finish\");");
 79         scratch.add("    }");
 80         scratch.add("}");
 81 
 82         Path testLambda = Path.of("TestLambda.java");
 83         Files.write(testLambda, scratch, Charset.defaultCharset());

 84 
 85         scratch.remove(0);
 86         scratch.remove(0);
 87         scratch.add(0, "public class LongPackageName {");
 88         StringBuilder sb = new StringBuilder("com.example.");
 89         // longer than 255 which exceed max length of most filesystems
 90         for (int i = 0; i < 30; i++) {
 91             sb.append("nonsense.");
 92         }
 93         sb.append("enough");
 94         longFQCN = sb.toString() + ".LongPackageName";
 95         sb.append(";");
 96         sb.insert(0, "package ");
 97         scratch.add(0, sb.toString());
 98         Path lpnTest = Path.of("LongPackageName.java");
 99         Files.write(lpnTest, scratch, Charset.defaultCharset());
100 
101         CompilerUtils.compile(Path.of("."), CLASSES);
102     }
103 
104     @AfterClass
105     public void cleanup() throws IOException {
106         Files.delete(Paths.get("TestLambda.java"));
107         Files.delete(Paths.get("LongPackageName.java"));
108         TestUtil.removeAll(DUMP_LAMBDA_PROXY_CLASS_FILES);
109         TestUtil.removeAll(Paths.get("notDir"));
110         TestUtil.removeAll(Paths.get("dump"));
111         TestUtil.removeAll(Paths.get("dumpLong"));
112     }
113 
114     @Test
115     public void testNotLogging() throws Exception {
116         ProcessBuilder pb = createLimitedTestJavaProcessBuilder(
117                                "-cp", CLASSES.toString(),
118                                "-Djava.security.manager=allow",
119                                "com.example.TestLambda");
120         executeProcess(pb).shouldHaveExitValue(0);
121     }
122 
123     @Test
124     public void testLogging() throws Exception {
125         Path testDir = Path.of("dump");
126         Path dumpDir = testDir.resolve(DUMP_LAMBDA_PROXY_CLASS_FILES);
127         Files.createDirectory(testDir);
128         ProcessBuilder pb = createLimitedTestJavaProcessBuilder(
129                                "-cp", CLASSES.toString(),

130                                "-Djava.security.manager=allow",
131                                "-Djdk.invoke.LambdaMetafactory.dumpProxyClassFiles",
132                                "com.example.TestLambda").directory(testDir.toFile());
133         executeProcess(pb).shouldHaveExitValue(0);
134 
135         // 2 our own class files. We don't care about the others
136         assertEquals(Files.find(
137                         dumpDir,
138                         99,
139                         (p, a) -> p.startsWith(dumpDir.resolve("com/example"))
140                                 && a.isRegularFile()).count(),
141                         2, "Two lambda captured");

142     }
143 
144     @Test
145     public void testDumpDirNotExist() throws Exception {
146         Path testDir = Path.of("NotExist");
147         Path dumpDir = testDir.resolve(DUMP_LAMBDA_PROXY_CLASS_FILES);
148         Files.createDirectory(testDir);
149         TestUtil.removeAll(dumpDir);

150         assertFalse(Files.exists(dumpDir));
151 
152         ProcessBuilder pb = createLimitedTestJavaProcessBuilder(
153                                 "-cp", CLASSES.toString(),
154                                 "-Djava.security.manager=allow",
155                                 "-Djdk.invoke.LambdaMetafactory.dumpProxyClassFiles",
156                                 "com.example.TestLambda").directory(testDir.toFile());
157         executeProcess(pb).shouldHaveExitValue(0);
158 
159         // The dump directory will be created if not exist
160         assertEquals(Files.find(
161                         dumpDir,
162                         99,
163                         (p, a) -> p.startsWith(dumpDir.resolve("com/example"))
164                                 && a.isRegularFile()).count(),
165                         2, "Two lambda captured");

166     }
167 
168     @Test
169     public void testDumpDirIsFile() throws Exception {
170         Path testDir = Path.of("notDir");
171         Path dumpFile = testDir.resolve(DUMP_LAMBDA_PROXY_CLASS_FILES);
172         Files.createDirectory(testDir);
173         Files.createFile(dumpFile);
174         assertTrue(Files.isRegularFile(dumpFile));
175         ProcessBuilder pb = createLimitedTestJavaProcessBuilder(
176                                 "-cp", CLASSES.toString(),
177                                 "-Djava.security.manager=allow",
178                                 "-Djdk.invoke.LambdaMetafactory.dumpProxyClassFiles",
179                                 "com.example.TestLambda").directory(testDir.toFile());
180         executeProcess(pb)
181                 .shouldContain("DUMP_LAMBDA_PROXY_CLASS_FILES is not a directory")
182                 .shouldNotHaveExitValue(0);



183     }
184 
185     private static boolean isWriteableDirectory(Path p) {
186         if (!Files.isDirectory(p)) {
187             return false;
188         }
189         Path test = p.resolve(Paths.get("test"));
190         try {
191             Files.createFile(test);
192             assertTrue(Files.exists(test));
193             return true;
194         } catch (IOException e) {
195             assertFalse(Files.exists(test));
196             return false;
197         } finally {
198             if (Files.exists(test)) {
199                 try {
200                     Files.delete(test);
201                 } catch (IOException e) {
202                     throw new Error(e);
203                 }
204             }
205         }
206     }
207 
208     @Test
209     public void testDumpDirNotWritable() throws Exception {
210         if (!Files.getFileStore(Paths.get("."))
211                   .supportsFileAttributeView(PosixFileAttributeView.class)) {
212             // No easy way to setup readonly directory without POSIX
213             // We would like to skip the test with a cause with
214             //     throw new SkipException("Posix not supported");
215             // but jtreg will report failure so we just pass the test
216             // which we can look at if jtreg changed its behavior
217             System.out.println("WARNING: POSIX is not supported. Skipping testDumpDirNotWritable test.");
218             return;
219         }
220 
221         Path testDir = Path.of("readOnly");
222         Path dumpDir = testDir.resolve(DUMP_LAMBDA_PROXY_CLASS_FILES);
223         Files.createDirectory(testDir);
224         Files.createDirectory(dumpDir,
225                               asFileAttribute(fromString("r-xr-xr-x")));
226         try {
227             if (isWriteableDirectory(dumpDir)) {
228                 // Skipping the test: it's allowed to write into read-only directory
229                 // (e.g. current user is super user).
230                 System.out.println("WARNING: The dump directory is writeable. Skipping testDumpDirNotWritable test.");
231                 return;
232             }
233 
234             ProcessBuilder pb = createLimitedTestJavaProcessBuilder(
235                                    "-cp", CLASSES.toString(),

236                                    "-Djava.security.manager=allow",
237                                    "-Djdk.invoke.LambdaMetafactory.dumpProxyClassFiles",
238                                    "com.example.TestLambda").directory(testDir.toFile());
239             executeProcess(pb)
240                     .shouldContain("DUMP_LAMBDA_PROXY_CLASS_FILES is not writable")
241                     .shouldNotHaveExitValue(0);


242         } finally {
243             TestUtil.removeAll(testDir);
244         }
245     }
246 
247     @Test
248     public void testLoggingException() throws Exception {
249         Path testDir = Path.of("dumpLong");
250         Path dumpDir = testDir.resolve(DUMP_LAMBDA_PROXY_CLASS_FILES);
251         Files.createDirectories(dumpDir.resolve("com/example/nonsense"));
252         Files.createFile(dumpDir.resolve("com/example/nonsense/nonsense"));
253         ProcessBuilder pb = createLimitedTestJavaProcessBuilder(
254                                "-cp", CLASSES.toString(),

255                                "-Djava.security.manager=allow",
256                                "-Djdk.invoke.LambdaMetafactory.dumpProxyClassFiles",
257                                longFQCN).directory(testDir.toFile());
258         OutputAnalyzer outputAnalyzer = executeProcess(pb);
259         outputAnalyzer.shouldHaveExitValue(0);
260         assertEquals(outputAnalyzer.asLines().stream()
261                                   .filter(s -> s.startsWith("WARNING: Exception"))
262                                   .count(),
263                      2, "show error each capture");
264         // dumpLong/DUMP_LAMBDA_PROXY_CLASS_FILES/com/example/nonsense/nonsense
265         Path dumpPath = dumpDir.resolve("com/example/nonsense");
266         Predicate<Path> filter = p -> p.getParent() == null || dumpPath.startsWith(p) || p.startsWith(dumpPath);
267         boolean debug = true;
268         if (debug) {
269            Files.walk(dumpDir)
270                 .forEachOrdered(p -> {
271                     if (filter.test(p)) {
272                         System.out.println("accepted: " + p.toString());
273                     } else {
274                         System.out.println("filtered out: " + p.toString());
275                     }
276                  });
277         }
278         assertEquals(Files.walk(dumpDir)
279                 .filter(filter)
280                 .count(), 5, "Two lambda captured failed to log");

281     }
282 }
< prev index next >