示例#1
0
  /**
   * Compiles the input file and generates the output class file.
   *
   * @param fullFilePath input .java file path.
   * @return class file path.
   */
  public static String compileFile(File fullFilePath) throws IOException {
    Preconditions.checkArgument(fullFilePath != null && fullFilePath.isFile());
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    Preconditions.checkNotNull(compiler);
    DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
    StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, null, null);
    Iterable<? extends JavaFileObject> compilationUnit =
        fileManager.getJavaFileObjectsFromFiles(Arrays.asList(fullFilePath));
    List<String> args = Arrays.asList("-Xlint:none");
    boolean result =
        compiler.getTask(null, fileManager, diagnostics, args, null, compilationUnit).call();

    String msg = "";
    if (!result) {
      for (Diagnostic diagnostic : diagnostics.getDiagnostics()) {
        msg +=
            String.format(
                "Error on line %d in %s%n",
                diagnostic.getLineNumber(), diagnostic.getMessage(null));
      }
      tracer.err(msg);
    }
    fileManager.close();
    return msg;
  }
示例#2
0
  /**
   * @author ZhangXiang
   * @param args 2011-4-7
   * @throws NoSuchMethodException
   * @throws InvocationTargetException
   * @throws SecurityException
   * @throws IllegalArgumentException
   */
  public static void main(String[] args)
      throws IllegalArgumentException, SecurityException, InvocationTargetException,
          NoSuchMethodException {

    StringBuilder classStr = new StringBuilder("package dyclass;public class Foo{");
    classStr.append("public void test(){");
    classStr.append("System.out.println(\"Foo2\");}}");

    JavaCompiler jc = ToolProvider.getSystemJavaCompiler();
    StandardJavaFileManager fileManager = jc.getStandardFileManager(null, null, null);
    Location location = StandardLocation.CLASS_OUTPUT;
    File[] outputs = new File[] {new File("D:/CodeProject/ToxinD/test-export/target/classes")};
    try {
      fileManager.setLocation(location, Arrays.asList(outputs));
    } catch (IOException e) {
      e.printStackTrace();
    }

    JavaFileObject jfo = new JavaSourceFromString("dyclass.Foo", classStr.toString());
    JavaFileObject[] jfos = new JavaFileObject[] {jfo};
    Iterable<? extends JavaFileObject> compilationUnits = Arrays.asList(jfos);
    boolean b = jc.getTask(null, fileManager, null, null, null, compilationUnits).call();
    if (b) { // 如果编译成功
      try {
        Object c = Class.forName("dyclass.Foo").newInstance();
        Class.forName("dyclass.Foo").getMethod("test").invoke(c);
      } catch (InstantiationException e) {
        e.printStackTrace();
      } catch (IllegalAccessException e) {
        e.printStackTrace();
      } catch (ClassNotFoundException e) {
        e.printStackTrace();
      }
    }
  }
示例#3
0
 private JavaFileManager getFileManager() {
   JavaCompiler systemJavaCompiler = ToolProvider.getSystemJavaCompiler();
   if (systemJavaCompiler == null) {
     throw new RuntimeException("JDK needed");
   }
   switch (pluginType) {
     case ECLIPSE_PROJECT:
       this.javaFileManager =
           new EclipseProjectPluginFileManager(
               systemJavaCompiler.getStandardFileManager(null, null, null),
               classLoader,
               new File(location.toString(), "bin"));
       break;
     case INTERNAL:
       this.javaFileManager = systemJavaCompiler.getStandardFileManager(null, null, null);
       break;
     case JAR_FILE:
       this.javaFileManager =
           new VirtualFileManager2(
               systemJavaCompiler.getStandardFileManager(null, null, null),
               classLoader,
               fileSystem,
               rootPath);
       break;
     default:
       break;
   }
   return javaFileManager;
 }
 private URL compileWithJavaCompiler(final File zestFile, final String name) {
   /* Create and set up the compiler: */
   JavaCompiler jc = ToolProvider.getSystemJavaCompiler();
   ClassloadingFileManager manager =
       new ClassloadingFileManager(jc.getStandardFileManager(null, null, null));
   File outputDir = zestFile.getParentFile();
   List<String> options = new ArrayList<String>();
   /*
    * TODO: A possible approach to solve the problems when running as a
    * plug-in would be to provide the complete classpath here, as an option
    * for the compiler. However, I don't see a proper way to get the
    * complete classpath of the running plug-in. It seems to always involve
    * internal API, which would be no real solution (see also the JDT
    * compiler variant and comments there), and in particular would also
    * require Java 6.
    */
   options.add("-d");
   options.add(outputDir.getAbsolutePath());
   /* Compile the generated Zest graph: */
   jc.getTask(null, manager, null, options, null, manager.getJavaFileObjects(zestFile)).call();
   try {
     manager.close();
     /* Return the URL of the folder where the compiled class file is: */
     return outputDir.toURI().toURL();
   } catch (IOException e) {
     e.printStackTrace();
   }
   return null;
 }
  public static void compileTree(JavaCompiler compiler, List<String> options, File targetFolder) {
    StandardJavaFileManager manager =
        compiler.getStandardFileManager(null, Locale.getDefault(), Charset.defaultCharset());

    // create new list containing inputfile
    List<File> files = new ArrayList<File>();
    findFilesUnder(targetFolder, files);
    Iterable<? extends JavaFileObject> units = manager.getJavaFileObjectsFromFiles(files);
    StringWriter stringWriter = new StringWriter();
    PrintWriter printWriter = new PrintWriter(stringWriter);

    options.add("-d");
    options.add(_tmpBinFolderName);
    options.add("-s");
    options.add(_tmpGenFolderName);
    options.add("-cp");
    options.add(
        _tmpSrcFolderName
            + File.pathSeparator
            + _tmpGenFolderName
            + File.pathSeparator
            + _processorJarPath);
    options.add("-processorpath");
    options.add(_processorJarPath);
    options.add("-XprintRounds");
    CompilationTask task = compiler.getTask(printWriter, manager, null, options, null, units);
    Boolean result = task.call();

    if (!result.booleanValue()) {
      String errorOutput = stringWriter.getBuffer().toString();
      System.err.println("Compilation failed: " + errorOutput);
      junit.framework.TestCase.assertTrue("Compilation failed : " + errorOutput, false);
    }
  }
 public static void main(String[] args) throws Exception {
   JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
   System.out.println("" + ToolProvider.getSystemJavaCompiler());
   StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
   StringObject so =
       new StringObject(
           "CalculatorTest",
           "class CalculatorTest {"
               + " public int multiply(int multiplicand, int multiplier) {"
               + " System.out.println(multiplicand);"
               + " System.out.println(multiplier);"
               + " return multiplicand * multiplier;"
               + " }"
               + "}");
   JavaFileObject file = so;
   Iterable files = Arrays.asList(file);
   JavaCompiler.CompilationTask task =
       compiler.getTask(null, fileManager, null, null, null, files);
   Boolean result = task.call();
   System.out.println(result);
   if (result) {
     Class clazz = Class.forName("CalculatorTest");
     Object instance = clazz.newInstance();
     Method m = clazz.getMethod("multiply", new Class[] {int.class, int.class});
     Object[] o = new Object[] {3, 2};
     System.out.println(m.invoke(instance, o));
   }
 }
示例#7
0
  void test(String[] opts, String className) throws Exception {
    count++;
    System.err.println("Test " + count + " " + Arrays.asList(opts) + " " + className);
    Path testSrcDir = Paths.get(System.getProperty("test.src"));
    Path testClassesDir = Paths.get(System.getProperty("test.classes"));
    Path classes = Paths.get("classes." + count);
    classes.createDirectory();

    Context ctx = new Context();
    PathFileManager fm = new JavacPathFileManager(ctx, true, null);
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    List<String> options = new ArrayList<String>();
    options.addAll(Arrays.asList(opts));
    options.addAll(Arrays.asList("-verbose", "-XDverboseCompilePolicy", "-d", classes.toString()));
    Iterable<? extends JavaFileObject> compilationUnits =
        fm.getJavaFileObjects(testSrcDir.resolve(className + ".java"));
    StringWriter sw = new StringWriter();
    PrintWriter out = new PrintWriter(sw);
    JavaCompiler.CompilationTask t =
        compiler.getTask(out, fm, null, options, null, compilationUnits);
    boolean ok = t.call();
    System.err.println(sw.toString());
    if (!ok) {
      throw new Exception("compilation failed");
    }

    File expect = new File("classes." + count + "/" + className + ".class");
    if (!expect.exists()) throw new Exception("expected file not found: " + expect);
    long expectedSize = new File(testClassesDir.toString(), className + ".class").length();
    long actualSize = expect.length();
    if (expectedSize != actualSize)
      throw new Exception("wrong size found: " + actualSize + "; expected: " + expectedSize);
  }
  /**
   * Compile the contents of a directory tree, collecting errors so that they can be compared with
   * expected errors.
   *
   * @param compiler the system compiler or Eclipse compiler
   * @param options will be passed to the compiler
   * @param targetFolder the folder to compile
   * @param errors a StringWriter into which compiler output will be written
   * @return true if the compilation was successful
   */
  public static boolean compileTreeWithErrors(
      JavaCompiler compiler,
      List<String> options,
      File targetFolder,
      DiagnosticListener<? super JavaFileObject> diagnosticListener) {
    StandardJavaFileManager manager =
        compiler.getStandardFileManager(null, Locale.getDefault(), Charset.defaultCharset());

    // create new list containing inputfile
    List<File> files = new ArrayList<File>();
    findFilesUnder(targetFolder, files);
    Iterable<? extends JavaFileObject> units = manager.getJavaFileObjectsFromFiles(files);

    options.add("-d");
    options.add(_tmpBinFolderName);
    options.add("-s");
    options.add(_tmpGenFolderName);
    options.add("-cp");
    options.add(
        _tmpSrcFolderName
            + File.pathSeparator
            + _tmpGenFolderName
            + File.pathSeparator
            + _processorJarPath);
    options.add("-processorpath");
    options.add(_processorJarPath);
    // use writer to prevent System.out/err to be polluted with problems
    StringWriter writer = new StringWriter();
    CompilationTask task =
        compiler.getTask(writer, manager, diagnosticListener, options, null, units);
    Boolean result = task.call();

    return result.booleanValue();
  }
    public static boolean compile(String[] args, File episode) throws Exception {

      JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
      DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
      StandardJavaFileManager fileManager =
          compiler.getStandardFileManager(diagnostics, null, null);
      JavacOptions options = JavacOptions.parse(compiler, fileManager, args);
      List<String> unrecognizedOptions = options.getUnrecognizedOptions();
      if (!unrecognizedOptions.isEmpty())
        Logger.getLogger(SchemaGenerator.class.getName())
            .log(Level.WARNING, "Unrecognized options found: {0}", unrecognizedOptions);
      Iterable<? extends JavaFileObject> compilationUnits =
          fileManager.getJavaFileObjectsFromFiles(options.getFiles());
      JavaCompiler.CompilationTask task =
          compiler.getTask(
              null,
              fileManager,
              diagnostics,
              options.getRecognizedOptions(),
              options.getClassNames(),
              compilationUnits);
      com.sun.tools.internal.jxc.ap.SchemaGenerator r =
          new com.sun.tools.internal.jxc.ap.SchemaGenerator();
      if (episode != null) r.setEpisodeFile(episode);
      task.setProcessors(Collections.singleton(r));
      return task.call();
    }
示例#10
0
  public static void main(String... args) throws IOException {
    class MyFileObject extends SimpleJavaFileObject {
      MyFileObject() {
        super(URI.create("myfo:///Test.java"), SOURCE);
      }

      @Override
      public String getCharContent(boolean ignoreEncodingErrors) {
        //      0         1         2
        //      0123456789012345678901234
        return "class Test { Test() { } }";
      }
    }
    JavaCompiler javac = ToolProvider.getSystemJavaCompiler();
    List<JavaFileObject> compilationUnits =
        Collections.<JavaFileObject>singletonList(new MyFileObject());
    JavacTask task = (JavacTask) javac.getTask(null, null, null, null, null, compilationUnits);
    Trees trees = Trees.instance(task);
    CompilationUnitTree toplevel = task.parse().iterator().next();
    Tree tree = ((ClassTree) toplevel.getTypeDecls().get(0)).getMembers().get(0);
    long pos = trees.getSourcePositions().getStartPosition(toplevel, tree);
    if (pos != 13)
      throw new AssertionError(String.format("Start pos for %s is incorrect (%s)!", tree, pos));
    pos = trees.getSourcePositions().getEndPosition(toplevel, tree);
    if (pos != 23)
      throw new AssertionError(String.format("End pos for %s is incorrect (%s)!", tree, pos));
  }
 public static Map<Lang, Result> convertFromFiles(
     ClassLoader loader, List<Lang> lang, String file, String fqn, String method)
     throws Exception {
   DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<>();
   StandardJavaFileManager manager = javac.getStandardFileManager(diagnostics, locale, charset);
   Iterable<? extends JavaFileObject> fileObjects = manager.getJavaFileObjects(file);
   StringWriter out = new StringWriter();
   JavaCompiler.CompilationTask task =
       javac.getTask(
           out,
           manager,
           diagnostics,
           Collections.<String>emptyList(),
           Collections.<String>emptyList(),
           fileObjects);
   task.setLocale(locale);
   ConvertingProcessor processor = new ConvertingProcessor(lang, fqn, method);
   task.setProcessors(Collections.<Processor>singletonList(processor));
   if (task.call()) {
     return processor.getResults();
   } else {
     StringWriter message = new StringWriter();
     PrintWriter writer = new PrintWriter(message);
     writer.append("Compilation of ").append(file).println(" failed:");
     for (Diagnostic<? extends JavaFileObject> diagnostic : diagnostics.getDiagnostics()) {
       writer.append(diagnostic.getMessage(locale));
     }
     writer.println("console:");
     writer.append(out.getBuffer());
     throw new Exception(message.toString());
   }
 }
示例#12
0
  public static void compileJavaFiles(
      @NotNull Collection<File> files, List<String> options, @Nullable File javaErrorFile)
      throws IOException {
    JavaCompiler javaCompiler = ToolProvider.getSystemJavaCompiler();
    DiagnosticCollector<JavaFileObject> diagnosticCollector =
        new DiagnosticCollector<JavaFileObject>();
    StandardJavaFileManager fileManager =
        javaCompiler.getStandardFileManager(
            diagnosticCollector, Locale.ENGLISH, Charset.forName("utf-8"));
    try {
      Iterable<? extends JavaFileObject> javaFileObjectsFromFiles =
          fileManager.getJavaFileObjectsFromFiles(files);

      JavaCompiler.CompilationTask task =
          javaCompiler.getTask(
              new StringWriter(), // do not write to System.err
              fileManager,
              diagnosticCollector,
              options,
              null,
              javaFileObjectsFromFiles);

      Boolean success = task.call(); // do NOT inline this variable, call() should complete before
      // errorsToString()
      if (javaErrorFile == null || !javaErrorFile.exists()) {
        Assert.assertTrue(errorsToString(diagnosticCollector, true), success);
      } else {
        assertEqualsToFile(javaErrorFile, errorsToString(diagnosticCollector, false));
      }
    } finally {
      fileManager.close();
    }
  }
  private void compile(final File f) throws IOException {
    // set up compiler
    final JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    final DiagnosticCollector<JavaFileObject> diagnostics =
        new DiagnosticCollector<JavaFileObject>();
    final StandardJavaFileManager fileManager =
        compiler.getStandardFileManager(diagnostics, null, null);
    final Iterable<? extends JavaFileObject> compilationUnits =
        fileManager.getJavaFileObjectsFromFiles(Arrays.asList(f));

    // compile generated source
    // (switch off annotation processing: no need to create Log4j2Plugins.dat)
    final List<String> options = Arrays.asList("-proc:none");
    compiler.getTask(null, fileManager, diagnostics, options, null, compilationUnits).call();

    // check we don't have any compilation errors
    final List<String> errors = new ArrayList<String>();
    for (final Diagnostic<? extends JavaFileObject> diagnostic : diagnostics.getDiagnostics()) {
      if (diagnostic.getKind() == Diagnostic.Kind.ERROR) {
        errors.add(
            String.format("Compile error: %s%n", diagnostic.getMessage(Locale.getDefault())));
      }
    }
    fileManager.close();
    assertTrue(errors.toString(), errors.isEmpty());
  }
示例#14
0
  public static void main(String[] args) throws Exception {
    String rt = "\r\n";
    String src =
        "package com.bjsxt.proxy;"
            + rt
            + "public class TankTimeProxy implements Moveable {"
            + rt
            + "    public TankTimeProxy(Moveable t) {"
            + rt
            + "        super();"
            + rt
            + "        this.t = t;"
            + rt
            + "    }"
            + rt
            + "    Moveable t;"
            + rt
            + "    @Override"
            + rt
            + "    public void move() {"
            + rt
            + "        long start = System.currentTimeMillis();"
            + rt
            + "        System.out.println(\"starttime:\" + start);"
            + rt
            + "        t.move();"
            + rt
            + "        long end = System.currentTimeMillis();"
            + rt
            + "        System.out.println(\"time:\" + (end-start));"
            + rt
            + "    }"
            + rt
            + "}";
    String fileName = System.getProperty("user.dir") + "/src/com/bjsxt/proxy/TankTimeProxy.java";
    File f = new File(fileName);
    FileWriter fw = new FileWriter(f);
    fw.write(src);
    fw.flush();
    fw.close();

    // compile
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    StandardJavaFileManager fileMgr = compiler.getStandardFileManager(null, null, null);
    Iterable units = fileMgr.getJavaFileObjects(fileName);
    CompilationTask t = compiler.getTask(null, fileMgr, null, null, null, units);
    t.call();
    fileMgr.close();

    // load into memory and create an instance
    URL[] urls = new URL[] {new URL("file:/" + System.getProperty("user.dir") + "/src")};
    URLClassLoader ul = new URLClassLoader(urls);
    Class c = ul.loadClass("com.bjsxt.proxy.TankTimeProxy");
    System.out.println(c);

    Constructor ctr = c.getConstructor(Moveable.class);
    Moveable m = (Moveable) ctr.newInstance(new Tank());
    m.move();
  }
示例#15
0
 void test() throws Throwable {
   JavaCompiler javac = ToolProvider.getSystemJavaCompiler();
   JavaFileManager jfm = javac.getStandardFileManager(null, null, null);
   JavaCompiler.CompilationTask task =
       javac.getTask(
           null, jfm, new DiagnosticChecker(), null, null, Arrays.asList(new ErroneousSource()));
   task.call();
 }
  public List<Diagnostic<? extends JavaFileObject>> doCompile() {
    List<File> list = new LinkedList<File>();

    //        Set<File> sourceFolders = new HashSet<File>();
    //
    //
    //        for ( String packageName : model.getAllPackageNames() ) {
    //            sourceFolders.add(
    //                    new File( getXjcDir().getPath() + File.separator +
    // packageName.replace(".", File.separator) )
    //            );
    //            sourceFolders.add(
    //                    new File( getJavaDir().getPath() + File.separator +
    // packageName.replace(".", File.separator) )
    //            );
    //        }
    //
    //        for ( File f : sourceFolders ) {
    //            System.out.println( "************** COMPILER USING SRC FOLDERS AS " + f.getPath()
    // );
    //        }
    //
    //        sourceFolders.add(
    //                new File( getXjcDir().getPath() + File.separator +
    // "org.w3._2001.xmlschema".replace(".", File.separator) )
    //        );
    //
    //
    //        for ( File folder : sourceFolders ) {
    //            if ( folder.exists() ) {
    //                list.addAll( Arrays.asList( folder.listFiles( (FilenameFilter) new
    // WildcardFileFilter( "*.java" ) ) ) );
    //            }
    //        }

    explore(getJavaDir(), list);
    explore(getXjcDir(), list);

    //        for ( File f : list ) {
    //            System.out.println( "************** COMPILER USING SRC FILE AS " + f.getPath() );
    //        }

    JavaCompiler jc = ToolProvider.getSystemJavaCompiler();
    DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
    StandardJavaFileManager fileManager = jc.getStandardFileManager(diagnostics, null, null);
    Iterable<? extends JavaFileObject> compilationUnits =
        fileManager.getJavaFileObjectsFromFiles(list);
    List<String> jcOpts = Arrays.asList("-d", getBinDir().getPath());
    JavaCompiler.CompilationTask task =
        jc.getTask(null, fileManager, diagnostics, jcOpts, null, compilationUnits);
    task.call();

    copyMetaInfResources();

    return diagnostics.getDiagnostics();
  }
示例#17
0
 void compileAndCheck(
     VarargsMethod m1, VarargsMethod m2, TypeKind actual, ArgumentsArity argsArity)
     throws Exception {
   final JavaCompiler tool = ToolProvider.getSystemJavaCompiler();
   JavaSource source = new JavaSource(m1, m2, actual, argsArity);
   ErrorChecker ec = new ErrorChecker();
   JavacTask ct = (JavacTask) tool.getTask(null, fm, ec, null, null, Arrays.asList(source));
   ct.generate();
   check(source, ec, m1, m2, actual, argsArity);
 }
 private boolean compile(String path) throws Exception {
   JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
   DiagnosticCollector<JavaFileObject> diags = new DiagnosticCollector<JavaFileObject>();
   StandardJavaFileManager fm = compiler.getStandardFileManager(diags, null, null);
   JavaCompiler.CompilationTask task =
       compiler.getTask(
           null, fm, null, null, null, fm.getJavaFileObjects(new File(res(path).toURI())));
   task.setProcessors(Arrays.asList(new AnnotationProcessor()));
   return task.call();
 }
示例#19
0
 @Override
 public void run() {
   int id = checkCount.incrementAndGet();
   final JavaCompiler tool = ToolProvider.getSystemJavaCompiler();
   JavaSource source = new JavaSource(id);
   JavacTask ct =
       (JavacTask) tool.getTask(null, fm.get(), null, null, null, Arrays.asList(source));
   ct.call();
   verifyBytecode(source, id);
 }
示例#20
0
  public static void main(String... args) throws IOException {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();

    try (StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null)) {
      JavacTask task =
          (JavacTask)
              compiler.getTask(
                  null, fileManager, null, null, null, fileManager.getJavaFileObjects(args));

      task.parse().forEach(cu -> cu.accept(new SampleVisitor(), null));
    }
  }
示例#21
0
 /**
  * 编译给定文件绝对路径的java文件列表
  *
  * @param srcFiles
  * @throws Exception
  */
 private void compile(String[] srcFiles) throws Exception {
   String args[] = this.buildCompileJavacArgs(srcFiles);
   ByteArrayOutputStream err = new ByteArrayOutputStream();
   JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
   if (compiler == null) {
     throw new NullPointerException(
         "ToolProvider.getSystemJavaCompiler() return null,please use JDK replace JRE!");
   }
   int resultCode = compiler.run(null, null, err, args);
   if (resultCode != 0) {
     throw new Exception(err.toString());
   }
 }
示例#22
0
  public static boolean compileFiles(List<String> sourceFiles) throws IOException {

    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();

    StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
    Iterable<? extends JavaFileObject> compilationUnits =
        fileManager.getJavaFileObjectsFromStrings(sourceFiles);
    JavaCompiler.CompilationTask task =
        compiler.getTask(null, fileManager, null, null, null, compilationUnits);
    boolean success = task.call();
    fileManager.close();

    return success;
  }
 @Override
 protected void setUp() {
   javac = ToolProvider.getSystemJavaCompiler();
   diagnosticCollector = new DiagnosticCollector<JavaFileObject>();
   fileManager = javac.getStandardFileManager(diagnosticCollector, null, null);
   tmpDir = Files.createTempDir();
 }
 private JavaCompiler.CompilationTask makeCompilationTask(String... files) throws IOException {
   JavaCompiler compiler = BazelJavaCompiler.newInstance();
   StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
   fileManager.setLocation(
       StandardLocation.CLASS_PATH,
       Arrays.asList(new File("third_party/ijar/test/interface_ijar_testlib.jar")));
   fileManager.setLocation(StandardLocation.CLASS_OUTPUT, Arrays.asList(getTmpDir()));
   diagnostics = new DiagnosticCollector<JavaFileObject>();
   return compiler.getTask(
       null,
       fileManager,
       diagnostics,
       Arrays.asList("-Xlint:deprecation"), // used for deprecation tests
       null,
       fileManager.getJavaFileObjects(files));
 }
示例#25
0
 public Compiler(Flags... flags) {
   setFlags(flags);
   this.tempDirs = new ArrayList<>();
   this.postprocessors = new ArrayList<>();
   this.systemJavaCompiler = ToolProvider.getSystemJavaCompiler();
   this.fm = systemJavaCompiler.getStandardFileManager(null, null, null);
 }
示例#26
0
  void test(List<String> opts, Main.Result expectResult, Set<Message> expectMessages) {
    System.err.println("test: " + opts);
    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);
    List<JavaFileObject> files = Arrays.asList(file);
    try {
      JavacTask t = (JavacTask) javac.getTask(pw, fm, null, opts, null, files);
      boolean ok = t.call();
      pw.close();
      String out = sw.toString().replaceAll("[\r\n]+", "\n");
      if (!out.isEmpty()) System.err.println(out);
      if (ok && expectResult != Main.Result.OK) {
        error("Compilation succeeded unexpectedly");
      } else if (!ok && expectResult != Main.Result.ERROR) {
        error("Compilation failed unexpectedly");
      } else check(out, expectMessages);
    } catch (IllegalArgumentException e) {
      System.err.println(e);
      String expectOut = expectMessages.iterator().next().text;
      if (expectResult != Main.Result.CMDERR) error("unexpected exception caught");
      else if (!e.getMessage().equals(expectOut)) {
        error("unexpected exception message: " + e.getMessage() + " expected: " + expectOut);
      }
    }

    //        if (errors > 0)
    //            throw new Error("stop");
  }
示例#27
0
  public TestInput(
      Iterable<? extends JavaFileObject> files, Iterable<String> processors, String[] options) {

    this.compiler = ToolProvider.getSystemJavaCompiler();
    this.fileManager = compiler.getStandardFileManager(null, null, null);

    this.files = files;
    this.processors = processors;
    this.options = new LinkedList<String>();

    String classpath = System.getProperty("tests.classpath", "tests" + File.separator + "build");
    String globalclasspath = System.getProperty("java.class.path", "");

    this.options.add("-Xmaxerrs");
    this.options.add("9999");
    this.options.add("-g");
    this.options.add("-d");
    this.options.add(OUTDIR);
    this.options.add("-classpath");
    this.options.add(
        "build"
            + File.pathSeparator
            + "junit.jar"
            + File.pathSeparator
            + classpath
            + File.pathSeparator
            + globalclasspath);
    this.options.addAll(Arrays.asList(options));
  }
示例#28
0
 public ContextImpl(
     @NotNull JavaCompiler compiler,
     @NotNull DiagnosticOutputConsumer outConsumer,
     @NotNull OutputFileConsumer sink,
     CanceledStatus canceledStatus,
     boolean canUseOptimizedmanager) {
   myOutConsumer = outConsumer;
   myOutputFileSink = sink;
   myCanceledStatus = canceledStatus;
   StandardJavaFileManager stdManager = null;
   if (canUseOptimizedmanager) {
     final Class<StandardJavaFileManager> optimizedManagerClass =
         ClasspathBootstrap.getOptimizedFileManagerClass();
     if (optimizedManagerClass != null) {
       try {
         stdManager = optimizedManagerClass.newInstance();
       } catch (Throwable e) {
         if (SystemInfo.isWindows) {
           System.err.println(
               "Failed to load JPS optimized file manager for javac: " + e.getMessage());
         }
       }
     }
   }
   if (stdManager != null) {
     myStdManager = stdManager;
   } else {
     myStdManager = compiler.getStandardFileManager(outConsumer, Locale.US, null);
   }
 }
示例#29
0
  /**
   * Compiles the source code using the systems java compiler
   *
   * @param source
   * @return true -> compiling worked flawlessly
   */
  private static String compile(JavaFileObject... source) {
    final ArrayList<String> options = new ArrayList<String>();
    if (classpath != null) {
      options.add("-classpath");
      options.add(System.getProperty("java.class.path") + classpath);
    }
    if (outputdir != null) {
      options.add("-d");
      options.add(outputdir);
    }

    DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();

    /**
     * Retrieving the standard file manager from compiler object, which is used to provide basic
     * building block for customizing how a compiler reads and writes to files.
     *
     * <p>The same file manager can be reopened for another compiler task. Thus we reduce the
     * overhead of scanning through file system and jar files each time
     */
    StandardJavaFileManager stdFileManager =
        compiler.getStandardFileManager(null, Locale.getDefault(), null);

    final JavaCompiler.CompilationTask task =
        compiler.getTask(null, stdFileManager, diagnostics, options, null, Arrays.asList(source));
    boolean result = task.call();
    String error = null;

    if (!result) {
      error = "Compilation failed, see log for details";
      for (@SuppressWarnings("rawtypes") Diagnostic diagnostic : diagnostics.getDiagnostics()) {
        Logger.getInstance()
            .log(
                "de.~.vm.Javac.compile(JavaFileObject...)",
                Logger.DEBUG,
                "Error on line %d in %s" + diagnostic.getLineNumber() + diagnostic);
      }
    }
    try {
      stdFileManager.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
    return error;
  }
  @NotNull
  public static NamespaceDescriptor compileJava(
      @NotNull Collection<File> javaFiles, File tmpdir, Disposable disposable) throws IOException {
    JavaCompiler javaCompiler = ToolProvider.getSystemJavaCompiler();

    StandardJavaFileManager fileManager =
        javaCompiler.getStandardFileManager(null, Locale.ENGLISH, Charset.forName("utf-8"));
    try {
      Iterable<? extends JavaFileObject> javaFileObjectsFromFiles =
          fileManager.getJavaFileObjectsFromFiles(javaFiles);
      List<String> options =
          Arrays.asList(
              "-classpath",
              "out/production/runtime"
                  + File.pathSeparator
                  + JetTestUtils.getAnnotationsJar().getPath(),
              "-d",
              tmpdir.getPath());
      JavaCompiler.CompilationTask task =
          javaCompiler.getTask(null, fileManager, null, options, null, javaFileObjectsFromFiles);

      Assert.assertTrue(task.call());
    } finally {
      fileManager.close();
    }

    JetCoreEnvironment jetCoreEnvironment =
        new JetCoreEnvironment(
            disposable,
            CompileCompilerDependenciesTest.compilerConfigurationForTests(
                ConfigurationKind.JDK_ONLY,
                TestJdkKind.MOCK_JDK,
                JetTestUtils.getAnnotationsJar(),
                tmpdir,
                new File("out/production/runtime")));

    InjectorForJavaSemanticServices injector =
        new InjectorForJavaSemanticServices(
            BuiltinsScopeExtensionMode.ALL, jetCoreEnvironment.getProject());
    JavaDescriptorResolver javaDescriptorResolver = injector.getJavaDescriptorResolver();
    return javaDescriptorResolver.resolveNamespace(
        FqName.topLevel(Name.identifier("test")), DescriptorSearchRule.ERROR_IF_FOUND_IN_KOTLIN);
  }