Ejemplo n.º 1
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;
 }
Ejemplo n.º 2
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());
  }
Ejemplo n.º 4
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));
  }
Ejemplo n.º 5
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;
  }
 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());
   }
 }
Ejemplo n.º 7
0
 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));
   }
 }
Ejemplo n.º 8
0
 @Override
 protected void setUp() {
   javac = ToolProvider.getSystemJavaCompiler();
   diagnosticCollector = new DiagnosticCollector<JavaFileObject>();
   fileManager = javac.getStandardFileManager(diagnosticCollector, null, null);
   tmpDir = Files.createTempDir();
 }
Ejemplo n.º 9
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);
   }
 }
Ejemplo n.º 10
0
  /**
   * 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();
  }
Ejemplo n.º 11
0
  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);
    }
  }
 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;
 }
Ejemplo n.º 13
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();
      }
    }
  }
    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();
    }
Ejemplo n.º 15
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);
 }
Ejemplo n.º 16
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();
  }
Ejemplo n.º 17
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();
  }
Ejemplo n.º 19
0
 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();
 }
Ejemplo n.º 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));
    }
  }
Ejemplo n.º 21
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;
  }
Ejemplo n.º 22
0
 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));
 }
Ejemplo n.º 23
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;
  }
Ejemplo n.º 24
0
  void run() throws Exception {
    javac = ToolProvider.getSystemJavaCompiler();
    fm = javac.getStandardFileManager(null, null, null);
    fm.setLocation(StandardLocation.CLASS_OUTPUT, Arrays.asList(new File(".")));
    file =
        new SimpleJavaFileObject(URI.create("Test.java"), JavaFileObject.Kind.SOURCE) {
          @Override
          public CharSequence getCharContent(boolean ignoreEncoding) {
            return code;
          }
        };

    test(Collections.<String>emptyList(), Main.Result.OK, EnumSet.noneOf(Message.class));

    test(Arrays.asList("-Xdoclint:none"), Main.Result.OK, EnumSet.noneOf(Message.class));

    test(
        Arrays.asList(rawDiags, "-Xdoclint"),
        Main.Result.ERROR,
        EnumSet.of(Message.DL_ERR6, Message.DL_ERR9, Message.DL_WRN12));

    test(
        Arrays.asList(rawDiags, "-Xdoclint:all/public"),
        Main.Result.OK,
        EnumSet.of(Message.DL_WRN12));

    test(
        Arrays.asList(rawDiags, "-Xdoclint:syntax"),
        Main.Result.ERROR,
        EnumSet.of(Message.DL_ERR6, Message.DL_WRN12));

    test(
        Arrays.asList(rawDiags, "-Xdoclint:reference"),
        Main.Result.ERROR,
        EnumSet.of(Message.DL_ERR9));

    test(
        Arrays.asList(rawDiags, "-Xdoclint:badarg"),
        Main.Result.CMDERR,
        EnumSet.of(Message.OPT_BADARG));

    if (errors > 0) throw new Exception(errors + " errors occurred");
  }
Ejemplo n.º 25
0
  @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);
  }
Ejemplo n.º 26
0
    @Override
    public Class<?> compile(URLClassLoader loader, String name, String src) throws Exception {
      log.info("External compiler");
      File classDir = new File(System.getProperty("oms.prj") + File.separatorChar + "dist");
      File srcDir = new File(System.getProperty("java.io.tmpdir"));

      File javaFile = new File(srcDir, name + ".java");
      write(javaFile, src);

      StandardJavaFileManager fm = jc.getStandardFileManager(null, null, null);

      Iterable fileObjects = fm.getJavaFileObjects(javaFile);
      String[] options = new String[] {"-d", classDir.toString()};
      jc.getTask(null, null, null, Arrays.asList(options), null, fileObjects).call();

      fm.close();

      return loader.loadClass(name);
    }
Ejemplo n.º 27
0
  private void compile() {
    try {
      console.setText("Compiling...");
      console.update(console.getGraphics());

      File compileDir = new File(".");
      // Util.saveToFile(codeEditor.getText(), "./CustomProtocol.java");
      Util.saveToFile(codeEditor.getText(), "./" + this.protocolClass + ".java"); // by urueda

      JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
      if (compiler == null) {
        throw new RuntimeException("JDK required (running inside of JRE)");
      }

      DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
      StandardJavaFileManager fileManager =
          compiler.getStandardFileManager(diagnostics, null, null);
      try {
        Iterable<? extends JavaFileObject> compilationUnits =
            fileManager.getJavaFileObjectsFromFiles(Util.getAllFiles(compileDir, ".java"));
        ArrayList<String> options = new ArrayList<String>();
        // options.add("-classpath \"" + System.getProperty("java.class.path") + "\\\"");
        options.add("-classpath");
        options.add(System.getProperty("java.class.path") + ";./monkey.jar");
        //                for(String cp : System.getProperty("java.class.path").split(";")){
        //                    if(new File(cp).isDirectory())
        //                        cp = cp + "\\";
        //                    options.add(cp);
        //                }
        JavaCompiler.CompilationTask task =
            compiler.getTask(null, fileManager, diagnostics, options, null, compilationUnits);
        if (!task.call()) {
          throw new RuntimeException("compile errors" + diagnostics.getDiagnostics().toString());
        }
      } finally {
        fileManager.close();
      }
      console.setText(console.getText() + "OK");
    } catch (Throwable t) {
      console.setText(console.getText() + "\n" + t.getMessage());
    }
  }
Ejemplo n.º 28
0
  private static void compileAbilities(File javaDir, File classDir) {
    if (!javaDir.exists()) return;

    // Make ready a new list of files to compile.
    List<File> toCompile = getSourceFilesToCompile(javaDir, classDir);

    // No files to compile?
    if (toCompile.isEmpty()) {
      return;
    }

    // Notify the console.
    Messenger.info("Compiling abilities: " + fileListToString(toCompile));

    // Get the compiler
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);

    // Generate some JavaFileObjects
    try {
      Iterable<? extends JavaFileObject> compilationUnits =
          fileManager.getJavaFileObjectsFromFiles(toCompile);

      // Include the MobArena.jar on the classpath, and set the destination folder.
      List<String> options = Arrays.asList("-classpath", classpath, "-d", classDir.getPath());

      // Set up the compilation task.
      JavaCompiler.CompilationTask task =
          compiler.getTask(null, fileManager, null, options, null, compilationUnits);

      // Call the task.
      task.call();

      // And close the file manager.
      fileManager.close();
    } catch (Exception e) {
      Messenger.severe("Compilation step failed...");
      e.printStackTrace();
    }
  }
Ejemplo n.º 29
0
 public static void main(String... args) {
   try {
     JavaCompiler javac = javax.tools.ToolProvider.getSystemJavaCompiler();
     DiagnosticListener<JavaFileObject> dl =
         new DiagnosticListener<JavaFileObject>() {
           public void report(Diagnostic<? extends JavaFileObject> message) {
             throw new NullPointerException(SILLY_BILLY);
           }
         };
     StandardJavaFileManager fm = javac.getStandardFileManager(dl, null, null);
     Iterable<? extends JavaFileObject> files =
         fm.getJavaFileObjectsFromStrings(Arrays.asList("badfile.java"));
     javac.getTask(null, fm, dl, null, null, files).call();
   } catch (RuntimeException e) {
     Throwable cause = e.getCause();
     if (cause instanceof NullPointerException && cause.getMessage().equals(SILLY_BILLY)) return;
     throw new Error("unexpected exception caught: " + e);
   } catch (Throwable t) {
     throw new Error("unexpected exception caught: " + t);
   }
   throw new Error("no exception caught");
 }
Ejemplo n.º 30
0
  public static void main(String[] args) {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
    // 生成java文件
    generateJavaClass();
    try {
      // 设置编译路径和文件输出路径
      String cp = ReportConstants.CONTEXT_REAL_PATH + "/classes/";
      List<String> list = new ArrayList<String>();
      list.add("-d");
      list.add(cp);
      list.add("-cp");
      list.add(cp);

      Iterable sourcefiles = fileManager.getJavaFileObjects(JAVA_SOURCE_FILE);
      compiler.getTask(null, fileManager, null, list, null, sourcefiles).call();
      fileManager.close();
      // 创建动态编译得到的DynamicObject类的实例
      Class.forName(JAVA_CLASS_NAME).newInstance();
    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }