Example usage for org.eclipse.jdt.internal.compiler.tool EclipseCompiler EclipseCompiler

List of usage examples for org.eclipse.jdt.internal.compiler.tool EclipseCompiler EclipseCompiler

Introduction

In this page you can find the example usage for org.eclipse.jdt.internal.compiler.tool EclipseCompiler EclipseCompiler.

Prototype

public EclipseCompiler() 

Source Link

Usage

From source file:cologne.eck.peafactory.peagen.FileCompiler.java

License:Open Source License

public void compile(String[] javaFileNames) {

    // get Compiler: package ecj-3.7.jar
    JavaCompiler compiler = new EclipseCompiler();// org.eclipse.jdt.internal.compiler.tool.EclipseCompiler

    // for compilation diagnostic message processing on compilation WARNING/ERROR
    MyDiagnosticListener c = new MyDiagnosticListener();

    StandardJavaFileManager fileManager = compiler.getStandardFileManager(c, null, PeaFactory.getCharset());

    // java files -> file objects
    Iterable<? extends JavaFileObject> fileObjects = fileManager.getJavaFileObjects(javaFileNames);

    try {//  ww w  .j  a v a 2  s  .c  o m
        JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager, c, null, null, fileObjects);
        task.call();
        fileManager.close();
    } catch (RuntimeException e) {
        System.err.println("FileCompiler: " + e.toString());
        e.printStackTrace();
    } catch (IOException e) {
        System.err.println("FileCompiler: Can not close StandardJavaFileManager " + e.toString());
        e.printStackTrace();
    }

    // JAR FILE SETTINGS.JAR:
    //
    // stream to write jar file:
    //
    /*      JarOutputStream jos = null;
          try {
             // create jar file with manifest         
             jos = new JarOutputStream(new FileOutputStream("Setting.jar"));
          } catch (FileNotFoundException e) {
             // TODO Auto-generated catch block
             e.printStackTrace();
          } catch (IOException e) {
             // TODO Auto-generated catch block
             e.printStackTrace();
          }
            
          //
          // Add class files to jar file
          //
               
          File source = new File("settings" + File.separator + "PeaSettings.class");
             BufferedInputStream in = null;
             try  {
    // cut "bin/" and replace File.sep with "/"
    JarEntry entry = null;
    if(source.getPath().startsWith("settings")
          || source.getPath().startsWith("start")){
       entry = new JarEntry( (source.getPath().replace(File.separator, "/") ));   
    } else {
       entry = new JarEntry( (source.getPath().substring(4, source.getPath().length())).replace(File.separator, "/") );   
    }
    entry.setTime(source.lastModified());
    jos.putNextEntry(entry);
    in = new BufferedInputStream(new FileInputStream(source));
     byte[] buffer = new byte[1024];
     while (true)  {
        int count = in.read(buffer);
        if (count == -1)  break;
        jos.write(buffer, 0, count);
     }
     jos.closeEntry();
             } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
             }  finally {
    if (in != null) {
       try {
          in.close();
       } catch (IOException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
       }
    }
             }
          if (jos != null) {
             try {
    jos.flush();
    jos.close();
             } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
             }
          } */
}

From source file:com.aionemu.commons.scripting.java.JavaCompiler.java

License:Open Source License

public JavaCompiler() {
    tool = new EclipseCompiler();
}

From source file:com.google.testing.compile.JavaSourcesSubjectFactoryTest.java

License:Apache License

@Test
public void compilesWithoutErrorWithEclipseCompiler() {
    assertAbout(javaSource()).that(JavaFileObjects.forResource(Resources.getResource("HelloWorld.java")))
            .withCompiler(new EclipseCompiler()).withCompilerOptions("-nowarn", "-1.6").compilesWithoutError();
}

From source file:com.l2jserver.service.game.scripting.impl.ecj.EclipseScriptCompiler.java

License:Open Source License

/**
 * Creates new instance of JavaCompilerImpl. If system compiler is not
 * available - throws RuntimeExcetion/*  w w w .j a  va2 s . c o  m*/
 * 
 * @throws RuntimeException
 *             if compiler is not available
 */
public EclipseScriptCompiler() {
    this.javaCompiler = new EclipseCompiler();

    if (javaCompiler == null) {
        if (ToolProvider.getSystemJavaCompiler() != null) {
            throw new RuntimeException(new InstantiationException("JavaCompiler is not aviable."));
        }
    }
}

From source file:com.mysema.query.apt.EclipseCompilationTest.java

License:Apache License

@Test
@Ignore/*  w  w w .j  av a 2s.  com*/
public void test() throws IOException {
    System.setProperty("jdt.compiler.useSingleThread", "true");
    // select classes
    List<String> classes = new ArrayList<String>();
    for (File file : new File(packagePath).listFiles()) {
        if (file.getName().endsWith(".java")) {
            classes.add(file.getPath());
        }
    }

    // prepare output
    File out = new File("target/out-eclipse");
    FileUtils.delete(out);
    if (!out.mkdirs()) {
        Assert.fail("Creation of " + out.getPath() + " failed");
    }

    String classPath = SimpleCompiler.getClassPath((URLClassLoader) getClass().getClassLoader());
    JavaCompiler compiler = new EclipseCompiler();
    List<String> options = new ArrayList<String>();
    options.add("-s");
    options.add("target/out-eclipse");
    options.add("-proc:only");
    options.add("-processor");
    options.add(QuerydslAnnotationProcessor.class.getName());
    options.add("-Aquerydsl.entityAccessors=true");
    options.add("-cp");
    options.add(classPath);
    options.add("-source");
    options.add("1.6");
    options.add("-verbose");
    options.addAll(classes);

    int compilationResult = compiler.run(null, System.out, System.err,
            options.toArray(new String[options.size()]));
    if (compilationResult == 0) {
        System.out.println("Compilation is successful");
    } else {
        Assert.fail("Compilation Failed");
    }

    File resultFile = new File("target/out-eclipse/com/mysema/query/eclipse/QSimpleEntity.java");
    assertTrue(resultFile.exists());
    String result = Files.toString(resultFile, Charsets.UTF_8);
    assertTrue(result.contains("NumberPath<java.math.BigDecimal> bigDecimalProp"));
    assertTrue(result.contains("NumberPath<Integer> integerProp"));
    assertTrue(result.contains("NumberPath<Integer> intProp"));
    assertTrue(result.contains("StringPath stringProp"));
}

From source file:com.querydsl.apt.EclipseCompilationTest.java

License:Apache License

@Test
@Ignore//from w  w  w  .j a  va 2 s  . co m
public void test() throws IOException {
    System.setProperty("jdt.compiler.useSingleThread", "true");
    // select classes
    List<String> classes = new ArrayList<String>();
    for (File file : new File(packagePath).listFiles()) {
        if (file.getName().endsWith(".java")) {
            classes.add(file.getPath());
        }
    }

    // prepare output
    File out = new File("target/out-eclipse");
    FileUtils.delete(out);
    if (!out.mkdirs()) {
        Assert.fail("Creation of " + out.getPath() + " failed");
    }

    String classPath = SimpleCompiler.getClassPath((URLClassLoader) getClass().getClassLoader());
    JavaCompiler compiler = new EclipseCompiler();
    List<String> options = new ArrayList<String>();
    options.add("-s");
    options.add("target/out-eclipse");
    options.add("-proc:only");
    options.add("-processor");
    options.add(QuerydslAnnotationProcessor.class.getName());
    options.add("-Aquerydsl.entityAccessors=true");
    options.add("-cp");
    options.add(classPath);
    options.add("-source");
    options.add("1.6");
    options.add("-verbose");
    options.addAll(classes);

    int compilationResult = compiler.run(null, System.out, System.err,
            options.toArray(new String[options.size()]));
    if (compilationResult == 0) {
        System.out.println("Compilation is successful");
    } else {
        Assert.fail("Compilation Failed");
    }

    File resultFile = new File("target/out-eclipse/com/querydsl/eclipse/QSimpleEntity.java");
    assertTrue(resultFile.exists());
    String result = Files.toString(resultFile, Charsets.UTF_8);
    assertTrue(result.contains("NumberPath<java.math.BigDecimal> bigDecimalProp"));
    assertTrue(result.contains("NumberPath<Integer> integerProp"));
    assertTrue(result.contains("NumberPath<Integer> intProp"));
    assertTrue(result.contains("StringPath stringProp"));
}

From source file:de.pavloff.spark4knime.jsnippet.JavaSnippetCompiler.java

License:Open Source License

/**
 * Creates a compilation task./*  www .j av a  2 s  . c o  m*/
 *
 * @param out a Writer for additional output from the compiler;
 * use System.err if null
 * @param digsCollector a diagnostic listener; if null use the compiler's
 * default method for reporting diagnostics
 * @return an object representing the compilation process
 * @throws IOException if temporary jar files cannot be created
 */
public CompilationTask getTask(final Writer out, final DiagnosticCollector<JavaFileObject> digsCollector)
        throws IOException {
    if (m_compiler == null) {
        m_compileArgs = new ArrayList<String>();
        File[] classpaths = m_snippet.getClassPath();
        if (classpaths != null && classpaths.length > 0) {
            m_compileArgs.add("-classpath");
            StringBuilder b = new StringBuilder();
            for (int i = 0; i < classpaths.length; i++) {
                if (i > 0) {
                    b.append(File.pathSeparatorChar);
                }
                b.append(classpaths[i]);
            }
            m_compileArgs.add(b.toString());
        }
        m_compileArgs.add("-source");
        m_compileArgs.add("1.7");
        m_compileArgs.add("-target");
        m_compileArgs.add("1.7");

        m_compiler = new EclipseCompiler();
    }
    StandardJavaFileManager stdFileMgr = m_compiler.getStandardFileManager(digsCollector, null, null);

    CompilationTask compileTask = m_compiler.getTask(out, stdFileMgr, digsCollector, m_compileArgs, null,
            m_snippet.getCompilationUnits());
    return compileTask;
}

From source file:io.smartspaces.workbench.language.java.EclipseJavaProgrammingLanguageCompiler.java

License:Apache License

@Override
public void compile(ProjectTaskContext context, File compilationBuildDirectory, List<File> classpath,
        List<File> compilationFiles, List<String> compilerOptions) {

    StandardJavaFileManager fileManager = null;
    try {//  w  w  w .  j  a  v a 2 s . c om
        JavaCompiler compiler = new EclipseCompiler();

        fileManager = compiler.getStandardFileManager(null, null, null);
        fileManager.setLocation(StandardLocation.CLASS_PATH, classpath);
        fileManager.setLocation(StandardLocation.CLASS_OUTPUT, Lists.newArrayList(compilationBuildDirectory));

        Iterable<? extends JavaFileObject> compilationUnits1 = fileManager
                .getJavaFileObjectsFromFiles(compilationFiles);

        Boolean success = compiler.getTask(null, fileManager, null, compilerOptions, null, compilationUnits1)
                .call();

        if (!success) {
            throw new SimpleSmartSpacesException("The Java compilation failed");
        }
    } catch (IOException e) {
        throw new SmartSpacesException("Error while compiling Java files", e);
    } finally {
        fileSupport.close(fileManager, false);
    }
}

From source file:net.gcolin.server.jsp.ecj.EcjCompiler.java

License:Apache License

@Override
protected JavaCompiler getJavaCompiler() {
    return new EclipseCompiler();
}

From source file:org.evosuite.testcarver.codegen.PostProcessor.java

License:Open Source License

/**
 * /*from ww w  .  ja  va 2  s.c  o  m*/
 * @param logs   logs of captured interaction
 * @param packages  package names associated with logs. Mapping logs.get(i) belongs to packages.get(i)
 * @throws IOException 
 */
public static void process(final List<CaptureLog> logs, final List<String> packages,
        final List<Class<?>[]> observedClasses) throws IOException {
    if (logs == null) {
        throw new NullPointerException("list of CaptureLogs must not be null");
    }

    if (packages == null) {
        throw new NullPointerException("list of package names associated with logs must not be null");
    }

    if (observedClasses == null) {
        throw new NullPointerException("list of classes to be observed must not be null");
    }

    final int size = logs.size();
    if (packages.size() != size || observedClasses.size() != size) {
        throw new IllegalArgumentException("given lists must have same size");
    }

    // create post-processing sources in os specific temp folder
    final File tempDir = new File(System.getProperty("java.io.tmpdir"),
            "postprocessing_" + System.currentTimeMillis());
    tempDir.mkdir();

    CaptureLog log;
    String packageName;
    Class<?>[] classes;

    String targetFolder;
    File targetFile;
    final StringBuilder testClassNameBuilder = new StringBuilder();
    String testClassName;

    for (int i = 0; i < size; i++) {
        //=============== prepare carved test for post-processing ================================================

        packageName = packages.get(i);
        targetFolder = packageName.replace(".", File.separator);
        classes = observedClasses.get(i);

        if (classes.length == 0) {
            throw new IllegalArgumentException("there must be at least one class to be observed");
        }

        //         for(int j = 0; j < classes.length; j++)
        //         {
        //            testClassNameBuilder.append(classes[j].getSimpleName());
        //            if(testClassNameBuilder.length() >= 10)
        //            {
        //               break;
        //            }
        //         }
        testClassNameBuilder.append("CarvedTest");

        log = logs.get(i);

        long s = System.currentTimeMillis();
        logger.debug(">>>> (postprocess) start test create ");

        targetFile = new File(tempDir, targetFolder);
        targetFile.mkdirs();
        testClassName = getFreeClassName(targetFile, testClassNameBuilder.toString());

        targetFile = new File(targetFile, testClassName + ".java");

        // write out test files containing post-processing statements
        writeTest(log, packageName, testClassName, classes, targetFile, true);

        logger.debug(">>>> (postprocess) end test creation -> " + (System.currentTimeMillis() - s) / 1000);

        //=============== compile generated post-processing test ================================================

        final JavaCompiler compiler = new EclipseCompiler();
        //         final JavaCompiler            compiler    = ToolProvider.getSystemJavaCompiler();
        final StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);

        Iterable<? extends JavaFileObject> compilationUnits = fileManager
                .getJavaFileObjectsFromFiles(Arrays.asList(new File[] { targetFile }));

        //--- add modified bins (see Transformer and ClassPreparer.createPreparedBin()) to class path
        String classPath = Configuration.INSTANCE.getProperty(Configuration.MODIFIED_BIN_LOC);
        classPath += File.pathSeparator + System.getProperty("java.class.path");

        final Boolean wasCompilationSuccess = compiler.getTask(null, fileManager, null,
                Arrays.asList(new String[] { "-cp", classPath }), null, compilationUnits).call();

        if (!wasCompilationSuccess) {

            logger.error("Compilation was not not successful for " + targetFile);
            fileManager.close();
            continue;
        }
        fileManager.close();

        //=============== execute + observe post-processing test run ================================================

        final PostProcessorClassLoader cl = new PostProcessorClassLoader(tempDir);

        final Class<?> testClass = cl.findClass(packageName + '.' + testClassName);

        BlockJUnit4ClassRunner testRunner;
        try {
            testRunner = new BlockJUnit4ClassRunner(testClass);
            testRunner.run(new RunNotifier());
        } catch (InitializationError e) {
            logger.error("" + e, e);
        }

        //============== generate final test file ================================================================

        final String targetDir = Configuration.INSTANCE.getProperty(Configuration.GEN_TESTS_LOC);
        targetFile = new File(new File(targetDir), targetFolder);
        targetFile.mkdirs();
        testClassName = getFreeClassName(targetFile, testClassNameBuilder.toString());
        targetFile = new File(targetFile, testClassName + ".java");
        writeTest(log, packageName, testClassName, classes, targetFile, false);

        // recycle StringBuilder for testClassName
        testClassNameBuilder.setLength(0);
    }

    // clean up post-processing stuff
    tempDir.delete();
}