Package javax.tools

Examples of javax.tools.JavaCompiler


        } finally {
            if (pw != null) {
                pw.close();
            }
        }
        JavaCompiler javac = ToolProvider.getSystemJavaCompiler();
        final String javacCmds[] = {UNPACK_FN + ".java"};
        javac.run(null, null, null, javacCmds);
    }
View Full Code Here


  {
    List<String> compilerOptions = new ArrayList<String>(options);
    compilerOptions.add("-d");
    compilerOptions.add(outputBase.getAbsolutePath());

    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    DiagnosticCollector<JavaFileObject> diagnosticsCollector = new DiagnosticCollector<JavaFileObject>();
    StandardJavaFileManager filer = compiler.getStandardFileManager(diagnosticsCollector, null, null);
    Iterable<? extends JavaFileObject> units = filer.getJavaFileObjectsFromFiles(sources);

    JavaCompiler.CompilationTask task = compiler.getTask(null, filer, diagnosticsCollector, compilerOptions, null,
      units);
    task.call();

    for (Diagnostic<?> diagnostic : diagnosticsCollector.getDiagnostics())
    {
View Full Code Here

     * @param diagnostics 存放编译过程中的错误信息 
     * @return   boolean
     */ 
    private static  boolean compiler(String encoding,String jars,String filePath, String distDir, DiagnosticCollector<JavaFileObject> diagnostics){   
        // 获取编译器实例  
        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();  

        // 获取标准文件管理器实例  
        StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);  
         
        //编译文件
        if (StringUtil.IsNullOrEmpty(filePath)) {  
          log.info("待编译的文件或目录不存在");
            return false;  
        }
        //输出目录
        if (!FileUtil.createDictory(distDir)) {  
          log.info("输出目录创建失败");
            return false;  
        }

        // 得到filePath目录下的所有java源文件  
        File sourceFile = new File(filePath);  
        List<File> sourceFileList = new ArrayList<File>();  
        sourceFileList = getSourceFiles(sourceFile);  

        // 没有java文件,直接返回  
        if (sourceFileList.size() == 0) {  
          log.info(filePath + "目录下查找不到任何java文件");
            return false;  
        }  
           
        // 获取要编译的编译单元  
        Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjectsFromFiles(sourceFileList);  

        //编译选项,在编译java文件时,编译程序会自动的去寻找java文件引用的其他的java源文件或者class。 -classpath选项就是定义class文件的查找目录。 
        Iterable<String> options = Arrays.asList("-encoding",encoding,"-classpath",jars,"-d", distDir);  
        CompilationTask compilationTask = compiler.getTask(null, fileManager, diagnostics, options, null, compilationUnits);  

        // 运行编译任务  
        boolean res= compilationTask.call();
        try {
      fileManager.close();
View Full Code Here

   
     

      ByteArrayOutputStream errorOutputStream = new ByteArrayOutputStream();

      JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();

      compiler.run(null, null, errorOutputStream, sourceFile.getAbsolutePath());

      for (byte b : errorOutputStream.toByteArray()) {
        System.out.print((char) b);
      }
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

    }

    System.out.println(">>> Going to search Java files under " + searchDir);

    //Get an instance of java compiler
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();

    //Get a new instance of the standard file manager implementation
    StandardJavaFileManager fileManager = compiler.
        getStandardFileManager(null, null, null);

    // Get the list of java file objects, in this case we have only
    // one file, TestClass.java

    System.out.println(">>> DETECTING SOURCES");
    fileManager.setLocation(StandardLocation.SOURCE_PATH, singleton(searchDir.getAbsoluteFile()));
    Iterable<JavaFileObject> sources = fileManager.list(
        StandardLocation.SOURCE_PATH //locationFor("src/test/java")
        , ""
        , singleton(JavaFileObject.Kind.SOURCE)
        , true);

    if (System.getProperty("sourcefind.debug", null) != null) {
      System.out.println(">>> Sources found:\n" + sources);
    }

    // Create the compilation task
    JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager, null, null, null, sources);

    // Set the annotation processor to the compiler task
    task.setProcessors(singleton(new CodeAnalyzerProcessor()));

    // Perform the compilation task.
View Full Code Here

  public static boolean CompileFromMemory(String[] classNames, String[] codeContent, String[] compOptions) {
   
    List<String> compOptList = null;
    if (compOptions != null) { compOptList = Arrays.asList(compOptions); }
   
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();

    // Need to add a check that classNames.length == codeContent.length, else we're fubared.
    List<JavaFileObject> files = new ArrayList<JavaFileObject> () ;
    int i = 0;
    for (String codePage : codeContent) {
      files.add(new JavaSourceFromString(classNames[i], codePage));
      i++;
    }

    Iterable<? extends JavaFileObject> compilationUnits = files;
   
    JavaCompiler.CompilationTask task = compiler.getTask(null, null, null, compOptList, null, compilationUnits);
   
    boolean success = task.call();

    return success;
View Full Code Here

    args.add(jarOutDir);

    args.add("-classpath");
    args.add(curClasspath + File.pathSeparator + coreJar + sqoopJar);

    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    if (null == compiler) {
      LOG.error("It seems as though you are running sqoop with a JRE.");
      LOG.error("Sqoop requires a JDK that can compile Java code.");
      LOG.error("Please install a JDK and set $JAVA_HOME to use it.");
      throw new IOException("Could not start Java compiler.");
    }
    StandardJavaFileManager fileManager =
        compiler.getStandardFileManager(null, null, null);

    ArrayList<String> srcFileNames = new ArrayList<String>();
    for (String srcfile : sources) {
      srcFileNames.add(jarOutDir + srcfile);
      LOG.debug("Adding source file: " + jarOutDir + srcfile);
    }

    if (LOG.isDebugEnabled()) {
      LOG.debug("Invoking javac with args:");
      for (String arg : args) {
        LOG.debug("  " + arg);
      }
    }

    Iterable<? extends JavaFileObject> srcFileObjs =
        fileManager.getJavaFileObjectsFromStrings(srcFileNames);
    JavaCompiler.CompilationTask task = compiler.getTask(
        null, // Write to stderr
        fileManager,
        null, // No special diagnostic handling
        args,
        null, // Compile all classes in the source compilation units
View Full Code Here

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

        FileManager fileManager = ServletActionContext.getContext().getInstance(FileManagerFactory.class).getFileManager();

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

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

        for (URL url : urls) {
            URL normalizedUrl = fileManager.normalizeToFileProtocol(url);
            File file = FileUtils.toFile(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

    List<File> javaFiles = new ArrayList<File>();
    for (OutputFile o : outputs) {
      javaFiles.add(o.writeToDestination(null, dstDir));
    }

    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    StandardJavaFileManager fileManager =
      compiler.getStandardFileManager(null, null, null);
   
    CompilationTask cTask = compiler.getTask(null, fileManager, null, null,
        null,
        fileManager.getJavaFileObjects(
            javaFiles.toArray(new File[javaFiles.size()])));
    assertTrue(cTask.call());
  }
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.