langtools/test/tools/lib/toolbox/JavacTask.java
changeset 36778 e04318f39f92
child 37758 3ecf9b414e05
equal deleted inserted replaced
36777:28d33fb9097f 36778:e04318f39f92
       
     1 /*
       
     2  * Copyright (c) 2013, 2016, 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 package toolbox;
       
    25 
       
    26 import java.io.File;
       
    27 import java.io.IOException;
       
    28 import java.io.PrintWriter;
       
    29 import java.nio.file.Path;
       
    30 import java.nio.file.Paths;
       
    31 import java.util.ArrayList;
       
    32 import java.util.Arrays;
       
    33 import java.util.Collections;
       
    34 import java.util.HashMap;
       
    35 import java.util.List;
       
    36 import java.util.Map;
       
    37 import java.util.stream.Collectors;
       
    38 import java.util.stream.Stream;
       
    39 import javax.tools.JavaCompiler;
       
    40 import javax.tools.JavaFileManager;
       
    41 import javax.tools.JavaFileObject;
       
    42 import javax.tools.StandardJavaFileManager;
       
    43 import javax.tools.StandardLocation;
       
    44 
       
    45 import com.sun.tools.javac.api.JavacTaskImpl;
       
    46 import com.sun.tools.javac.api.JavacTool;
       
    47 
       
    48 /**
       
    49  * A task to configure and run the Java compiler, javac.
       
    50  */
       
    51 public class JavacTask extends AbstractTask<JavacTask> {
       
    52     private boolean includeStandardOptions;
       
    53     private List<Path> classpath;
       
    54     private List<Path> sourcepath;
       
    55     private Path outdir;
       
    56     private List<String> options;
       
    57     private List<String> classes;
       
    58     private List<String> files;
       
    59     private List<JavaFileObject> fileObjects;
       
    60     private JavaFileManager fileManager;
       
    61 
       
    62     private JavaCompiler compiler;
       
    63     private StandardJavaFileManager internalFileManager;
       
    64 
       
    65     /**
       
    66      * Creates a task to execute {@code javac} using API mode.
       
    67      * @param toolBox the {@code ToolBox} to use
       
    68      */
       
    69     public JavacTask(ToolBox toolBox) {
       
    70         super(toolBox, Task.Mode.API);
       
    71     }
       
    72 
       
    73     /**
       
    74      * Creates a task to execute {@code javac} in a specified mode.
       
    75      * @param toolBox the {@code ToolBox} to use
       
    76      * @param mode the mode to be used
       
    77      */
       
    78     public JavacTask(ToolBox toolBox, Task.Mode mode) {
       
    79         super(toolBox, mode);
       
    80     }
       
    81 
       
    82     /**
       
    83      * Sets the classpath.
       
    84      * @param classpath the classpath
       
    85      * @return this task object
       
    86      */
       
    87     public JavacTask classpath(String classpath) {
       
    88         this.classpath = Stream.of(classpath.split(File.pathSeparator))
       
    89                 .filter(s -> !s.isEmpty())
       
    90                 .map(s -> Paths.get(s))
       
    91                 .collect(Collectors.toList());
       
    92         return this;
       
    93     }
       
    94 
       
    95     /**
       
    96      * Sets the classpath.
       
    97      * @param classpath the classpath
       
    98      * @return this task object
       
    99      */
       
   100     public JavacTask classpath(Path... classpath) {
       
   101         this.classpath = Arrays.asList(classpath);
       
   102         return this;
       
   103     }
       
   104 
       
   105     /**
       
   106      * Sets the sourcepath.
       
   107      * @param sourcepath the sourcepath
       
   108      * @return this task object
       
   109      */
       
   110     public JavacTask sourcepath(String sourcepath) {
       
   111         this.sourcepath = Stream.of(sourcepath.split(File.pathSeparator))
       
   112                 .filter(s -> !s.isEmpty())
       
   113                 .map(s -> Paths.get(s))
       
   114                 .collect(Collectors.toList());
       
   115         return this;
       
   116     }
       
   117 
       
   118     /**
       
   119      * Sets the sourcepath.
       
   120      * @param sourcepath the sourcepath
       
   121      * @return this task object
       
   122      */
       
   123     public JavacTask sourcepath(Path... sourcepath) {
       
   124         this.sourcepath = Arrays.asList(sourcepath);
       
   125         return this;
       
   126     }
       
   127 
       
   128     /**
       
   129      * Sets the output directory.
       
   130      * @param outdir the output directory
       
   131      * @return this task object
       
   132      */
       
   133     public JavacTask outdir(String outdir) {
       
   134         this.outdir = Paths.get(outdir);
       
   135         return this;
       
   136     }
       
   137 
       
   138     /**
       
   139      * Sets the output directory.
       
   140      * @param outdir the output directory
       
   141      * @return this task object
       
   142      */
       
   143     public JavacTask outdir(Path outdir) {
       
   144         this.outdir = outdir;
       
   145         return this;
       
   146     }
       
   147 
       
   148     /**
       
   149      * Sets the options.
       
   150      * @param options the options
       
   151      * @return this task object
       
   152      */
       
   153     public JavacTask options(String... options) {
       
   154         this.options = Arrays.asList(options);
       
   155         return this;
       
   156     }
       
   157 
       
   158     /**
       
   159      * Sets the classes to be analyzed.
       
   160      * @param classes the classes
       
   161      * @return this task object
       
   162      */
       
   163     public JavacTask classes(String... classes) {
       
   164         this.classes = Arrays.asList(classes);
       
   165         return this;
       
   166     }
       
   167 
       
   168     /**
       
   169      * Sets the files to be compiled or analyzed.
       
   170      * @param files the files
       
   171      * @return this task object
       
   172      */
       
   173     public JavacTask files(String... files) {
       
   174         this.files = Arrays.asList(files);
       
   175         return this;
       
   176     }
       
   177 
       
   178     /**
       
   179      * Sets the files to be compiled or analyzed.
       
   180      * @param files the files
       
   181      * @return this task object
       
   182      */
       
   183     public JavacTask files(Path... files) {
       
   184         this.files = Stream.of(files)
       
   185                 .map(Path::toString)
       
   186                 .collect(Collectors.toList());
       
   187         return this;
       
   188     }
       
   189 
       
   190     /**
       
   191      * Sets the sources to be compiled or analyzed.
       
   192      * Each source string is converted into an in-memory object that
       
   193      * can be passed directly to the compiler.
       
   194      * @param sources the sources
       
   195      * @return this task object
       
   196      */
       
   197     public JavacTask sources(String... sources) {
       
   198         fileObjects = Stream.of(sources)
       
   199                 .map(s -> new ToolBox.JavaSource(s))
       
   200                 .collect(Collectors.toList());
       
   201         return this;
       
   202     }
       
   203 
       
   204     /**
       
   205      * Sets the file manager to be used by this task.
       
   206      * @param fileManager the file manager
       
   207      * @return this task object
       
   208      */
       
   209     public JavacTask fileManager(JavaFileManager fileManager) {
       
   210         this.fileManager = fileManager;
       
   211         return this;
       
   212     }
       
   213 
       
   214     /**
       
   215      * {@inheritDoc}
       
   216      * @return the name "javac"
       
   217      */
       
   218     @Override
       
   219     public String name() {
       
   220         return "javac";
       
   221     }
       
   222 
       
   223     /**
       
   224      * Calls the compiler with the arguments as currently configured.
       
   225      * @return a Result object indicating the outcome of the compilation
       
   226      * and the content of any output written to stdout, stderr, or the
       
   227      * main stream by the compiler.
       
   228      * @throws TaskError if the outcome of the task is not as expected.
       
   229      */
       
   230     @Override
       
   231     public Task.Result run() {
       
   232         if (mode == Task.Mode.EXEC)
       
   233             return runExec();
       
   234 
       
   235         AbstractTask.WriterOutput direct = new AbstractTask.WriterOutput();
       
   236         // The following are to catch output to System.out and System.err,
       
   237         // in case these are used instead of the primary (main) stream
       
   238         AbstractTask.StreamOutput sysOut = new AbstractTask.StreamOutput(System.out, System::setOut);
       
   239         AbstractTask.StreamOutput sysErr = new AbstractTask.StreamOutput(System.err, System::setErr);
       
   240         int rc;
       
   241         Map<Task.OutputKind, String> outputMap = new HashMap<>();
       
   242         try {
       
   243             switch (mode == null ? Task.Mode.API : mode) {
       
   244                 case API:
       
   245                     rc = runAPI(direct.pw);
       
   246                     break;
       
   247                 case CMDLINE:
       
   248                     rc = runCommand(direct.pw);
       
   249                     break;
       
   250                 default:
       
   251                     throw new IllegalStateException();
       
   252             }
       
   253         } catch (IOException e) {
       
   254             toolBox.out.println("Exception occurred: " + e);
       
   255             rc = 99;
       
   256         } finally {
       
   257             outputMap.put(Task.OutputKind.STDOUT, sysOut.close());
       
   258             outputMap.put(Task.OutputKind.STDERR, sysErr.close());
       
   259             outputMap.put(Task.OutputKind.DIRECT, direct.close());
       
   260         }
       
   261         return checkExit(new Task.Result(toolBox, this, rc, outputMap));
       
   262     }
       
   263 
       
   264     private int runAPI(PrintWriter pw) throws IOException {
       
   265         try {
       
   266 //                if (compiler == null) {
       
   267                 // TODO: allow this to be set externally
       
   268 //                    compiler = ToolProvider.getSystemJavaCompiler();
       
   269                 compiler = JavacTool.create();
       
   270 //                }
       
   271 
       
   272             if (fileManager == null)
       
   273                 fileManager = internalFileManager = compiler.getStandardFileManager(null, null, null);
       
   274             if (outdir != null)
       
   275                 setLocationFromPaths(StandardLocation.CLASS_OUTPUT, Collections.singletonList(outdir));
       
   276             if (classpath != null)
       
   277                 setLocationFromPaths(StandardLocation.CLASS_PATH, classpath);
       
   278             if (sourcepath != null)
       
   279                 setLocationFromPaths(StandardLocation.SOURCE_PATH, sourcepath);
       
   280             List<String> allOpts = new ArrayList<>();
       
   281             if (options != null)
       
   282                 allOpts.addAll(options);
       
   283 
       
   284             Iterable<? extends JavaFileObject> allFiles = joinFiles(files, fileObjects);
       
   285             JavaCompiler.CompilationTask task = compiler.getTask(pw,
       
   286                     fileManager,
       
   287                     null,  // diagnostic listener; should optionally collect diags
       
   288                     allOpts,
       
   289                     classes,
       
   290                     allFiles);
       
   291             return ((JavacTaskImpl) task).doCall().exitCode;
       
   292         } finally {
       
   293             if (internalFileManager != null)
       
   294                 internalFileManager.close();
       
   295         }
       
   296     }
       
   297 
       
   298     private void setLocationFromPaths(StandardLocation location, List<Path> files) throws IOException {
       
   299         if (!(fileManager instanceof StandardJavaFileManager))
       
   300             throw new IllegalStateException("not a StandardJavaFileManager");
       
   301         ((StandardJavaFileManager) fileManager).setLocationFromPaths(location, files);
       
   302     }
       
   303 
       
   304     private int runCommand(PrintWriter pw) {
       
   305         List<String> args = getAllArgs();
       
   306         String[] argsArray = args.toArray(new String[args.size()]);
       
   307         return com.sun.tools.javac.Main.compile(argsArray, pw);
       
   308     }
       
   309 
       
   310     private Task.Result runExec() {
       
   311         List<String> args = new ArrayList<>();
       
   312         Path javac = toolBox.getJDKTool("javac");
       
   313         args.add(javac.toString());
       
   314         if (includeStandardOptions) {
       
   315             args.addAll(toolBox.split(System.getProperty("test.tool.vm.opts"), " +"));
       
   316             args.addAll(toolBox.split(System.getProperty("test.compiler.opts"), " +"));
       
   317         }
       
   318         args.addAll(getAllArgs());
       
   319 
       
   320         String[] argsArray = args.toArray(new String[args.size()]);
       
   321         ProcessBuilder pb = getProcessBuilder();
       
   322         pb.command(argsArray);
       
   323         try {
       
   324             return runProcess(toolBox, this, pb.start());
       
   325         } catch (IOException | InterruptedException e) {
       
   326             throw new Error(e);
       
   327         }
       
   328     }
       
   329 
       
   330     private List<String> getAllArgs() {
       
   331         List<String> args = new ArrayList<>();
       
   332         if (options != null)
       
   333             args.addAll(options);
       
   334         if (outdir != null) {
       
   335             args.add("-d");
       
   336             args.add(outdir.toString());
       
   337         }
       
   338         if (classpath != null) {
       
   339             args.add("-classpath");
       
   340             args.add(toSearchPath(classpath));
       
   341         }
       
   342         if (sourcepath != null) {
       
   343             args.add("-sourcepath");
       
   344             args.add(toSearchPath(sourcepath));
       
   345         }
       
   346         if (classes != null)
       
   347             args.addAll(classes);
       
   348         if (files != null)
       
   349             args.addAll(files);
       
   350 
       
   351         return args;
       
   352     }
       
   353 
       
   354     private String toSearchPath(List<Path> files) {
       
   355         return files.stream()
       
   356             .map(Path::toString)
       
   357             .collect(Collectors.joining(File.pathSeparator));
       
   358     }
       
   359 
       
   360     private Iterable<? extends JavaFileObject> joinFiles(
       
   361             List<String> files, List<JavaFileObject> fileObjects) {
       
   362         if (files == null)
       
   363             return fileObjects;
       
   364         if (internalFileManager == null)
       
   365             internalFileManager = compiler.getStandardFileManager(null, null, null);
       
   366         Iterable<? extends JavaFileObject> filesAsFileObjects =
       
   367                 internalFileManager.getJavaFileObjectsFromStrings(files);
       
   368         if (fileObjects == null)
       
   369             return filesAsFileObjects;
       
   370         List<JavaFileObject> combinedList = new ArrayList<>();
       
   371         for (JavaFileObject o : filesAsFileObjects)
       
   372             combinedList.add(o);
       
   373         combinedList.addAll(fileObjects);
       
   374         return combinedList;
       
   375     }
       
   376 }