Ejemplo n.º 1
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();
  }
    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.º 3
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();
    }
  }
Ejemplo n.º 4
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 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.º 6
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;
  }
Ejemplo n.º 7
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 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.º 9
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.º 10
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.º 11
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.º 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();
  }
Ejemplo n.º 13
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;
    }
    */
  }
  @SuppressWarnings("unchecked")
  private void executeWithExceptionsHandled() throws Exception {
    if (outputDirectory == null) {
      outputDirectory = getDefaultOutputDirectory();
    }

    ensureOutputDirectoryExists();
    addOutputToSourcesIfNeeded();

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

    final String includesString =
        (includes == null || includes.length == 0) ? "**/*.java" : StringUtils.join(includes, ",");
    final String excludesString =
        (excludes == null || excludes.length == 0) ? null : StringUtils.join(excludes, ",");

    List<File> filesToCompile = new ArrayList<File>(100);
    for (Object sourceDirectory : project.getCompileSourceRoots()) {
      File directory = new File((String) sourceDirectory);
      if (directory.exists()) {
        if (!directory.equals(outputDirectory)) {
          filesToCompile.addAll(FileUtils.getFiles(directory, includesString, excludesString));
        }
      }
    }

    if (filesToCompile.isEmpty()) {
      getLog().warn("no source file(s) detected! processor compilationTask will be skipped!");
      return;
    }

    List<String> options = new ArrayList<String>(10);

    options.add("-cp");
    options.add(buildCompileClasspath());
    options.add("-proc:only");

    String processor = buildProcessor();
    if (processor != null) {
      options.add("-processor");
      options.add(processor);
    } else {
      getLog().info("No processors specified. Using default discovery mechanism.");
    }
    options.add("-d");
    options.add(getOutputClassDirectory().getPath());

    options.add("-s");
    options.add(outputDirectory.getPath());

    if (encoding != null) {
      options.add("-encoding");
      options.add(encoding);
    }

    addCompilerArguments(options);

    setSystemProperties();

    CompilationTask compilationTask =
        compiler.getTask(
            new PrintWriter(System.out),
            fileManager,
            createDiagnosticListener(),
            options,
            null,
            fileManager.getJavaFileObjectsFromFiles(filesToCompile));

    // Perform the compilation compilationTask.
    if (!compilationTask.call()) {
      throw new Exception(
          "An error ocurred while the DevKit was generating Java code. Check the logs for further details.");
    }
  }
Ejemplo n.º 15
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();
  }
Ejemplo n.º 16
0
    void run(PrintWriter out, String... args) throws IOException {
      JavaCompiler c = ToolProvider.getSystemJavaCompiler();
      StandardJavaFileManager fm = c.getStandardFileManager(null, null, null);

      // DPrinter options
      final Set<TaskEvent.Kind> before = EnumSet.noneOf(TaskEvent.Kind.class);
      final Set<TaskEvent.Kind> after = EnumSet.noneOf(TaskEvent.Kind.class);
      boolean showPositions = false;
      boolean showSource = false;
      boolean showTreeSymbols = false;
      boolean showTreeTypes = false;
      boolean showEmptyItems = true;
      boolean showNulls = true;

      // javac options
      Collection<String> options = new ArrayList<String>();
      Collection<File> files = new ArrayList<File>();
      String classpath = null;
      String classoutdir = null;

      final Handler h = getHandlers().get(args[0]);
      if (h == null) throw new IllegalArgumentException(args[0]);

      for (int i = 1; i < args.length; i++) {
        String arg = args[i];
        if (arg.equals("-before") && i + 1 < args.length) {
          before.add(getKind(args[++i]));
        } else if (arg.equals("-after") && i + 1 < args.length) {
          after.add(getKind(args[++i]));
        } else if (arg.equals("-showPositions")) {
          showPositions = true;
        } else if (arg.equals("-showSource")) {
          showSource = true;
        } else if (arg.equals("-showTreeSymbols")) {
          showTreeSymbols = true;
        } else if (arg.equals("-showTreeTypes")) {
          showTreeTypes = true;
        } else if (arg.equals("-hideEmptyLists")) {
          showEmptyItems = false;
        } else if (arg.equals("-hideNulls")) {
          showNulls = false;
        } else if (arg.equals("-classpath") && i + 1 < args.length) {
          classpath = args[++i];
        } else if (arg.equals("-d") && i + 1 < args.length) {
          classoutdir = args[++i];
        } else if (arg.startsWith("-")) {
          int n = c.isSupportedOption(arg);
          if (n < 0) throw new IllegalArgumentException(arg);
          options.add(arg);
          while (n > 0) options.add(args[++i]);
        } else if (arg.endsWith(".java")) {
          files.add(new File(arg));
        }
      }

      if (classoutdir != null) {
        fm.setLocation(StandardLocation.CLASS_OUTPUT, Arrays.asList(new File(classoutdir)));
      }

      if (classpath != null) {
        Collection<File> path = new ArrayList<File>();
        for (String p : classpath.split(File.pathSeparator)) {
          if (p.isEmpty()) continue;
          File f = new File(p);
          if (f.exists()) path.add(f);
        }
        fm.setLocation(StandardLocation.CLASS_PATH, path);
      }
      Iterable<? extends JavaFileObject> fos = fm.getJavaFileObjectsFromFiles(files);

      JavacTask task = (JavacTask) c.getTask(out, fm, null, options, null, fos);
      final Trees trees = Trees.instance(task);

      final DPrinter dprinter = new DPrinter(out, trees);
      dprinter
          .source(showSource)
          .emptyItems(showEmptyItems)
          .nulls(showNulls)
          .positions(showPositions)
          .treeSymbols(showTreeSymbols)
          .treeTypes(showTreeTypes);

      if (before.isEmpty() && after.isEmpty()) {
        if (h.name.equals("trees") && !showTreeSymbols && !showTreeTypes)
          after.add(TaskEvent.Kind.PARSE);
        else after.add(TaskEvent.Kind.ANALYZE);
      }

      task.addTaskListener(
          new TaskListener() {
            public void started(TaskEvent e) {
              if (before.contains(e.getKind())) handle(e);
            }

            public void finished(TaskEvent e) {
              if (after.contains(e.getKind())) handle(e);
            }

            private void handle(TaskEvent e) {
              JCCompilationUnit unit = (JCCompilationUnit) e.getCompilationUnit();
              switch (e.getKind()) {
                case PARSE:
                case ENTER:
                  h.handle(e.getSourceFile().getName(), unit, unit, dprinter);
                  break;

                default:
                  TypeElement elem = e.getTypeElement();
                  h.handle(elem.toString(), unit, (JCTree) trees.getTree(elem), dprinter);
                  break;
              }
            }
          });

      task.call();
    }
Ejemplo n.º 17
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;
  }
Ejemplo n.º 18
0
 public Iterable<? extends JavaFileObject> getJavaFileObjectsFromFiles(
     Iterable<? extends File> files) {
   return standardJavaFileManager.getJavaFileObjectsFromFiles(files);
 }
Ejemplo n.º 19
0
 static JavacTaskImpl getTask(JavaCompiler compiler, File... file) {
   StandardJavaFileManager fm = compiler.getStandardFileManager(null, null, null);
   Iterable<? extends JavaFileObject> files = fm.getJavaFileObjectsFromFiles(Arrays.asList(file));
   return (JavacTaskImpl) compiler.getTask(null, fm, null, null, null, files);
 }
Ejemplo n.º 20
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;
  }