Package javax.tools

Examples of javax.tools.JavaCompiler


     */
    private void compileJava(String className, final String source, Set<String> extraClassPath) throws IOException {
        if (LOG.isTraceEnabled())
            LOG.trace("Compiling [#0], source: [#1]", className, source);

        JavaCompiler compiler =
                ToolProvider.getSystemJavaCompiler();

        DiagnosticCollector<JavaFileObject> diagnostics =
                new DiagnosticCollector<JavaFileObject>();

        //the generated bytecode is fed to the class loader
        JavaFileManager jfm = new
                ForwardingJavaFileManager<StandardJavaFileManager>(
                        compiler.getStandardFileManager(diagnostics, null, null)) {

                    @Override
                    public JavaFileObject getJavaFileForOutput(Location location,
                                                               String name,
                                                               JavaFileObject.Kind kind,
                                                               FileObject sibling) throws IOException {
                        MemoryJavaFileObject fileObject = new MemoryJavaFileObject(name, kind);
                        classLoader.addMemoryJavaFileObject(name, fileObject);
                        return fileObject;
                    }
                };

        //read java source code from memory
        String fileName = className.replace('.', '/') + ".java";
        SimpleJavaFileObject sourceCodeObject = new SimpleJavaFileObject(toURI(fileName), JavaFileObject.Kind.SOURCE) {
            @Override
            public CharSequence getCharContent(boolean
                    ignoreEncodingErrors)
                    throws IOException, IllegalStateException,
                    UnsupportedOperationException {
                return source;
            }

        };

        //build classpath
        //some entries will be added multiple times, hence the set
        List<String> optionList = new ArrayList<String>();
        Set<String> classPath = new HashSet<String>();

        //find available jars
        ClassLoaderInterface classLoaderInterface = getClassLoaderInterface();
        UrlSet urlSet = new UrlSet(classLoaderInterface);

        //find jars
        List<URL> urls = urlSet.getUrls();

        for (URL url : urls) {
            URL normalizedUrl = URLUtil.normalizeToFileProtocol(url);
            File file = FileUtils.toFile((URL) ObjectUtils.defaultIfNull(normalizedUrl, url));
            if (file.exists())
                classPath.add(file.getAbsolutePath());
        }

        //these should be in the list already, but I am feeling paranoid
        //this jar
        classPath.add(getJarUrl(EmbeddedJSPResult.class));
        //servlet api
        classPath.add(getJarUrl(Servlet.class));
        //jsp api
        classPath.add(getJarUrl(JspPage.class));

        try {
            Class annotationsProcessor = Class.forName("org.apache.AnnotationProcessor");
            classPath.add(getJarUrl(annotationsProcessor));
        } catch (ClassNotFoundException e) {
            //ok ignore
        }

        //add extra classpath entries (jars where tlds were found will be here)
        for (Iterator<String> iterator = extraClassPath.iterator(); iterator.hasNext();) {
            String entry = iterator.next();
            classPath.add(entry);
        }

        String classPathString = StringUtils.join(classPath, File.pathSeparator);
        if (LOG.isDebugEnabled()) {
            LOG.debug("Compiling [#0] with classpath [#1]", className, classPathString);
        }

        optionList.addAll(Arrays.asList("-classpath", classPathString));

        //compile
        JavaCompiler.CompilationTask task = compiler.getTask(
                null, jfm, diagnostics, optionList, null,
                Arrays.asList(sourceCodeObject));

        if (!task.call()) {
            throw new StrutsException("Compilation failed:" + diagnostics.getDiagnostics().get(0).toString());
View Full Code Here


            }
        }
    }
   
    private void setFileManager() {
        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
        fileManager = compiler.getStandardFileManager(null, null, null);
        String outDir = processingEnv.getOptions().get("out");
        if (outDir != null)
           isUserSpecifiedOutputLocation = setSourceOutputDirectory(new File(outDir));
    }
View Full Code Here

    BufferedWriter bw = new BufferedWriter(new FileWriter(sourceCodeFile));
    bw.write(javaCode);
    bw.close();

    // compile it by JavaCompiler
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    ArrayList<String> srcFileNames = new ArrayList<String>();
    srcFileNames.add(sourceCodeFile.toString());
    StandardJavaFileManager fm = compiler.getStandardFileManager(null, null,
      null);
    Iterable<? extends JavaFileObject> cu =
      fm.getJavaFileObjects(sourceCodeFile);
    List<String> options = new ArrayList<String>();
    options.add("-classpath");
    // only add hbase classes to classpath. This is a little bit tricky: assume
    // the classpath is {hbaseSrc}/target/classes.
    String currentDir = new File(".").getAbsolutePath();
    String classpath = currentDir + File.separator + "target"+ File.separator
      + "classes" + System.getProperty("path.separator")
      + System.getProperty("java.class.path") + System.getProperty("path.separator")
      + System.getProperty("surefire.test.class.path");

    options.add(classpath);
    LOG.debug("Setting classpath to: " + classpath);

    JavaCompiler.CompilationTask task = compiler.getTask(null, fm, null,
      options, null, cu);
    assertTrue("Compile file " + sourceCodeFile + " failed.", task.call());

    // build a jar file by the classes files
    String jarFileName = className + ".jar";
View Full Code Here

    PrintStream source = new PrintStream(javaPath);
    source.println("package " + packageName + ";");
    source.println("public class " + classNamePrefix
        + " { public static void main(String[] args) { } };");
    source.close();
    JavaCompiler jc = ToolProvider.getSystemJavaCompiler();
    int result = jc.run(null, null, null, javaPath);
    assertEquals(0, result);
    File classFile = new File(classPath);
    assertTrue(classFile.exists());
    return new FileAndPath(packageName.replace('.', '/') + '/', classFile);
  }
View Full Code Here

        return result;
    }

    private boolean compileFiles(Map<String,MemoryByteCode> mem, Iterable<? extends JavaFileObject> javaSources)
    {
        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
        if( compiler==null ){
            Logger.getLogger(JDKCompiler.class.getName()).log(
                    Level.WARNING,
                    "platform not support Java compiler, use JDK");
            return false;
        }
        StandardJavaFileManager fileman = compiler.getStandardFileManager(null, null, null);
        MemoryJavaFileManager fileman2 = new MemoryJavaFileManager(fileman);

        fileman2.setClassDataMap(mem);
        Iterable<? extends JavaFileObject> compilUnit = javaSources;

        Writer writer = new OutputStreamWriter(System.err);
        JavaCompiler.CompilationTask ctask = compiler.getTask(writer, fileman2, null, null, null, compilUnit);
        Boolean res = ctask.call();
        boolean successCompile = res!=null ? res : false;

        try {
            fileman.close();
View Full Code Here

    return tmp;
  }

  /** Compile java src into java .class files */
  private void compileJava(File tempDir) throws IOException, CompileException {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    if (compiler == null) {
      throw new CompileException("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(getAllFiles(tempDir, ".java"));
      ArrayList<String> options = new ArrayList<String>();
      String classpath = getMyClasspath();
      if (classpath != null) {
        options.add("-classpath");
        options.add(classpath);
      }
      options.add("-d");
      options.add(tempDir.getPath());
      JavaCompiler.CompilationTask task = compiler.getTask(
          null,
          fileManager,
          diagnostics,
          options,
          null,
View Full Code Here

    } finally {
      fw.close();
    }

    // compiling it
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
    Iterable<? extends JavaFileObject> compilationUnits1 = fileManager.getJavaFileObjects(javaFile);
    CompilationTask task = compiler.getTask(null, fileManager, null, null, null, compilationUnits1);
    task.call();

    // here is the compiled file
    File classFile = new File(javaFile.getParentFile(), className+".class");
    Assert.assertTrue(classFile.exists());
View Full Code Here

    }

    private static List<File> compile(File[] javaFiles) {
        LOG.info("Compiling: " + Arrays.asList(javaFiles));

        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
        StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
        Iterable<? extends JavaFileObject> compilationUnits1 =
                fileManager.getJavaFileObjects(javaFiles);
        JavaCompiler.CompilationTask task =
                compiler.getTask(null, fileManager, null, null, null, compilationUnits1);
        task.call();

        List<File> classFiles = Lists.newArrayList();
        for (File javaFile : javaFiles) {
            File classFile = new File(javaFile.getAbsolutePath().replace(".java", ".class"));
View Full Code Here

        "  @interface Empty {}",
        "  @AutoAnnotation static Empty newEmpty() {}",
        "  @NotAutoAnnotation Empty notNewEmpty() {}",
        "}"
    );
    JavaCompiler javaCompiler = ToolProvider.getSystemJavaCompiler();
    DiagnosticCollector<JavaFileObject> diagnosticCollector =
        new DiagnosticCollector<JavaFileObject>();
    JavaCompiler.CompilationTask compilationTask = javaCompiler.getTask(
        (Writer) null, (JavaFileManager) null, diagnosticCollector, (Iterable<String>) null,
        (Iterable<String>) null, ImmutableList.of(erroneousJavaFileObject));
    compilationTask.setProcessors(ImmutableList.of(new AutoAnnotationProcessor()));
    boolean result = compilationTask.call();
    assertThat(result).isFalse();
View Full Code Here

  }

  private void doTestTypeSimplifier(
      AbstractTestProcessor testProcessor, File tmpDir, ImmutableMap<String, String> classToSource)
      throws IOException {
    JavaCompiler javac = ToolProvider.getSystemJavaCompiler();
    DiagnosticCollector<JavaFileObject> diagnosticCollector =
        new DiagnosticCollector<JavaFileObject>();
    StandardJavaFileManager fileManager =
        javac.getStandardFileManager(diagnosticCollector, null, null);

    StringWriter compilerOut = new StringWriter();

    List<String> options = ImmutableList.of(
        "-sourcepath", tmpDir.getPath(),
        "-d", tmpDir.getPath(),
        "-Xlint");
    javac.getTask(compilerOut, fileManager, diagnosticCollector, options, null, null);
    // This doesn't compile anything but communicates the paths to the JavaFileManager.

    ImmutableList.Builder<JavaFileObject> javaFilesBuilder = ImmutableList.builder();
    for (String className : classToSource.keySet()) {
      JavaFileObject sourceFile = fileManager.getJavaFileForInput(
          StandardLocation.SOURCE_PATH, className, Kind.SOURCE);
      javaFilesBuilder.add(sourceFile);
    }

    // Compile the empty source file to trigger the annotation processor.
    // (Annotation processors are somewhat misnamed because they run even on classes with no
    // annotations.)
    JavaCompiler.CompilationTask javacTask = javac.getTask(
        compilerOut, fileManager, diagnosticCollector, options,
        classToSource.keySet(), javaFilesBuilder.build());
    javacTask.setProcessors(ImmutableList.of(testProcessor));
    javacTask.call();
    List<Diagnostic<? extends JavaFileObject>> diagnostics =
View Full Code Here

TOP

Related Classes of javax.tools.JavaCompiler

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.