Example usage for org.eclipse.jdt.core.compiler.batch BatchCompiler compile

List of usage examples for org.eclipse.jdt.core.compiler.batch BatchCompiler compile

Introduction

In this page you can find the example usage for org.eclipse.jdt.core.compiler.batch BatchCompiler compile.

Prototype

public static boolean compile(String[] commandLineArguments, PrintWriter outWriter, PrintWriter errWriter,
        CompilationProgress progress) 

Source Link

Document

Invokes the Eclipse Compiler for Java with the given command line arguments, using the given writers to print messages, and reporting progress to the given compilation progress.

Usage

From source file:abs.backend.java.codegeneration.JavaCompiler.java

License:Open Source License

public static boolean compile(String args) throws JavaCodeGenerationException {
    StringWriter outWriter = new StringWriter();
    StringWriter errWriter = new StringWriter();
    boolean res = BatchCompiler.compile(DEFAULT_PREFIX + args, new PrintWriter(outWriter),
            new PrintWriter(errWriter), null);
    if (!res) {//w ww  .  ja va2  s  .  c o  m
        String errorString = errWriter.toString();
        throw new JavaCodeGenerationException("There seems to be a bug in the ABS Java backend. "
                + "The generated code contains errors:\n" + errorString);
    }
    return res;
}

From source file:com.google.appinventor.buildserver.util.AARLibraries.java

License:Open Source License

/**
 * Writes out the R.class files for all of the ARR libraries as well as an R.class file for the
 * main app being compiled./*  w  ww.  jav a2 s .  com*/
 *
 * @param outputDir the output directory to write the R.class files to.
 * @param appPackageName The package name of the currently compiling app.
 * @param appRTxt The app's R.txt file containing a list of resources.
 * @return 0 if the operation completes successfully, or 1 if an error occurs.
 * @throws IOException if the program is unable to read any R.txt files or write R.java or
 *                     R.class files
 * @throws InterruptedException if the compiler thread is interrupted.
 */
public int writeRClasses(File outputDir, String appPackageName, File appRTxt)
        throws IOException, InterruptedException {
    this.outputDir = outputDir;
    SymbolLoader baseSymbolTable = new SymbolLoader(appRTxt, LOG);
    baseSymbolTable.load();

    // aggregate symbols into one writer per package
    Map<String, SymbolWriter> writers = new HashMap<>();
    for (String packageName : symbols.keys()) {
        Collection<SymbolLoader> loaders = symbols.get(packageName);
        SymbolWriter writer = new SymbolWriter(generated, packageName, baseSymbolTable);
        for (SymbolLoader loader : loaders) {
            writer.addSymbolsToWrite(loader);
        }
        writers.put(packageName, writer);
        writer.write();
    }

    // construct compiler command line
    List<String> args = new ArrayList<>();
    args.add("-1.7");
    args.add("-d");
    args.add(outputDir.getAbsolutePath());
    args.add(generated);

    // compile R classes using ECJ batch compiler
    PrintWriter out = new PrintWriter(System.out);
    PrintWriter err = new PrintWriter(System.err);
    if (BatchCompiler.compile(args.toArray(new String[0]), out, err, new NOPCompilationProgress())) {
        return 0;
    } else {
        return 1;
    }
}

From source file:com.liferay.mobile.sdk.core.MobileSDKBuilder.java

License:Open Source License

private static boolean compile(String sourceDir, String destDir) throws IOException {
    final List<String> args = new ArrayList<String>();

    args.add("-cp");

    final String jsonPath = libPath("jars/org.json_20131018.0.0.jar");
    final String sdkPath = libPath("jars/liferay-android-sdk-6.2.0.1.jar");

    args.add(jsonPath + File.pathSeparatorChar + sdkPath);

    args.add("-1.6");

    args.add("-d");
    args.add(destDir);/* w ww. ja  v  a 2s  . c o m*/

    args.add(sourceDir);

    final CompilationProgress progress = new CompilationProgress() {
        public void begin(int remainingWork) {
        }

        public void done() {
        }

        public boolean isCanceled() {
            return false;
        }

        public void setTaskName(String name) {
        }

        public void worked(int workIncrement, int remainingWork) {
        }
    };

    return BatchCompiler.compile(args.toArray(new String[0]), new PrintWriter(System.out),
            new PrintWriter(System.err), progress);
}

From source file:de.ovgu.featureide.ui.actions.generator.Compiler.java

License:Open Source License

private String process(AbstractList<String> command) {
    final StringBuilder sb = new StringBuilder();
    for (String string : command) {
        sb.append(string);/*from w  w w. j  a v a2s.  co m*/
        sb.append(' ');
    }

    String output = null;
    try (StringWriter writer = new StringWriter()) {
        BatchCompiler.compile(sb.toString(), new PrintWriter(System.out), new PrintWriter(writer), null);
        output = writer.toString();
    } catch (IOException e) {
        UIPlugin.getDefault().logError(e);
    }
    return output;
}

From source file:de.ovgu.featureide.ui.actions.generator.JavaCompiler.java

License:Open Source License

private String process(AbstractList<String> command) {
    final StringBuilder sb = new StringBuilder();
    for (String string : command) {
        sb.append(string);/*from ww  w .  jav  a  2 s. com*/
        sb.append(' ');
    }

    String output = null;
    try (StringWriter writer = new StringWriter()) {
        final String params = sb.toString();

        BatchCompiler.compile(params, new PrintWriter(System.out), new PrintWriter(writer), null);
        output = writer.toString();
    } catch (IOException e) {
        UIPlugin.getDefault().logError(e);
    }
    return output;
}

From source file:io.sarl.lang.compiler.batch.SarlBatchCompiler.java

License:Apache License

/** Run the Java compiler.
 *
 * @param classDirectory the output directory.
 * @param sourcePathDirectories the source directories.
 * @param classPathEntries classpath entries.
 * @param enableCompilerOutput indicates if the Java compiler output is displayed.
 * @param cancelIndicator monitor for cancelling the compilation.
 * @return the success status. Replies <code>false</code> if the activity is cancelled.
 *///  w w  w .  j  a  v a 2  s .c  o m
@SuppressWarnings({ "checkstyle:npathcomplexity", "checkstyle:cyclomaticcomplexity", "resource" })
protected boolean runJavaCompiler(File classDirectory, Iterable<File> sourcePathDirectories,
        Iterable<File> classPathEntries, boolean enableCompilerOutput, CancelIndicator cancelIndicator) {
    assert cancelIndicator != null;
    final List<String> commandLine = Lists.newArrayList();
    commandLine.add("-nowarn"); //$NON-NLS-1$
    if (isJavaCompilerVerbose()) {
        commandLine.add("-verbose"); //$NON-NLS-1$
    }
    if (cancelIndicator.isCanceled()) {
        return false;
    }
    final List<File> bootClassPathEntries = getBootClassPath();
    if (cancelIndicator.isCanceled()) {
        return false;
    }
    if (!bootClassPathEntries.isEmpty()) {
        final StringBuilder cmd = new StringBuilder("-bootclasspath \""); //$NON-NLS-1$
        boolean first = true;
        for (final File entry : bootClassPathEntries) {
            if (cancelIndicator.isCanceled()) {
                return false;
            }
            if (first) {
                first = false;
            } else {
                cmd.append(File.pathSeparator);
            }
            cmd.append(entry.getAbsolutePath());
        }
        cmd.append("\""); //$NON-NLS-1$
        commandLine.add(cmd.toString());
    }
    final Iterator<File> classPathIterator = classPathEntries.iterator();
    if (classPathIterator.hasNext()) {
        final StringBuilder cmd = new StringBuilder("-cp \""); //$NON-NLS-1$
        boolean first = true;
        while (classPathIterator.hasNext()) {
            if (cancelIndicator.isCanceled()) {
                return false;
            }
            if (first) {
                first = false;
            } else {
                cmd.append(File.pathSeparator);
            }
            cmd.append(classPathIterator.next().getAbsolutePath());
        }
        cmd.append("\""); //$NON-NLS-1$
        commandLine.add(cmd.toString());
    }
    if (cancelIndicator.isCanceled()) {
        return false;
    }
    commandLine.add("-d \"" + classDirectory.getAbsolutePath() + "\""); //$NON-NLS-1$ //$NON-NLS-2$
    commandLine.add("-" + getJavaSourceVersion()); //$NON-NLS-1$
    commandLine.add("-proceedOnError"); //$NON-NLS-1$
    if (this.encodingProvider.getDefaultEncoding() != null) {
        commandLine.add("-encoding \"" + this.encodingProvider.getDefaultEncoding() + "\""); //$NON-NLS-1$ //$NON-NLS-2$
    }
    if (cancelIndicator.isCanceled()) {
        return false;
    }

    final StringBuilder cmd = new StringBuilder();
    boolean first = true;
    for (final File sourceFolder : sourcePathDirectories) {
        if (cancelIndicator.isCanceled()) {
            return false;
        }
        if (first) {
            first = false;
        } else {
            cmd.append(" "); //$NON-NLS-1$
        }
        cmd.append("\""); //$NON-NLS-1$
        cmd.append(sourceFolder.getAbsolutePath().replaceAll(Pattern.quote("\""), "\\\"")); //$NON-NLS-1$//$NON-NLS-2$
        cmd.append("\""); //$NON-NLS-1$
    }
    commandLine.add(cmd.toString());

    if (this.logger.isDebugEnabled()) {
        this.logger.debug(MessageFormat.format(Messages.SarlBatchCompiler_6, Strings.concat(" ", commandLine))); //$NON-NLS-1$
    }

    if (cancelIndicator.isCanceled()) {
        return false;
    }

    final PrintWriter outWriter = getStubCompilerOutputWriter();
    final PrintWriter errWriter;
    if (enableCompilerOutput) {
        errWriter = getErrorCompilerOutputWriter();
    } else {
        errWriter = getStubCompilerOutputWriter();
    }
    if (cancelIndicator.isCanceled()) {
        return false;
    }
    return BatchCompiler.compile(Strings.concat(" ", commandLine), outWriter, errWriter, //$NON-NLS-1$
            new CancelIndicatorWrapper(cancelIndicator));
}

From source file:org.absmodels.abs.plugin.actions.JavaJob.java

License:Open Source License

/**
 * generates .class files (needs .java files)
 * @param monitor /*  w w  w.  ja v a 2  s  .c  om*/
 * 
 * @param absFrontendLocation -where to find the absfrontend
 * @param path - directory with java files
 * @param noWarnings - do not show any compile warnings
 * @throws AbsJobException 
 */
private void generateJavaClassFiles(IProgressMonitor monitor, String absFrontendLocation, File path,
        boolean noWarnings) throws AbsJobException {
    monitor.subTask("Creating class files");

    //args
    String noWarn;
    if (noWarnings) {
        noWarn = "-nowarn";
    } else {
        noWarn = "";
    }
    if (!path.isDirectory() || !path.isAbsolute()) {
        if (debugMode)
            System.err.println("Not a absolute path of a directory: " + path.getAbsolutePath());
        throw new AbsJobException("Path is not an absolute path of a directory");
    }
    String args = "-1.5 " + noWarn + " -classpath " + "\"" + absFrontendLocation + "\"" + " " + "\""
            + path.getAbsolutePath() + "\"";
    if (debugMode)
        System.out.println("arguments: " + args);

    //console
    try {
        ConsoleManager.displayConsoleView();
    } catch (PartInitException e) {
        standardExceptionHandling(e);
        throw new AbsJobException("Not able to show console");
    }

    //compile with jdt-BatchCompiler
    CompilationProgress progress = null;
    OutputStream os = javaConsole.getOutputStream(ConsoleManager.MessageType.MESSAGE_ERROR);
    boolean compilationSuccessful = BatchCompiler.compile(args, new PrintWriter(os), new PrintWriter(os),
            progress);
    if (!compilationSuccessful) {
        throw new AbsJobException("Sorry, there seems to be a bug in the java backend. The generated java "
                + "files could not be compiled correctly.");
    }
}

From source file:org.eclipse.pde.api.tools.model.tests.TestSuiteHelper.java

License:Open Source License

/**
 * Compiles a single source file//  w  ww .ja v a  2s.co  m
 * 
 * @param sourcename
 * @param destinationpath
 * @param compileroptions
 * @return true if compilation succeeded false otherwise
 */
public static boolean compile(String sourcename, String destinationpath, String[] compileroptions) {
    StringWriter out = new StringWriter();
    PrintWriter outWriter = new PrintWriter(out);
    StringWriter err = new StringWriter();
    PrintWriter errWriter = new PrintWriter(err);
    List<String> cmd = new ArrayList<String>();
    cmd.add("-noExit"); //$NON-NLS-1$
    for (int i = 0, max = compileroptions.length; i < max; i++) {
        cmd.add(compileroptions[i]);
    }
    if (destinationpath != null) {
        cmd.add("-d"); //$NON-NLS-1$
        cmd.add(destinationpath);
    }
    cmd.add(sourcename);

    String[] args = new String[cmd.size()];
    cmd.toArray(args);
    boolean result = false;
    try {
        result = BatchCompiler.compile(args, outWriter, errWriter, null);
    } catch (RuntimeException e) {
        e.printStackTrace();
    }
    if (!result) {
        System.err.println(err.getBuffer());
    }
    return result;
}

From source file:org.eclipse.pde.api.tools.model.tests.TestSuiteHelper.java

License:Open Source License

/**
 * Compiles all source files in the specified source paths to the specified
 * destination path, with the given compiler options
 * //w  ww  .j av  a 2 s  . c  o  m
 * @param sourceFilePaths
 * @param destinationPath
 * @param compilerOptions
 * @return true if the compilation succeeded false otherwise
 */
public static boolean compile(String[] sourceFilePaths, String destinationPath, String[] compilerOptions) {
    StringWriter out = new StringWriter();
    PrintWriter outWriter = new PrintWriter(out);
    StringWriter err = new StringWriter();
    PrintWriter errWriter = new PrintWriter(err);
    List<String> cmd = new ArrayList<String>();
    cmd.add("-noExit"); //$NON-NLS-1$
    for (int i = 0, max = compilerOptions.length; i < max; i++) {
        cmd.add(compilerOptions[i]);
    }
    if (destinationPath != null) {
        cmd.add("-d"); //$NON-NLS-1$
        cmd.add(destinationPath);
    }
    Set<String> directories = new HashSet<String>();
    for (int i = 0, max = sourceFilePaths.length; i < max; i++) {
        String sourceFilePath = sourceFilePaths[i];
        File file = new File(sourceFilePath);
        if (!file.exists()) {
            continue;
        }
        if (file.isDirectory()) {
            directories.add(file.getAbsolutePath());
        } else {
            File parent = file.getParentFile();
            directories.add(parent.getAbsolutePath());
        }
        cmd.add(sourceFilePath);
    }
    // add all directories as classpath entries
    if (!directories.isEmpty()) {
        StringBuffer classpathEntry = new StringBuffer();
        int length = directories.size();
        int counter = 0;
        for (Iterator<String> iterator = directories.iterator(); iterator.hasNext();) {
            String path = iterator.next();
            classpathEntry.append(path);
            if (counter < length - 1) {
                classpathEntry.append(File.pathSeparatorChar);
            }
        }
        cmd.add("-classpath"); //$NON-NLS-1$
        cmd.add(String.valueOf(classpathEntry));
    }
    String[] args = new String[cmd.size()];
    cmd.toArray(args);
    boolean result = false;
    try {
        result = BatchCompiler.compile(args, outWriter, errWriter, null);
    } catch (RuntimeException e) {
        e.printStackTrace();
    }
    if (!result) {
        System.err.println(err.getBuffer());
    }
    return result;
}

From source file:org.eclipse.swt.tools.builders.Check64CompilationParticipant.java

License:Open Source License

void build(IJavaProject project, String root) throws CoreException {
    PrintWriter writer = null;//from  w w  w  .  java  2 s .c o m
    try {
        StringBuffer sourcePath = new StringBuffer(), cp = new StringBuffer();
        IClasspathEntry[] entries = project.getResolvedClasspath(true);
        for (int i = 0; i < entries.length; i++) {
            IClasspathEntry entry = entries[i];
            String path = entry.getPath().toPortableString();
            if (entry.getEntryKind() == IClasspathEntry.CPE_SOURCE) {
                if (path.startsWith(pluginDir)) {
                    if (sourcePath.length() > 0)
                        sourcePath.append(File.pathSeparatorChar);
                    String dir = root + path.substring(pluginDir.length());
                    sourcePath.append(dir);
                }
            } else {
                if (cp.length() > 0)
                    cp.append(File.pathSeparator);
                cp.append(path);
            }
        }
        String bin = root + "/bin";
        if (cp.length() > 0)
            cp.append(File.pathSeparator);
        cp.append(bin);
        ArrayList<String> args = new ArrayList<String>();
        args.addAll(Arrays.asList(new String[] { "-nowarn", "-1.5",
                //         "-verbose",
                "-d", bin, "-cp", cp.toString(), "-log", root + "/log.xml", "-sourcepath",
                sourcePath.toString(), }));
        args.addAll(sources);
        writer = new PrintWriter(new BufferedOutputStream(new FileOutputStream(root + "/out.txt")));
        BatchCompiler.compile(args.toArray(new String[args.size()]), writer, writer, null);
        writer.close();
        writer = null;
        project.getProject().findMember(new Path(buildDir)).refreshLocal(IResource.DEPTH_INFINITE, null);
    } catch (Exception e) {
        throw new CoreException(
                new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Problem building 64-bit code", e));
    } finally {
        if (writer != null)
            writer.close();
    }
}