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));
 }
Esempio n. 2
0
  /**
   * @author ZhangXiang
   * @param args 2011-4-7
   * @throws NoSuchMethodException
   * @throws InvocationTargetException
   * @throws SecurityException
   * @throws IllegalArgumentException
   */
  public static void main(String[] args)
      throws IllegalArgumentException, SecurityException, InvocationTargetException,
          NoSuchMethodException {

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

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

    JavaFileObject jfo = new JavaSourceFromString("dyclass.Foo", classStr.toString());
    JavaFileObject[] jfos = new JavaFileObject[] {jfo};
    Iterable<? extends JavaFileObject> compilationUnits = Arrays.asList(jfos);
    boolean b = jc.getTask(null, fileManager, null, null, null, compilationUnits).call();
    if (b) { // 如果编译成功
      try {
        Object c = Class.forName("dyclass.Foo").newInstance();
        Class.forName("dyclass.Foo").getMethod("test").invoke(c);
      } catch (InstantiationException e) {
        e.printStackTrace();
      } catch (IllegalAccessException e) {
        e.printStackTrace();
      } catch (ClassNotFoundException e) {
        e.printStackTrace();
      }
    }
  }
Esempio n. 3
0
  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()"));
    }
  }
Esempio n. 4
0
  void run() throws Exception {
    javac = ToolProvider.getSystemJavaCompiler();
    fm = javac.getStandardFileManager(null, null, null);
    fm.setLocation(StandardLocation.CLASS_OUTPUT, Arrays.asList(new File(".")));
    file =
        new SimpleJavaFileObject(URI.create("Test.java"), JavaFileObject.Kind.SOURCE) {
          @Override
          public CharSequence getCharContent(boolean ignoreEncoding) {
            return code;
          }
        };

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

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

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

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

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

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

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

    if (errors > 0) throw new Exception(errors + " errors occurred");
  }
Esempio n. 5
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();
  }
Esempio n. 6
0
  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();
    }
  }
    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();
    }
Esempio n. 8
0
  void createSymbols() throws IOException {
    Set<String> legacy = getLegacyPackages();
    Set<String> legacyProprietary = getLegacyPackages();
    Set<String> documented = new HashSet<String>();
    Set<PackageSymbol> packages =
        ((JavacProcessingEnvironment) processingEnv).getSpecifiedPackages();
    String jarName = processingEnv.getOptions().get("com.sun.tools.javac.sym.Jar");
    if (jarName == null)
      throw new RuntimeException("Must use -Acom.sun.tools.javac.sym.Jar=LOCATION_OF_JAR");
    String destName = processingEnv.getOptions().get("com.sun.tools.javac.sym.Dest");
    if (destName == null)
      throw new RuntimeException("Must use -Acom.sun.tools.javac.sym.Dest=LOCATION_OF_JAR");

    for (PackageSymbol psym : packages) {
      String name = psym.getQualifiedName().toString();
      legacyProprietary.remove(name);
      documented.add(name);
    }

    JavaCompiler tool = ToolProvider.getSystemJavaCompiler();
    StandardJavaFileManager fm = tool.getStandardFileManager(null, null, null);
    Location jarLocation = StandardLocation.locationFor(jarName);
    File jarFile = new File(jarName);
    fm.setLocation(jarLocation, List.of(jarFile));
    fm.setLocation(StandardLocation.CLASS_PATH, List.<File>nil());
    fm.setLocation(StandardLocation.SOURCE_PATH, List.<File>nil());
    {
      ArrayList<File> bootClassPath = new ArrayList<File>();
      bootClassPath.add(jarFile);
      for (File path : fm.getLocation(StandardLocation.PLATFORM_CLASS_PATH)) {
        if (!new File(path.getName()).equals(new File("rt.jar"))) bootClassPath.add(path);
      }
      System.err.println("Using boot class path = " + bootClassPath);
      fm.setLocation(StandardLocation.PLATFORM_CLASS_PATH, bootClassPath);
    }
    // System.out.println(fm.getLocation(StandardLocation.PLATFORM_CLASS_PATH));
    File destDir = new File(destName);
    if (!destDir.exists())
      if (!destDir.mkdirs()) throw new RuntimeException("Could not create " + destDir);
    fm.setLocation(StandardLocation.CLASS_OUTPUT, List.of(destDir));
    Set<String> hiddenPackages = new HashSet<String>();
    Set<String> crisp = new HashSet<String>();
    List<String> options = List.of("-XDdev");
    // options = options.prepend("-doe");
    // options = options.prepend("-verbose");
    JavacTaskImpl task = (JavacTaskImpl) tool.getTask(null, fm, null, options, null, null);
    com.sun.tools.javac.main.JavaCompiler compiler =
        com.sun.tools.javac.main.JavaCompiler.instance(task.getContext());
    ClassReader reader = ClassReader.instance(task.getContext());
    ClassWriter writer = ClassWriter.instance(task.getContext());
    Symtab syms = Symtab.instance(task.getContext());
    Attribute.Compound proprietary =
        new Attribute.Compound(
            syms.proprietaryType, List.<Pair<Symbol.MethodSymbol, Attribute>>nil());

    Type.moreInfo = true;
    Pool pool = new Pool();
    for (JavaFileObject file : fm.list(jarLocation, "", EnumSet.of(CLASS), true)) {
      String className = fm.inferBinaryName(jarLocation, file);
      int index = className.lastIndexOf('.');
      String pckName = index == -1 ? "" : className.substring(0, index);
      boolean addLegacyAnnotation = false;
      if (documented.contains(pckName)) {
        if (!legacy.contains(pckName)) crisp.add(pckName);
        // System.out.println("Documented: " + className);
      } else if (legacyProprietary.contains(pckName)) {
        addLegacyAnnotation = true;
        // System.out.println("Legacy proprietary: " + className);
      } else {
        // System.out.println("Hidden " + className);
        hiddenPackages.add(pckName);
        continue;
      }
      TypeSymbol sym = (TypeSymbol) compiler.resolveIdent(className);
      if (sym.kind != Kinds.TYP) {
        if (className.indexOf('$') < 0) {
          System.err.println("Ignoring (other) " + className + " : " + sym);
          System.err.println("   " + sym.getClass().getSimpleName() + " " + sym.type);
        }
        continue;
      }
      sym.complete();
      if (sym.getEnclosingElement().getKind() != ElementKind.PACKAGE) {
        System.err.println("Ignoring (bad) " + sym.getQualifiedName());
        continue;
      }
      ClassSymbol cs = (ClassSymbol) sym;
      if (addLegacyAnnotation) {
        cs.attributes_field =
            (cs.attributes_field == null)
                ? List.of(proprietary)
                : cs.attributes_field.prepend(proprietary);
      }
      writeClass(pool, cs, writer);
    }

    if (false) {
      for (String pckName : crisp) System.out.println("Crisp: " + pckName);
      for (String pckName : hiddenPackages) System.out.println("Hidden: " + pckName);
      for (String pckName : legacyProprietary) System.out.println("Legacy proprietary: " + pckName);
      for (String pckName : documented) System.out.println("Documented: " + pckName);
    }
  }
Esempio n. 9
0
 public void setLocation(Location location, Iterable<? extends File> path) throws IOException {
   standardJavaFileManager.setLocation(location, path);
 }
Esempio n. 10
0
  public boolean run() throws Util.Exit {

    if (!javac_extras.contains("-XDsuppress-tool-removal-message")) {
      log.println(getMessage("javah.misc.Deprecation"));
    }

    Util util = new Util(log, diagnosticListener);

    if (noArgs || help) {
      showHelp();
      return help; // treat noArgs as an error for purposes of exit code
    }

    if (version || fullVersion) {
      showVersion(fullVersion);
      return true;
    }

    util.verbose = verbose;

    Gen g;

    if (llni) g = new LLNI(doubleAlign, util);
    else {
      g = new JNI(util);
    }

    if (ofile != null) {
      if (!(fileManager instanceof StandardJavaFileManager)) {
        diagnosticListener.report(createDiagnostic("err.cant.use.option.for.fm", "-o"));
        return false;
      }
      Iterable<? extends JavaFileObject> iter =
          ((StandardJavaFileManager) fileManager)
              .getJavaFileObjectsFromFiles(Collections.singleton(ofile));
      JavaFileObject fo = iter.iterator().next();
      g.setOutFile(fo);
    } else {
      if (odir != null) {
        if (!(fileManager instanceof StandardJavaFileManager)) {
          diagnosticListener.report(createDiagnostic("err.cant.use.option.for.fm", "-d"));
          return false;
        }

        if (!odir.exists()) if (!odir.mkdirs()) util.error("cant.create.dir", odir.toString());
        try {
          ((StandardJavaFileManager) fileManager)
              .setLocation(StandardLocation.CLASS_OUTPUT, Collections.singleton(odir));
        } catch (IOException e) {
          Object msg = e.getLocalizedMessage();
          if (msg == null) {
            msg = e;
          }
          diagnosticListener.report(createDiagnostic("err.ioerror", odir, msg));
          return false;
        }
      }
      g.setFileManager(fileManager);
    }

    /*
     * Force set to false will turn off smarts about checking file
     * content before writing.
     */
    g.setForce(force);

    if (fileManager instanceof JavahFileManager)
      ((JavahFileManager) fileManager).setSymbolFileEnabled(false);

    JavaCompiler c = ToolProvider.getSystemJavaCompiler();
    List<String> opts = new ArrayList<>();
    opts.add("-proc:only");
    opts.addAll(javac_extras);

    CompilationTask t;
    try {
      t = c.getTask(log, fileManager, diagnosticListener, opts, classes, null);
    } catch (IllegalArgumentException e) {
      util.error("bad.arg", e.getMessage());
      return false;
    }

    JavahProcessor p = new JavahProcessor(g);
    t.setProcessors(Collections.singleton(p));

    boolean ok = t.call();
    if (p.exit != null) throw new Util.Exit(p.exit);
    return ok;
  }
 @Override
 public void setLocation(Location location, Iterable<? extends File> path) throws IOException {
   myStandardFileManager.setLocation(location, path);
 }