Package javax.tools

Examples of javax.tools.JavaCompiler


    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


  }

  private void compile(List<File> sourceFiles) throws Exception {
    List<String> options = createJavaOptions();

    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
    StandardJavaFileManager fileManager = compiler.getStandardFileManager( diagnostics, null, null );
    Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjectsFromFiles(
        sourceFiles
    );

    compileSources( options, compiler, diagnostics, fileManager, compilationUnits );
View Full Code Here

    options.add(compileTargetDir.getAbsolutePath());
    for (CompilerOptionsProvider cop : compilerOptionsProviders) {
      options.addAll(cop.getOptions());
    }
    logger.info("Compiler options: "+options.toString());
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    if (compiler == null) throw new NullPointerException("No java compiler available! Did you start from a JDK? JRE will not work.");
    StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
    final Map<String,File> files = new HashMap<String,File>();
    try {
      final StringWriter sw = new StringWriter();
      sw.append("Compilation failed!\n");
      for (String dir : sourceDirs) {
        files.putAll(findFiles(new File(dir), ".java"));
      }
      files.putAll(findFiles(additionalSourcesDir,".java"));
      if (files.size() > 0) {
        final Iterable<? extends JavaFileObject> compilationUnits1 = fileManager.getJavaFileObjectsFromFiles(files.values());
        final CompilationTask task = compiler.getTask(sw, fileManager, null, options, null, compilationUnits1);
        if (!task.call()) {
          logger.error(sw.toString());
          throw new CopperRuntimeException("Compilation failed, see logfile for details");
        }
      }
View Full Code Here

      System.out.println("wrote file: " + sourceFile.getAbsolutePath());

      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

  }

  public byte[] compile(JavaFileObject javaObject, Iterable<Class<?>> classPaths) {
    long startMillis = System.currentTimeMillis();
    log.debug("Compile '{}'", javaObject.getName());
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    JavaMemoryManager manager = new JavaMemoryManager(compiler.getStandardFileManager(null, null, null));
    Iterable<JavaFileObject> javaObjects = Arrays.asList(javaObject);
    List<String> options = new ArrayList<String>();

    if (classPaths != null) {
      options.add("-cp");
      String classPath = buildClassPath(classPaths);
      options.add(classPath);
    }

    CompilationTask task = compiler.getTask(null, manager, null, options, null, javaObjects);
    if (!task.call()) { // compile error
      log.error("Compilation error");
      throw new RuntimeException("Compilation error");
    }
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>();

        //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

    return s;
  }

  protected void compileClass(String className, String s, Directory targetDir)
  {
    JavaCompiler jc = ToolProvider.getSystemJavaCompiler();
    if (jc == null)
    {
      throw new FileSystemException("No java compiler in the current Java. This must be run on a JDK rather on a JRE");
    }

    JavaFileManager fm = new TestClassFileManager<JavaFileManager>(jc.getStandardFileManager(null, null, null), targetDir, Thread.currentThread().getContextClassLoader());

    if (!jc.getTask(null, fm, null, null, null, Collections.singletonList(new JavaSourceFromString(className, s))).call().booleanValue())
    {
      System.out.println(s);
      fail();
    }
  }
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(fileManager, 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

    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 compileJavaFiles(String classpath, File webInf, File jspClassDir,
      ApplicationProcessingOptions opts) throws IOException {

    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    if (compiler == null) {
      throw new RuntimeException(
          "Cannot get the System Java Compiler. Please use a JDK, not a JRE.");
    }
    StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);

    ArrayList<File> files = new ArrayList<File>();
    for (File f : new FileIterator(jspClassDir)) {
      if (f.getPath().toLowerCase().endsWith(".java")) {
        files.add(f);
      }
    }
    if (files.isEmpty()) {
      return;
    }
    List<String> optionList = new ArrayList<String>();
    optionList.addAll(Arrays.asList("-classpath", classpath.toString()));
    optionList.addAll(Arrays.asList("-d", jspClassDir.getPath()));
    optionList.addAll(Arrays.asList("-encoding", opts.getCompileEncoding()));

    Iterable<? extends JavaFileObject> compilationUnits =
        fileManager.getJavaFileObjectsFromFiles(files);
    boolean success = compiler.getTask(
        null, fileManager, null, optionList, null, compilationUnits).call();
    fileManager.close();

    if (!success) {
      throw new JspCompilationException("Failed to compile the generated JSP java files.",
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.