1  /*
   2  * Copyright (c) 2011, 2018, 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 8004182 8028545
  27  * @summary Add support for profiles in javac
  28  * @modules java.desktop
  29  *          java.sql.rowset
  30  *          jdk.compiler/com.sun.tools.javac.api
  31  *          jdk.compiler/com.sun.tools.javac.jvm
  32  *          jdk.security.auth
  33  */
  34 
  35 import java.io.PrintWriter;
  36 import java.io.StringWriter;
  37 import java.lang.annotation.Annotation;
  38 import java.lang.annotation.Retention;
  39 import java.lang.annotation.RetentionPolicy;
  40 import java.lang.reflect.InvocationTargetException;
  41 import java.lang.reflect.Method;
  42 import java.net.URI;
  43 import java.util.ArrayList;
  44 import java.util.Arrays;
  45 import java.util.Collections;
  46 import java.util.EnumMap;
  47 import java.util.List;
  48 import java.util.Map;
  49 
  50 import javax.tools.Diagnostic;
  51 import javax.tools.DiagnosticCollector;
  52 import javax.tools.JavaCompiler;
  53 import javax.tools.JavaFileObject;
  54 import javax.tools.SimpleJavaFileObject;
  55 import javax.tools.StandardJavaFileManager;
  56 
  57 import com.sun.source.util.JavacTask;
  58 import com.sun.tools.javac.api.JavacTool;
  59 import com.sun.tools.javac.jvm.Profile;
  60 import com.sun.tools.javac.jvm.Target;
  61 
  62 
  63 public class ProfileOptionTest {
  64     public static void main(String... args) throws Exception {
  65         new ProfileOptionTest().run();
  66     }
  67 
  68     private final JavaCompiler javac = JavacTool.create();
  69     private final StandardJavaFileManager fm = javac.getStandardFileManager(null, null, null);
  70 
  71 
  72     // ---------- Test cases, invoked reflectively via run. ----------
  73 
  74     @Test
  75     void testInvalidProfile_API() throws Exception {
  76         JavaFileObject fo = new StringJavaFileObject("Test.java", "class Test { }");
  77         String badName = "foo";
  78         List<String> opts = Arrays.asList("--release", "8", "-profile", badName);
  79         StringWriter sw = new StringWriter();
  80         try {
  81             JavacTask task = (JavacTask) javac.getTask(sw, fm, null, opts, null,
  82                 Arrays.asList(fo));
  83             throw new Exception("expected exception not thrown");
  84         } catch (IllegalArgumentException e) {
  85             // expected
  86         }
  87     }
  88 
  89     @Test
  90     void testInvalidProfile_CommandLine() throws Exception {
  91         String badName = "foo";
  92         String[] opts = { "--release", "8", "-profile", badName };
  93         StringWriter sw = new StringWriter();
  94         PrintWriter pw = new PrintWriter(sw);
  95         int rc = com.sun.tools.javac.Main.compile(opts, pw);
  96 
  97         // sadly, command line errors are not (yet?) reported to
  98         // the diag listener
  99         String out = sw.toString();
 100         if (!out.isEmpty())
 101             System.err.println(out.trim());
 102 
 103         if (!out.contains("invalid profile: " + badName)) {
 104             error("expected message not found");
 105         }
 106     }
 107 
 108     @Test
 109     void testTargetProfileCombinations() throws Exception {
 110         JavaFileObject fo = new StringJavaFileObject("Test.java", "class Test { }");
 111         for (Target t: Target.values()) {
 112             switch (t) {
 113                 case JDK1_1:
 114                 case JDK1_2:
 115                 case JDK1_3:
 116                 case JDK1_4:
 117                 case JDK1_5: // not supported
 118                     continue;
 119             }
 120 
 121             for (Profile p: Profile.values()) {
 122                 List<String> opts = new ArrayList<>();
 123                 opts.addAll(Arrays.asList("-source", t.name, "-target", t.name));
 124                 opts.add("-Xlint:-options"); // don't warn about no -bootclasspath
 125                 if (p != Profile.DEFAULT)
 126                     opts.addAll(Arrays.asList("-profile", p.name));
 127 
 128                 IllegalStateException ise;
 129                 StringWriter sw = new StringWriter();
 130                 try {
 131                     JavacTask task = (JavacTask) javac.getTask(sw, fm, null, opts, null,
 132                             Arrays.asList(fo));
 133                     task.analyze();
 134                     ise = null;
 135                 } catch (IllegalStateException e) {
 136                     ise = e;
 137                 }
 138 
 139                 // sadly, command line errors are not (yet?) reported to
 140                 // the diag listener
 141                 String out = sw.toString();
 142                 if (!out.isEmpty())
 143                     System.err.println(out.trim());
 144 
 145                 switch (t) {
 146                     case JDK1_8:
 147                         if (ise != null)
 148                             error("unexpected exception from compiler: " + ise);
 149                         break;
 150                     case JDK1_9:
 151                     case JDK1_10:
 152                     case JDK1_11:
 153                     case JDK1_12:
 154                     case JDK1_13:
 155                         if (p == Profile.DEFAULT)
 156                             break;
 157                         if (ise == null)
 158                             error("IllegalStateException not thrown as expected");
 159                         else if (!ise.getMessage().contains("option -profile " +
 160                                 "not allowed with target " + t.name)) {
 161                             error("exception not thrown as expected: " + ise);
 162                         }
 163                         break;
 164                     default:
 165                         if (p == Profile.DEFAULT)
 166                             break;
 167                         if (ise == null)
 168                             error("IllegalStateException not thrown as expected");
 169                         else if (!ise.getMessage().contains("profile " + p.name
 170                                     + " is not valid for target release " + t.name)) {
 171                             error("exception not thrown as expected: " + ise);
 172                         }
 173                         break;
 174                 }
 175             }
 176         }
 177     }
 178 
 179     @Test
 180     void testClassesInProfiles() throws Exception {
 181         for (Profile p: Profile.values()) {
 182             for (Map.Entry<Profile, List<JavaFileObject>> e: testClasses.entrySet()) {
 183                 for (JavaFileObject fo: e.getValue()) {
 184                     DiagnosticCollector<JavaFileObject> dl =
 185                             new DiagnosticCollector<JavaFileObject>();
 186                     List<String> opts = (p == Profile.DEFAULT)
 187                             ? Collections.<String>emptyList()
 188                             : Arrays.asList("--release", "8", "-profile", p.name);
 189                     JavacTask task = (JavacTask) javac.getTask(null, fm, dl, opts, null,
 190                             Arrays.asList(fo));
 191                     task.analyze();
 192 
 193                     List<String> expectDiagCodes = new ArrayList<>();
 194                     if (fo.getName().equals("TPolicyFile.java")) {
 195                         expectDiagCodes.add("compiler.warn.has.been.deprecated.for.removal");
 196                     }
 197 
 198                     if (p.value < e.getKey().value) {
 199                         expectDiagCodes.add("compiler.err.not.in.profile");
 200                     }
 201 
 202                     checkDiags(opts + " " + fo.getName(), dl.getDiagnostics(), expectDiagCodes);
 203                 }
 204             }
 205         }
 206     }
 207 
 208     Map<Profile, List<JavaFileObject>> testClasses =
 209             new EnumMap<Profile, List<JavaFileObject>>(Profile.class);
 210 
 211     void initTestClasses() {
 212         // The following table assumes the existence of specific classes
 213         // in specific profiles, as defined in the Java SE 8 spec.
 214         init(Profile.COMPACT1,
 215                 java.lang.String.class);
 216 
 217         init(Profile.COMPACT2,
 218                 javax.xml.XMLConstants.class);
 219 
 220         //init(Profile.COMPACT3,
 221         //        javax.sql.rowset.Predicate.class,
 222         //        com.sun.security.auth.PolicyFile.class); // specifically included in 3
 223 
 224         init(Profile.COMPACT3,
 225                 javax.sql.rowset.Predicate.class);
 226 
 227         init(Profile.DEFAULT,
 228                 java.beans.BeanInfo.class);
 229     }
 230 
 231     void init(Profile p, Class<?>... classes) {
 232         List<JavaFileObject> srcs = new ArrayList<JavaFileObject>();
 233         for (Class<?> c: classes) {
 234             String name = "T" + c.getSimpleName();
 235             String src =
 236                     "class T" + name + "{" + "\n" +
 237                     "    Class<?> c = " + c.getName() + ".class;\n" +
 238                     "}";
 239             srcs.add(new StringJavaFileObject(name + ".java", src));
 240         }
 241         testClasses.put(p, srcs);
 242     }
 243 
 244     void checkDiags(String msg, List<Diagnostic<? extends JavaFileObject>> diags, List<String> expectDiagCodes) {
 245         System.err.print(msg);
 246         if (diags.isEmpty())
 247             System.err.println(" OK");
 248         else {
 249             System.err.println();
 250             System.err.println(diags);
 251         }
 252 
 253         List<String> foundDiagCodes = new ArrayList<String>();
 254         for (Diagnostic<? extends JavaFileObject> d: diags)
 255             foundDiagCodes.add(d.getCode());
 256 
 257         if (!foundDiagCodes.equals(expectDiagCodes)) {
 258             System.err.println("Found diag codes:    " + foundDiagCodes);
 259             System.err.println("Expected diag codes: " + expectDiagCodes);
 260             error("expected diagnostics not found");
 261         }
 262     }
 263 
 264     /** Marker annotation for test cases. */
 265     @Retention(RetentionPolicy.RUNTIME)
 266     @interface Test { }
 267 
 268     /** Run all test cases. */
 269     void run() throws Exception {
 270         try {
 271             initTestClasses();
 272 
 273             for (Method m: getClass().getDeclaredMethods()) {
 274                 Annotation a = m.getAnnotation(Test.class);
 275                 if (a != null) {
 276                     System.err.println(m.getName());
 277                     try {
 278                         m.invoke(this, new Object[] { });
 279                     } catch (InvocationTargetException e) {
 280                         Throwable cause = e.getCause();
 281                         throw (cause instanceof Exception) ? ((Exception) cause) : e;
 282                     }
 283                     System.err.println();
 284                 }
 285             }
 286 
 287             if (errors > 0)
 288                 throw new Exception(errors + " errors occurred");
 289         } finally {
 290             fm.close();
 291         }
 292     }
 293 
 294     void error(String msg) {
 295         System.err.println("Error: " + msg);
 296         errors++;
 297     }
 298 
 299     int errors;
 300 
 301     private static class StringJavaFileObject extends SimpleJavaFileObject {
 302         StringJavaFileObject(String name, String text) {
 303             super(URI.create(name), JavaFileObject.Kind.SOURCE);
 304             this.text = text;
 305         }
 306         @Override
 307         public CharSequence getCharContent(boolean b) {
 308             return text;
 309         }
 310         private String text;
 311     }
 312 }