Beispiel #1
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 #3
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;
  }
Beispiel #4
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 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;
  }
Beispiel #6
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);
  }
Beispiel #8
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 #11
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 #12
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();
  }
Beispiel #13
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;
  }
Beispiel #14
0
  /**
   * Wow! much faster than compiling outside of VM. Finicky though. Had rules called r and modulo.
   * Wouldn't compile til I changed to 'a'.
   */
  protected boolean compile(String fileName) {
    String classpathOption = "-classpath";

    String[] args =
        new String[] {
          "javac",
          "-d",
          tmpdir,
          classpathOption,
          tmpdir + pathSep + CLASSPATH,
          tmpdir + "/" + fileName
        };
    String cmdLine =
        "javac"
            + " -d "
            + tmpdir
            + " "
            + classpathOption
            + " "
            + tmpdir
            + pathSep
            + CLASSPATH
            + " "
            + fileName;
    // System.out.println("compile: "+cmdLine);

    File f = new File(tmpdir, fileName);
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    //		DiagnosticCollector<JavaFileObject> diagnostics =
    //			new DiagnosticCollector<JavaFileObject>();

    StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);

    Iterable<? extends JavaFileObject> compilationUnits =
        fileManager.getJavaFileObjectsFromFiles(Arrays.asList(f));

    Iterable<String> compileOptions =
        Arrays.asList(new String[] {"-d", tmpdir, "-cp", tmpdir + pathSep + CLASSPATH});

    JavaCompiler.CompilationTask task =
        compiler.getTask(null, fileManager, null, compileOptions, null, compilationUnits);
    boolean ok = task.call();

    try {
      fileManager.close();
    } catch (IOException ioe) {
      ioe.printStackTrace(System.err);
    }

    //		List<String> errors = new ArrayList<String>();
    //		for (Diagnostic diagnostic : diagnostics.getDiagnostics()) {
    //			errors.add(
    //				String.valueOf(diagnostic.getLineNumber())+
    //				": " + diagnostic.getMessage(null));
    //		}
    //		if ( errors.size()>0 ) {
    //			System.err.println("compile stderr from: "+cmdLine);
    //			System.err.println(errors);
    //			return false;
    //		}
    return ok;

    /*
    File outputDir = new File(tmpdir);
    try {
    	Process process =
    		Runtime.getRuntime().exec(args, null, outputDir);
    	StreamVacuum stdout = new StreamVacuum(process.getInputStream());
    	StreamVacuum stderr = new StreamVacuum(process.getErrorStream());
    	stdout.start();
    	stderr.start();
    	process.waitFor();
              stdout.join();
              stderr.join();
    	if ( stdout.toString().length()>0 ) {
    		System.err.println("compile stdout from: "+cmdLine);
    		System.err.println(stdout);
    	}
    	if ( stderr.toString().length()>0 ) {
    		System.err.println("compile stderr from: "+cmdLine);
    		System.err.println(stderr);
    	}
    	int ret = process.exitValue();
    	return ret==0;
    }
    catch (Exception e) {
    	System.err.println("can't exec compilation");
    	e.printStackTrace(System.err);
    	return false;
    }
    */
  }
Beispiel #15
0
 public void close() throws IOException {
   standardJavaFileManager.close();
 }
  void run() throws Exception {
    javadoc = ToolProvider.getSystemDocumentationTool();
    fm = javadoc.getStandardFileManager(null, null, null);
    try {
      fm.setLocation(StandardLocation.CLASS_OUTPUT, Arrays.asList(new File(".")));
      fm.setLocation(StandardLocation.CLASS_PATH, Collections.<File>emptyList());
      files = Arrays.asList(new TestJFO("Test.java", code));

      test(
          Collections.<String>emptyList(),
          Main.Result.ERROR,
          EnumSet.of(Message.DL_ERR9A, Message.DL_WRN12A));

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

      //            test(Arrays.asList("-Xdoclint:none"),
      //                    Main.Result.OK,
      //                    EnumSet.of(Message.JD_WRN10, Message.JD_WRN13));

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

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

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

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

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

      test(
          Arrays.asList(rawDiags, "-Xdoclint:syntax", "-private"),
          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.ERROR,
          EnumSet.of(Message.OPT_BADARG));

      files =
          Arrays.asList(
              new TestJFO("p1/P1Test.java", p1Code), new TestJFO("p2/P2Test.java", p2Code));

      test(
          Arrays.asList(rawDiags),
          Main.Result.ERROR,
          EnumSet.of(Message.DL_ERR_P1TEST, Message.DL_ERR_P2TEST));

      test(
          Arrays.asList(rawDiags, "-Xdoclint/package:p1"),
          Main.Result.ERROR,
          EnumSet.of(Message.DL_ERR_P1TEST));

      test(
          Arrays.asList(rawDiags, "-Xdoclint/package:*p"),
          Main.Result.ERROR,
          EnumSet.of(Message.OPT_BADPACKAGEARG));

      if (errors > 0) throw new Exception(errors + " errors occurred");
    } finally {
      fm.close();
    }
  }
Beispiel #17
0
  public static void main(String[] args) throws Throwable {
    StringBuilder sb = new StringBuilder(64);
    sb.append("package tools.test.compile;\n");
    sb.append("public class HelloWorld implements tools.test.InlineCompiler.DoStuff {\n");
    sb.append("    public void doStuff() {\n");
    sb.append(
        "        System.out.println(\"print:\" + tools.Convert.toString(\"Hello world\"));\n");
    sb.append("    }\n");
    sb.append("}\n");

    File helloWorldJava =
        new File("./tools/test/compile/HelloWorld.java"); // 注意这里的路径,和包名对应 2014-11-21 by 六三
    if (helloWorldJava.getParentFile().exists() || helloWorldJava.getParentFile().mkdirs()) {
      // 写文件
      Writer writer = null;
      try {
        writer = new FileWriter(helloWorldJava);
        writer.write(sb.toString());
        writer.flush();
      } finally {
        try {
          writer.close();
        } catch (Exception e) {;
        }
      }
    }

    /**
     * Compilation Requirements
     * ********************************************************************************************
     */
    DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, null, null);

    // This sets up the class path that the compiler will use.
    // I've added the .jar file that contains the DoStuff interface within in it...
    List<String> optionList = new ArrayList<String>();
    optionList.add("-classpath");
    optionList.add(System.getProperty("java.class.path") + ";");

    Iterable<? extends JavaFileObject> compilationUnit =
        fileManager.getJavaFileObjectsFromFiles(Arrays.asList(helloWorldJava));

    JavaCompiler.CompilationTask task =
        compiler.getTask(null, fileManager, diagnostics, optionList, null, compilationUnit);

    /** Compilation Requirements * */
    if (task.call()) {
      /** Load and execute * */
      System.out.println("Yipe");
      // Create a new custom class loader, pointing to the directory that contains the compiled
      // classes, this should point to the top of the package structure!
      URLClassLoader classLoader = new URLClassLoader(new URL[] {new File("./").toURI().toURL()});
      // Load the class from the classloader by name....
      Class<?> loadedClass = classLoader.loadClass("tools.test.compile.HelloWorld");
      // Create a new instance...
      Object obj = loadedClass.newInstance();
      // Santity check
      if (obj instanceof DoStuff) {
        // Cast to the DoStuff interface
        DoStuff stuffToDo = (DoStuff) obj;
        // Run it baby
        stuffToDo.doStuff();
      }
      /** Load and execute * */
    } else {
      for (Diagnostic<? extends JavaFileObject> diagnostic : diagnostics.getDiagnostics()) {
        System.out.format(
            "Error on line %d in %s%n", diagnostic.getLineNumber(), diagnostic.getSource().toUri());
      }
    }
    fileManager.close();
  }
Beispiel #18
0
  /**
   * Compile the given files.
   *
   * @param files Source files to compile.
   * @param classPath Support jars or directories that should be on the classpath. If @code{null},
   *     the default is used.
   * @param sourcePath Location of additional sources to be compiled on-demand. If @code{null}, the
   *     default is used.
   * @param destination Location (directory) for compiled classes. If @code{null}, the default
   *     in-place location is used.
   * @param bootClassPath The bootclasspath (contains Java API jars or directories); should be
   *     consistent with @code{sourceVersion} If @code{null}, the default is used.
   * @param sourceVersion The language version of the sources. Should be consistent
   *     with @code{bootClassPath}. If @code{null}, the default is used.
   * @param showWarnings Whether compiler warnings should be shown or ignored.
   * @return Errors that occurred. If no errors, should be zero length (not null).
   */
  public List<? extends DJError> compile(
      List<? extends File> files,
      List<? extends File> classPath,
      List<? extends File> sourcePath,
      File destination,
      List<? extends File> bootClassPath,
      String sourceVersion,
      boolean showWarnings) {
    debug.logStart("compile()");
    debug.logValues(
        new String[] {
          "this",
          "files",
          "classPath",
          "sourcePath",
          "destination",
          "bootClassPath",
          "sourceVersion",
          "showWarnings"
        },
        this,
        files,
        classPath,
        sourcePath,
        destination,
        bootClassPath,
        sourceVersion,
        showWarnings);

    Iterable<String> options =
        _createOptions(
            classPath, sourcePath, destination, bootClassPath, sourceVersion, showWarnings);
    LinkedList<DJError> errors = new LinkedList<DJError>();

    // This is the class that javax.tools.ToolProvider.getSystemJavaCompiler() uses.
    // We create an instance of that class directly, bypassing ToolProvider, because ToolProvider
    // returns null
    // if DrJava is started with just the JRE, instead of with the JDK, even if tools.jar is later
    // made available
    // to the class loader.
    JavaCompiler compiler = null;
    try {
      compiler = (JavaCompiler) (Class.forName("com.sun.tools.javac.api.JavacTool").newInstance());
    } catch (ClassNotFoundException e) {
      errors.addFirst(new DJError("Compile exception: " + e, false));
      error.log(e);
      return errors;
    } catch (InstantiationException e) {
      errors.addFirst(new DJError("Compile exception: " + e, false));
      error.log(e);
      return errors;
    } catch (IllegalAccessException e) {
      errors.addFirst(new DJError("Compile exception: " + e, false));
      error.log(e);
      return errors;
    }

    /** Default FileManager provided by Context class */
    DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
    StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, null, null);
    Iterable<? extends JavaFileObject> fileObjects = fileManager.getJavaFileObjectsFromFiles(files);

    try {
      System.err.println("Calling '" + compiler + "' with options " + options);
      compiler.getTask(null, fileManager, diagnostics, options, null, fileObjects).call();
      for (Diagnostic<? extends JavaFileObject> d : diagnostics.getDiagnostics()) {
        Diagnostic.Kind dt = d.getKind();
        boolean isWarning = false; // init required by javac

        switch (dt) {
          case OTHER:
            continue; // skip, do not record
          case NOTE:
            continue; // skip, do not record
          case MANDATORY_WARNING:
            isWarning = true;
            break;
          case WARNING:
            isWarning = true;
            break;
          case ERROR:
            isWarning = false;
            break;
        }

        /* The new Java 6.0 Diagnostic interface appears to be broken.  The expression d.getSource().getName() returns a
         * non-existent path--the name of the test file (allocated as a TEMP file) appended to the source root for
         * DrJava--in GlobalModelCompileErrorsTest.testCompileFailsCorrectLineNumbers().  The expression
         * d.getSource().toUri().getPath() returns the correct result as does ((JCDiagnostic) d).getSourceName(). */
        if (d.getSource() != null) {
          errors.add(
              new DJError(
                  new File(d.getSource().toUri().getPath()), // d.getSource().getName() fails!
                  ((int) d.getLineNumber()) - 1, // javac starts counting at 1
                  ((int) d.getColumnNumber()) - 1,
                  d.getMessage(null), // null is the locale
                  isWarning));
        } else {
          errors.add(new DJError(d.getMessage(null), isWarning));
        }
      }
      fileManager.close();
    } catch (Throwable t) { // compiler threw an exception/error (typically out of memory error)
      errors.addFirst(new DJError("Compile exception: " + t, false));
      error.log(t);
    }

    debug.logEnd("compile()");
    return errors;
  }
  public static void compile(
      String fileLocation,
      String code,
      String outputLocation,
      final PrintStream stream,
      ArrayList<CompilerListener> compilerListeners) {
    if (!CONFIG_DATA.containsKey("jdk.location")
        || !(new File(CONFIG_DATA.get("jdk.location")).isDirectory())) {
      FileBrowseDialog jdkSearch =
          new FileBrowseDialog(
              "Specify your JDK location.", "Location:", FileBrowseDialog.DIRECTORY);

      String jdkLoc = jdkSearch.open();

      if (jdkLoc != null) {
        String location = FileUtils.removeEndingSlashes(jdkLoc.replace('\\', '/'));

        ArrowIDE.setConfigDataValue("jdk.location", location);
      } else {
        stream.println("You must specify a valid jdk to compile this program.");

        return;
      }
    }

    String fileName = FileUtils.getFileNameWithoutExtension(fileLocation);

    fileLocation = FileUtils.removeExtension(fileLocation);

    String projectLocation = FileUtils.getPrecedingPath(fileLocation, "/src/");

    outputLocation = projectLocation + "/bin/";

    try {
      outputLocation = FileUtils.getAbsolutePath(outputLocation) + "/";
    } catch (IOException e2) {
      e2.printStackTrace();
    }

    new File(outputLocation).mkdirs();

    //		fileName = fileName == null ? "" : fileName;
    //
    //		JavacJavaCompilerSettings settings = new JavacJavaCompilerSettings();
    //
    //		org.apache.commons.jci.compilers.JavaCompiler compiler = new
    // JavacJavaCompiler(settings);//new JavaCompilerFactory().createCompiler("javac");//new
    // JavacJavaCompiler(settings);
    //
    ////		org.apache.commons.jci.compilers.JavaCompiler compiler = new
    // JavaCompilerFactory().createCompiler("eclipse");
    //
    //		MemoryResourceReader mrr = new MemoryResourceReader();
    //		mrr.add("Test", code.getBytes());
    //
    //		MemoryResourceStore mrs = new MemoryResourceStore();
    //
    //
    //		CompilationResult result = compiler.compile(new String[] { fileName }, mrr, mrs);
    //
    //		return result.getErrors().length + " ";

    /*Creating dynamic java source code file object*/

    SimpleJavaFileObject fileObject = new DynamicJavaSourceCodeObject(fileName, code);

    JavaFileObject javaFileObjects[] = new JavaFileObject[] {fileObject};

    /*Instantiating the java compiler*/
    JavaCompiler compiler = getCompiler();

    /**
     * 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);

    /* Prepare a list of compilation units (java source code file objects) to input to compilation task*/
    Iterable<? extends JavaFileObject> compilationUnits = Arrays.asList(javaFileObjects);

    String classpath = getClasspath(projectLocation);

    /*Prepare any compilation options to be used during compilation*/
    // In this example, we are asking the compiler to place the output files under bin folder.
    String[] compileOptions =
        new String[] {
          //			"-cp", classpath,
          "-cp", classpath,
          "-d", outputLocation
        };

    Iterable<String> compilationOptions = Arrays.asList(compileOptions);

    //		if (true)return;

    /*Create a diagnostic controller, which holds the compilation problems*/
    DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();

    /*Create a compilation task from compiler by passing in the required input objects prepared above*/
    CompilationTask compilerTask =
        compiler.getTask(
            null, stdFileManager, diagnostics, compilationOptions, null, compilationUnits);

    // Perform the compilation by calling the call method on compilerTask object.
    boolean status = compilerTask.call();

    final StringBuilder error = new StringBuilder();

    String outputFile = outputLocation + fileName + ".class";

    final String outputFiles[] = new String[] {outputFile};

    ArrayList<Diagnostic> ds = new ArrayList<Diagnostic>();

    ArrayList<String> errors = new ArrayList<String>();

    // If compilation error occurs
    if (!status) {
      /*Iterate through each compilation problem and print it*/
      for (Diagnostic d : diagnostics.getDiagnostics()) {
        String err = d.getMessage(Locale.getDefault());

        errors.add(String.format("Error on line %d: %s", d.getLineNumber(), err));

        ds.add(d);
      }

      String strs[] = errors.toArray(new String[0]);

      for (String str : strs) {
        error.append(str);
      }

      Display.getDefault()
          .syncExec(
              new Runnable() {
                public void run() {
                  if (stream != null) {
                    stream.println(error.toString());
                  }
                }
              });
    }

    CompileOutput output = null;

    CompileOutput outputs[] = new CompileOutput[ds.size() > 0 ? ds.size() : 1];

    if (ds.size() > 0) {
      for (int i = 0; i < ds.size(); i++) {
        outputs[i] =
            new CompileOutput(
                (int) ds.get(i).getStartPosition(),
                (int) ds.get(i).getEndPosition(),
                (int) ds.get(i).getLineNumber(),
                status ? 0 : 1,
                errors.get(i));
      }
    } else {
      outputs[0] = new CompileOutput(0, 0, 0, status ? 0 : 1, "");
    }

    for (int i = compilerListeners.size() - 1; i >= 0; i--) {
      CompilerEvent event = new CompilerEvent(outputFiles, outputs, stream, fileLocation);

      compilerListeners.get(i).compiled(event);
    }

    try {
      stdFileManager.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
 public void close() throws IOException {
   // System.out.println("close()");
   fileManager.close();
 }
 @Override
 public void close() throws IOException {
   myStandardFileManager.close();
 }
Beispiel #22
0
  // compile a Java file with the installed javac compiler
  public boolean compileFile(String sourceFile) {
    boolean compilationResult = true; // no errors

    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    if (compiler == null) { // Sterg-SOS why not loaded?
      System.out.println(
          "ToolProvider.getSystemJavaCompiler: no compiler provided. Unable to compile");
    }
    DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<>();
    StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, null, null);

    StringWriter compileWriter = new StringWriter();

    List<File> sourceFileList = new ArrayList<File>();
    sourceFileList.add(new File(sourceFile));
    Iterable<? extends JavaFileObject> compilationUnits =
        fileManager.getJavaFileObjectsFromFiles(sourceFileList);

    String pathOfFile = sourceFile.substring(0, sourceFile.lastIndexOf(File.separatorChar));
    String classpath =
        GlobalValues.jarFilePath
            + File.pathSeparatorChar
            + pathOfFile
            + File.pathSeparatorChar
            + ".";
    Iterable<String> options = Arrays.asList("-cp", classpath);

    CompilationTask task =
        compiler.getTask(compileWriter, fileManager, null, options, null, compilationUnits);

    boolean compileResult = task.call();
    if (compileResult == false) {
      compilationResult = false; // compilation errors
      JFrame compResultsFrame = new JFrame("Compilation Results");
      String diagnString = compileWriter.toString();
      JTextArea compResultsArea = new JTextArea(diagnString);
      compResultsArea.setFont(new Font("Arial", Font.BOLD, 16));
      JPanel compResultsPanel = new JPanel();
      compResultsPanel.add(compResultsArea);
      compResultsFrame.add(compResultsPanel);
      compResultsFrame.setSize(800, 200);
      compResultsFrame.setLocation(100, 200);
      compResultsFrame.setVisible(true);
      int response =
          JOptionPane.showOptionDialog(
              null,
              "File " + sourceFile + " has compilation errors ",
              "Edit File? ",
              JOptionPane.YES_NO_OPTION,
              JOptionPane.QUESTION_MESSAGE,
              null,
              null,
              null);
      if (response == JOptionPane.YES_OPTION) { // edit it with scalalabEditor
        new scalalabEdit.EditorPaneEdit(sourceFile);
      }
    }

    try {
      fileManager.close();
    } catch (IOException e) {
    }

    return compilationResult;
  }
Beispiel #23
0
  // JDK6 Complier API,CGLib,ASM
  public static Object newProxyInstance(Class infce, InvocationHandler h) throws Exception {
    String methodStr = "";
    String rt = "\r\n";

    Method[] methods = infce.getMethods();

    /*for(Method m : methods) {
    	methodStr += "@Override" +rt +
    			"public void " + m.getName() + "() {" + rt +
    		    "	     long start = System.currentTimeMillis();" + rt +
    		    "        System.out.println(\"starttime:\" + start);" + rt +
    		    "        t." +m.getName() + "();"+ rt +
    		    "        long end = System.currentTimeMillis();" + rt +
    		    "        System.out.println(\"time:\" + (end-start));" + rt +
    			"}";
    }*/
    for (Method m : methods) {
      methodStr +=
          "@Override"
              + rt
              + "public void "
              + 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
              + "}";
    }

    String src =
        "package com.lq.proxy1;"
            + rt
            + "import java.lang.reflect.Method;"
            + rt
            + "public class $Proxy1 implements "
            + infce.getName()
            + "{"
            + rt
            + "    public $Proxy1(InvocationHandler h) {"
            + rt
            + "        super();"
            + rt
            + "        this.h = h;"
            + rt
            + "    }"
            + rt
            + "    com.lq.proxy1.InvocationHandler h;"
            + rt
            + methodStr
            + "}";
    // System.out.println(System.getProperty("user.dir"));
    String fileName = "d:/src/com/lq/proxy1/$Proxy1.java";
    File f = new File(fileName);
    FileWriter fw = new FileWriter(f);
    fw.write(src);
    fw.flush();
    fw.close();
    /** compile 从JavaCompiler开始到最后的作用是生成class文件 */
    // 拿到系统当前默认的java编译器,即javac
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    // System.out.println(compiler.getClass().getName());
    // 第一个参数:诊断监听器
    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:/" + "d:/src/")};
    URLClassLoader ul = new URLClassLoader(urls);
    Class c = ul.loadClass("com.lq.proxy1.$Proxy1");
    System.out.println(c);

    // 拿到参数为Moveable类型的class类型的Constructor
    Constructor ctr = c.getConstructor(InvocationHandler.class);
    // Tank为被代理对象
    Object m = ctr.newInstance(h);
    // m.move();

    return m;
  }