Beispiel #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;
  }
  /**
   * 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();
  }
Beispiel #3
0
  public static void main(String... args) throws Throwable {
    String testSrcDir = System.getProperty("test.src");
    String testClassDir = System.getProperty("test.classes");
    String self = T6361619.class.getName();

    JavacTool tool = JavacTool.create();

    final PrintWriter out = new PrintWriter(System.err, true);

    Iterable<String> flags =
        Arrays.asList(
            "-processorpath", testClassDir,
            "-processor", self,
            "-d", ".");
    DiagnosticListener<JavaFileObject> dl =
        new DiagnosticListener<JavaFileObject>() {
          public void report(Diagnostic<? extends JavaFileObject> m) {
            out.println(m);
          }
        };

    StandardJavaFileManager fm = tool.getStandardFileManager(dl, null, null);
    Iterable<? extends JavaFileObject> f =
        fm.getJavaFileObjectsFromFiles(Arrays.asList(new File(testSrcDir, self + ".java")));

    JavacTask task = tool.getTask(out, fm, dl, flags, null, f);
    MyTaskListener tl = new MyTaskListener(task);
    task.setTaskListener(tl);

    // should complete, without exceptions
    task.call();
  }
    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();
    }
  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 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());
   }
 }
Beispiel #7
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());
  }
Beispiel #9
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();
      }
    }
  }
Beispiel #10
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();
  }
  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();
  }
 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();
 }
  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));
    }
  }
Beispiel #14
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;
  }
 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));
 }
 @Override
 public boolean isSameFile(FileObject a, FileObject b) {
   if (a instanceof FileVirtualObject && b instanceof FileVirtualObject
       || a instanceof Output && b instanceof Output) {
     return a.equals(b);
   }
   return myStandardFileManager.isSameFile(a, b);
 }
Beispiel #17
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;
  }
  void run() throws IOException {
    JavacTool tool = (JavacTool) ToolProvider.getSystemJavaCompiler();
    StandardJavaFileManager fm = tool.getStandardFileManager(null, null, null);

    File classes = new File("classes");
    classes.mkdirs();
    File extraClasses = new File("extraClasses");
    extraClasses.mkdirs();

    System.out.println("compiling classes to extraClasses");
    { // setup class in extraClasses
      fm.setLocation(StandardLocation.CLASS_OUTPUT, Collections.singleton(extraClasses));
      List<? extends JavaFileObject> files =
          Arrays.asList(
              new MemFile("AnnoProc.java", annoProc), new MemFile("Callback.java", callback));
      JavacTask task = tool.getTask(null, fm, null, null, null, files);
      check(task.call());
    }

    System.out.println("compiling dummy to classes with anno processor");
    { // use that class in a TaskListener after processing has completed
      PrintStream prev = System.out;
      String out;
      ByteArrayOutputStream baos = new ByteArrayOutputStream();
      try (PrintStream ps = new PrintStream(baos)) {
        System.setOut(ps);
        File testClasses = new File(System.getProperty("test.classes"));
        fm.setLocation(StandardLocation.CLASS_OUTPUT, Collections.singleton(classes));
        fm.setLocation(
            StandardLocation.ANNOTATION_PROCESSOR_PATH, Arrays.asList(extraClasses, testClasses));
        List<? extends JavaFileObject> files =
            Arrays.asList(new MemFile("my://dummy", "class Dummy { }"));
        List<String> options = Arrays.asList("-processor", "AnnoProc");
        JavacTask task = tool.getTask(null, fm, null, options, null, files);
        task.setTaskListener(this);
        check(task.call());
      } finally {
        System.setOut(prev);
        out = baos.toString();
        if (!out.isEmpty()) System.out.println(out);
      }
      check(out.contains("AnnoProc$1: run()"));
      check(out.contains("Callback: run()"));
    }
  }
  /**
   * Returns an empty processor iterator if no processors are on the relevant path, otherwise if
   * processors are present, logs an error. Called when a service loader is unavailable for some
   * reason, either because a service loader class cannot be found or because a security policy
   * prevents class loaders from being created.
   *
   * @param key The resource key to use to log an error message
   * @param e If non-null, pass this exception to Abort
   */
  private Iterator<Processor> handleServiceLoaderUnavailability(String key, Exception e) {
    JavaFileManager fileManager = context.get(JavaFileManager.class);

    if (fileManager instanceof JavacFileManager) {
      StandardJavaFileManager standardFileManager = (JavacFileManager) fileManager;
      Iterable<? extends File> workingPath =
          fileManager.hasLocation(ANNOTATION_PROCESSOR_PATH)
              ? standardFileManager.getLocation(ANNOTATION_PROCESSOR_PATH)
              : standardFileManager.getLocation(CLASS_PATH);

      if (needClassLoader(options.get(PROCESSOR), workingPath)) handleException(key, e);

    } else {
      handleException(key, e);
    }

    java.util.List<Processor> pl = Collections.emptyList();
    return pl.iterator();
  }
  @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);
  }
Beispiel #21
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);
    }
  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());
    }
  }
  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();
    }
  }
Beispiel #24
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");
 }
Beispiel #25
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();
    }
  }
Beispiel #26
0
  public static void main(String[] args) throws Exception {
    // create the source
    File sourceFile = new File("/root/workspace/SensorMiddleware/src/Hello.java");
    FileWriter writer = new FileWriter(sourceFile);

    writer.write(
        "public class Hello{ \n"
            + " public void doit() { \n"
            + "   System.out.println(\"Hello world\") ;\n"
            + " }\n"
            + "}");
    writer.close();

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

    fileManager.setLocation(
        StandardLocation.CLASS_OUTPUT,
        Arrays.asList(new File("/root/workspace/SensorMiddleware/build/classes")));
    // Compile the file
    compiler
        .getTask(
            null,
            fileManager,
            null,
            null,
            null,
            fileManager.getJavaFileObjectsFromFiles(Arrays.asList(sourceFile)))
        .call();
    fileManager.close();

    // delete the source file
    // sourceFile.deleteOnExit();

    runIt();
  }
 public JavaFileObject getJavaFileForInput(Location location, String className, Kind kind)
     throws IOException {
   // System.out.println("getJavaFileForInput(location=" + location + ", className=" + className +
   // ", kind=" + kind + ')');
   if (location == StandardLocation.CLASS_OUTPUT
       && buffers.containsKey(className)
       && kind == Kind.CLASS) {
     final byte[] bytes = buffers.get(className).toByteArray();
     return new SimpleJavaFileObject(URI.create(className), kind) {
       public InputStream openInputStream() {
         return new ByteArrayInputStream(bytes);
       }
     };
   }
   return fileManager.getJavaFileForInput(location, className, kind);
 }
Beispiel #28
0
  public JavaFileObject getJavaFileForOutput(
      Location location, String className, Kind kind, FileObject sibling) throws IOException {
    JavaFileObject object =
        standardJavaFileManager.getJavaFileForOutput(location, className, kind, sibling);

    if (kind == Kind.CLASS) {
      className = className.replace("/", ".");
      String enclosingClassName = className.split("\\$")[0];
      String sourceFileName =
          enclosingClassName.substring(enclosingClassName.lastIndexOf(".") + 1) + ".java";
      Optional<PluginSource> source = result.findSource(sourceFileName);
      Path binaryFile = Paths.get(object.toUri());
      URL binaryURL = binaryFile.toUri().toURL();
      PluginBinary binary = new PluginBinary(binaryURL, source, Optional.of(className));
      result.getBinaries().add(binary);
    }
    return object;
  }
  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");
  }
Beispiel #30
0
  /**
   * @param infce 被代理类的接口
   * @param h 代理类
   * @return
   * @throws Exception
   */
  public static Object newProxyInstance(Class infce, InvocationHandler h) throws Exception {
    String methodStr = "";
    String rt = "\r\n";

    // 利用反射得到infce的所有方法,并重新组装
    Method[] methods = infce.getMethods();
    for (Method m : methods) {
      methodStr +=
          "    @Override"
              + rt
              + "    public  "
              + m.getReturnType()
              + " "
              + m.getName()
              + "() {"
              + rt
              + "        try {"
              + rt
              + "        Method md = "
              + infce.getName()
              + ".class.getMethod(\""
              + m.getName()
              + "\");"
              + rt
              + "        h.invoke(this, md);"
              + rt
              + "        }catch(Exception e) {e.printStackTrace();}"
              + rt
              + "    }"
              + rt;
    }

    // 生成Java源文件
    String srcCode =
        "package proxy;"
            + rt
            + "import java.lang.reflect.Method;"
            + rt
            + "public class $Proxy1 implements "
            + infce.getName()
            + "{"
            + rt
            + "    public $Proxy1(InvocationHandler h) {"
            + rt
            + "        this.h = h;"
            + rt
            + "    }"
            + rt
            + "    InvocationHandler h;"
            + rt
            + methodStr
            + rt
            + "}";
    String fileName = "$Proxy1.java";
    File f = new File(fileName);
    FileWriter fw = new FileWriter(f);
    fw.write(srcCode);
    fw.flush();
    fw.close();

    // 将Java文件编译成class文件
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    StandardJavaFileManager fileMgr = compiler.getStandardFileManager(null, null, null);
    Iterable units = fileMgr.getJavaFileObjects(fileName);
    JavaCompiler.CompilationTask t = compiler.getTask(null, fileMgr, null, null, null, units);
    t.call();
    fileMgr.close();

    // 加载到内存,并实例化
    URL[] urls = new URL[] {new URL("./")};
    URLClassLoader ul = new URLClassLoader(urls);
    Class c = ul.loadClass("$Proxy1");

    Constructor ctr = c.getConstructor(InvocationHandler.class);
    Object m = ctr.newInstance(h);

    return m;
  }