Example usage for org.eclipse.jdt.internal.compiler Compiler Compiler

List of usage examples for org.eclipse.jdt.internal.compiler Compiler Compiler

Introduction

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

Prototype

public Compiler(INameEnvironment environment, IErrorHandlingPolicy policy, CompilerOptions options,
        final ICompilerRequestor requestor, IProblemFactory problemFactory) 

Source Link

Document

Answer a new compiler using the given name environment and compiler options.

Usage

From source file:br.com.objectos.code.JdtCompilerBuilderPojo.java

License:Apache License

@Override
public JdtCompiler build() {
    NameEnvironment environment = new NameEnvironment();
    IErrorHandlingPolicy policy = DefaultErrorHandlingPolicies.exitAfterAllProblems();
    CompilerOptions options = new CompilerOptions();
    options.set(optionMap.build());//  w ww  .j  a v  a  2  s.  c  om
    IProblemFactory problemFactory = ProblemFactory.getProblemFactory(Locale.getDefault());
    Compiler delegate = new Compiler(environment, policy, options, requestor, problemFactory);
    annotationProcessorManager.set(delegate);
    return new JdtCompiler(delegate);
}

From source file:com.mysema.codegen.ECJEvaluatorFactory.java

License:Apache License

protected void compile(String source, ClassType projectionType, String[] names, Type[] types, String id,
        Map<String, Object> constants) throws IOException {
    // create source
    source = createSource(source, projectionType, names, types, id, constants);

    // compile/*from   w w  w.  j av  a  2s  .c o  m*/
    final char[] targetContents = source.toCharArray();
    final String targetName = id;
    final ICompilationUnit[] targetCompilationUnits = new ICompilationUnit[] { new ICompilationUnit() {
        @Override
        public char[] getContents() {
            return targetContents;
        }

        @Override
        public char[] getMainTypeName() {
            int dot = targetName.lastIndexOf('.');
            if (dot > 0)
                return targetName.substring(dot + 1).toCharArray();
            else
                return targetName.toCharArray();
        }

        @Override
        public char[][] getPackageName() {
            StringTokenizer tok = new StringTokenizer(targetName, ".");
            char[][] result = new char[tok.countTokens() - 1][];
            for (int j = 0; j < result.length; j++) {
                result[j] = tok.nextToken().toCharArray();
            }
            return result;
        }

        @Override
        public char[] getFileName() {
            return CharOperation.concat(targetName.toCharArray(), ".java".toCharArray());
        }

        @Override
        public boolean ignoreOptionalProblems() {
            return true;
        }
    } };

    INameEnvironment env = new INameEnvironment() {

        private String join(char[][] compoundName, char separator) {
            if (compoundName == null) {
                return "";
            } else {
                List<String> parts = Lists.newArrayListWithCapacity(compoundName.length);
                for (char[] part : compoundName) {
                    parts.add(new String(part));
                }
                return Joiner.on(separator).join(parts);
            }
        }

        @Override
        public NameEnvironmentAnswer findType(char[][] compoundTypeName) {
            return findType(join(compoundTypeName, '.'));
        }

        @Override
        public NameEnvironmentAnswer findType(char[] typeName, char[][] packageName) {
            return findType(CharOperation.arrayConcat(packageName, typeName));
        }

        private boolean isClass(String result) {
            if (Strings.isNullOrEmpty(result)) {
                return false;
            }

            // if it's the class we're compiling, then of course it's a class
            if (result.equals(targetName)) {
                return true;
            }
            InputStream is = null;
            try {
                // if this is a class we've already compiled, it's a class
                is = loader.getResourceAsStream(result);
                if (is == null) {
                    // use our normal class loader now...
                    String resourceName = result.replace('.', '/') + ".class";
                    is = parentClassLoader.getResourceAsStream(resourceName);
                    if (is == null && !result.contains(".")) {
                        // we couldn't find the class, and it has no package; is it a core class?
                        is = parentClassLoader.getResourceAsStream("java/lang/" + resourceName);
                    }
                }
                return is != null;
            } finally {
                if (is != null) {
                    try {
                        is.close();
                    } catch (IOException ex) {
                    }
                }
            }
        }

        @Override
        public boolean isPackage(char[][] parentPackageName, char[] packageName) {
            // if the parent is a class, the child can't be a package
            String parent = join(parentPackageName, '.');
            if (isClass(parent))
                return false;

            // if the child is a class, it's not a package
            String qualifiedName = (parent.isEmpty() ? "" : parent + ".") + new String(packageName);
            return !isClass(qualifiedName);
        }

        @Override
        public void cleanup() {
        }

        private NameEnvironmentAnswer findType(String className) {
            String resourceName = className.replace('.', '/') + ".class";
            InputStream is = null;
            try {
                // we're only asking ECJ to compile a single class; we shouldn't need this
                if (className.equals(targetName)) {
                    return new NameEnvironmentAnswer(targetCompilationUnits[0], null);
                }

                is = loader.getResourceAsStream(resourceName);
                if (is == null) {
                    is = parentClassLoader.getResourceAsStream(resourceName);
                }

                if (is != null) {
                    ClassFileReader cfr = new ClassFileReader(ByteStreams.toByteArray(is),
                            className.toCharArray(), true);
                    return new NameEnvironmentAnswer(cfr, null);
                } else {
                    return null;
                }
            } catch (ClassFormatException ex) {
                throw new RuntimeException(ex);
            } catch (IOException e) {
                throw new RuntimeException(e);
            } finally {
                if (is != null) {
                    try {
                        is.close();
                    } catch (IOException e) {
                    }
                }
            }

        }
    };

    ICompilerRequestor requestor = new ICompilerRequestor() {

        @Override
        public void acceptResult(CompilationResult result) {
            if (result.hasErrors()) {
                for (CategorizedProblem problem : result.getProblems()) {
                    if (problem.isError()) {
                        problemList.add(problem.getMessage());
                    }
                }
            } else {
                for (ClassFile clazz : result.getClassFiles()) {
                    try {
                        MemJavaFileObject jfo = (MemJavaFileObject) fileManager.getJavaFileForOutput(
                                StandardLocation.CLASS_OUTPUT, new String(clazz.fileName()),
                                JavaFileObject.Kind.CLASS, null);
                        OutputStream os = jfo.openOutputStream();
                        os.write(clazz.getBytes());
                    } catch (IOException ex) {
                        throw new RuntimeException(ex);
                    }
                }
            }
        }
    };

    problemList.clear();

    IErrorHandlingPolicy policy = DefaultErrorHandlingPolicies.exitAfterAllProblems();
    IProblemFactory problemFactory = new DefaultProblemFactory(Locale.getDefault());

    try {
        //Compiler compiler = new Compiler(env, policy, getCompilerOptions(), requestor, problemFactory, true);
        Compiler compiler = new Compiler(env, policy, compilerOptions, requestor, problemFactory);
        compiler.compile(targetCompilationUnits);
        if (!problemList.isEmpty()) {
            StringBuilder sb = new StringBuilder();
            for (String problem : problemList) {
                sb.append("\t").append(problem).append("\n");
            }
            throw new CodegenException("Compilation of " + id + " failed:\n" + source + "\n" + sb.toString());
        }
    } catch (RuntimeException ex) {
        // if we encountered an IOException, unbox and throw it;
        // if we encountered a ClassFormatException, box it as an IOException and throw it
        // otherwise, it's a legit RuntimeException, 
        //    not one of our checked exceptions boxed as unchecked; just rethrow
        Throwable cause = ex.getCause();
        if (cause != null) {
            if (cause instanceof IOException) {
                throw (IOException) cause;
            } else if (cause instanceof ClassFormatException) {
                throw new IOException(cause);
            }
        }
        throw ex;
    }
}

From source file:com.opensymphony.webwork.util.classloader.compilers.eclipse.EclipseJavaCompiler.java

License:Apache License

public void compile(final String[] pClazzNames, final ResourceReader pReader, final ResourceStore pStore,
        final CompilationProblemHandler pProblemHandler) {

    final Map settingsMap = settings.getMap();
    final Set clazzIndex = new HashSet();
    ICompilationUnit[] compilationUnits = new ICompilationUnit[pClazzNames.length];
    for (int i = 0; i < compilationUnits.length; i++) {
        final String clazzName = pClazzNames[i];
        compilationUnits[i] = new CompilationUnit(pReader, clazzName);
        clazzIndex.add(clazzName);/* w  w w.  ja v a2s  . c o m*/
        log.debug("compiling " + clazzName);
    }

    final IErrorHandlingPolicy policy = DefaultErrorHandlingPolicies.proceedWithAllProblems();
    final IProblemFactory problemFactory = new DefaultProblemFactory(Locale.getDefault());
    final INameEnvironment nameEnvironment = new INameEnvironment() {

        public NameEnvironmentAnswer findType(final char[][] compoundTypeName) {
            final StringBuffer result = new StringBuffer();
            for (int i = 0; i < compoundTypeName.length; i++) {
                if (i != 0) {
                    result.append('.');
                }
                result.append(compoundTypeName[i]);
            }
            return findType(result.toString());
        }

        public NameEnvironmentAnswer findType(final char[] typeName, final char[][] packageName) {
            final StringBuffer result = new StringBuffer();
            for (int i = 0; i < packageName.length; i++) {
                result.append(packageName[i]);
                result.append('.');
            }
            result.append(typeName);
            return findType(result.toString());
        }

        private NameEnvironmentAnswer findType(final String clazzName) {
            byte[] clazzBytes = pStore.read(clazzName);
            if (clazzBytes != null) {
                // log.debug("loading from store " + clazzName);
                final char[] fileName = clazzName.toCharArray();
                try {
                    final ClassFileReader classFileReader = new ClassFileReader(clazzBytes, fileName, true);
                    return new NameEnvironmentAnswer(classFileReader, null);
                } catch (final ClassFormatException e) {
                    log.error("wrong class format", e);
                }
            } else {
                if (pReader.isAvailable(clazzName.replace('.', '/') + ".java")) {
                    log.debug("compile " + clazzName);
                    ICompilationUnit compilationUnit = new CompilationUnit(pReader, clazzName);
                    return new NameEnvironmentAnswer(compilationUnit, null);
                }

                final String resourceName = clazzName.replace('.', '/') + ".class";
                final InputStream is = this.getClass().getClassLoader().getResourceAsStream(resourceName);
                if (is != null) {
                    final byte[] buffer = new byte[8192];
                    final ByteArrayOutputStream baos = new ByteArrayOutputStream(buffer.length);
                    int count;
                    try {
                        while ((count = is.read(buffer, 0, buffer.length)) > 0) {
                            baos.write(buffer, 0, count);
                        }
                        baos.flush();
                        clazzBytes = baos.toByteArray();
                        final char[] fileName = clazzName.toCharArray();
                        ClassFileReader classFileReader = new ClassFileReader(clazzBytes, fileName, true);
                        return new NameEnvironmentAnswer(classFileReader, null);
                    } catch (final IOException e) {
                        log.error("could not read class", e);
                    } catch (final ClassFormatException e) {
                        log.error("wrong class format", e);
                    } finally {
                        try {
                            baos.close();
                        } catch (final IOException oe) {
                            log.error("could not close output stream", oe);
                        }
                        try {
                            is.close();
                        } catch (final IOException ie) {
                            log.error("could not close input stream", ie);
                        }
                    }
                }
            }
            return null;
        }

        private boolean isPackage(final String clazzName) {
            final String resourceName = clazzName.replace('.', '/') + ".class";
            final URL resource = this.getClass().getClassLoader().getResource(resourceName);
            return resource == null;
        }

        public boolean isPackage(char[][] parentPackageName, char[] packageName) {
            final StringBuffer result = new StringBuffer();
            if (parentPackageName != null) {
                for (int i = 0; i < parentPackageName.length; i++) {
                    if (i != 0) {
                        result.append('.');
                    }
                    result.append(parentPackageName[i]);
                }
            }
            if (Character.isUpperCase(packageName[0])) {
                return false;
            }
            if (parentPackageName != null && parentPackageName.length > 0) {
                result.append('.');
            }
            result.append(packageName);
            return isPackage(result.toString());
        }

        public void cleanup() {
        }
    };

    final ICompilerRequestor compilerRequestor = new ICompilerRequestor() {
        public void acceptResult(CompilationResult result) {
            if (result.hasProblems()) {
                if (pProblemHandler != null) {
                    final IProblem[] problems = result.getProblems();
                    for (int i = 0; i < problems.length; i++) {
                        final IProblem problem = problems[i];
                        pProblemHandler.handle(new EclipseCompilationProblem(problem));
                    }
                }
            }
            if (!result.hasErrors()) {
                final ClassFile[] clazzFiles = result.getClassFiles();
                for (int i = 0; i < clazzFiles.length; i++) {
                    final ClassFile clazzFile = clazzFiles[i];
                    final char[][] compoundName = clazzFile.getCompoundName();
                    final StringBuffer clazzName = new StringBuffer();
                    for (int j = 0; j < compoundName.length; j++) {
                        if (j != 0) {
                            clazzName.append('.');
                        }
                        clazzName.append(compoundName[j]);
                    }
                    pStore.write(clazzName.toString(), clazzFile.getBytes());
                }
            }
        }
    };

    pProblemHandler.onStart();

    try {

        final Compiler compiler = new Compiler(nameEnvironment, policy, settingsMap, compilerRequestor,
                problemFactory);

        compiler.compile(compilationUnits);

    } finally {
        pProblemHandler.onStop();
    }
}

From source file:com.tsc9526.monalisa.plugin.eclipse.jdt.JDTCompiler.java

License:Open Source License

public void compile(File java) {
    INameEnvironment nameEnvironment = new FileSystem(classPaths, new String[] { java.getAbsolutePath() },
            "UTF-8");

    Compiler jdtCompiler = new Compiler(nameEnvironment, policy, options, compilerRequestor, problemFactory);

    jdtCompiler.compile(new ICompilationUnit[] { new CompilationUnit(java) });
}

From source file:com.xqbase.compiler.eclipse.EclipseJavaCompiler.java

License:Open Source License

public CompilerResult performCompile(CompilerConfiguration config) throws CompilerException {

    // added by xqbase-compiler-eclipse
    if (config.getGeneratedSourcesDirectory() != null) {
        config.getGeneratedSourcesDirectory().mkdirs();
    }//from w  w  w. j  a v a  2  s.  co  m

    List<CompilerMessage> errors = new LinkedList<CompilerMessage>();

    List<String> classpathEntries = config.getClasspathEntries();

    URL[] urls = new URL[1 + classpathEntries.size()];

    int i = 0;

    try {
        urls[i++] = new File(config.getOutputLocation()).toURL();

        for (String entry : classpathEntries) {
            urls[i++] = new File(entry).toURL();
        }
    } catch (MalformedURLException e) {
        throw new CompilerException("Error while converting the classpath entries to URLs.", e);
    }

    ClassLoader classLoader = new URLClassLoader(urls);

    SourceCodeLocator sourceCodeLocator = new SourceCodeLocator(config.getSourceLocations());

    INameEnvironment env = new EclipseCompilerINameEnvironment(sourceCodeLocator, classLoader, errors);

    IErrorHandlingPolicy policy = DefaultErrorHandlingPolicies.proceedWithAllProblems();

    // ----------------------------------------------------------------------
    // Build settings from configuration
    // ----------------------------------------------------------------------

    Map<String, String> settings = new HashMap<String, String>();

    if (config.isDebug()) {
        settings.put(CompilerOptions.OPTION_LocalVariableAttribute, CompilerOptions.GENERATE);
        settings.put(CompilerOptions.OPTION_LineNumberAttribute, CompilerOptions.GENERATE);
        settings.put(CompilerOptions.OPTION_SourceFileAttribute, CompilerOptions.GENERATE);
    }

    if (!config.isShowWarnings()) {
        Map opts = new CompilerOptions().getMap();
        for (Object optKey : opts.keySet()) {
            if (opts.get(optKey).equals(CompilerOptions.WARNING)) {
                settings.put((String) optKey, CompilerOptions.IGNORE);
            }
        }
    }

    String sourceVersion = decodeVersion(config.getSourceVersion());

    if (sourceVersion != null) {
        settings.put(CompilerOptions.OPTION_Source, sourceVersion);
    }

    String targetVersion = decodeVersion(config.getTargetVersion());

    if (targetVersion != null) {
        settings.put(CompilerOptions.OPTION_TargetPlatform, targetVersion);

        if (config.isOptimize()) {
            settings.put(CompilerOptions.OPTION_Compliance, targetVersion);
        }
    }

    if (StringUtils.isNotEmpty(config.getSourceEncoding())) {
        settings.put(CompilerOptions.OPTION_Encoding, config.getSourceEncoding());
    }

    if (config.isShowDeprecation()) {
        settings.put(CompilerOptions.OPTION_ReportDeprecation, CompilerOptions.WARNING);
    } else {
        settings.put(CompilerOptions.OPTION_ReportDeprecation, CompilerOptions.IGNORE);
    }

    // ----------------------------------------------------------------------
    // Set Eclipse-specific options
    // ----------------------------------------------------------------------

    settings.put(CompilerOptions.OPTION_LineNumberAttribute, CompilerOptions.GENERATE);
    settings.put(CompilerOptions.OPTION_SourceFileAttribute, CompilerOptions.GENERATE);

    // compiler-specific extra options override anything else in the config object...
    Map<String, String> extras = config.getCustomCompilerArguments();
    if (extras != null && !extras.isEmpty()) {
        settings.putAll(extras);
    }

    if (settings.containsKey("-properties")) {
        initializeWarnings(settings.get("-properties"), settings);
        settings.remove("-properties");
    }

    IProblemFactory problemFactory = new DefaultProblemFactory(Locale.getDefault());

    ICompilerRequestor requestor = new EclipseCompilerICompilerRequestor(config.getOutputLocation(), errors);

    List<CompilationUnit> compilationUnits = new ArrayList<CompilationUnit>();

    for (String sourceRoot : config.getSourceLocations()) {
        Set<String> sources = getSourceFilesForSourceRoot(config, sourceRoot);

        for (String source : sources) {
            CompilationUnit unit = new CompilationUnit(source, makeClassName(source, sourceRoot), errors,
                    config.getSourceEncoding());

            compilationUnits.add(unit);
        }
    }

    // ----------------------------------------------------------------------
    // Compile!
    // ----------------------------------------------------------------------

    CompilerOptions options = new CompilerOptions(settings);
    Compiler compiler = new Compiler(env, policy, options, requestor, problemFactory);

    ICompilationUnit[] units = compilationUnits.toArray(new ICompilationUnit[compilationUnits.size()]);

    compiler.compile(units);

    CompilerResult compilerResult = new CompilerResult().compilerMessages(errors);

    for (CompilerMessage compilerMessage : errors) {
        if (compilerMessage.isError()) {
            compilerResult.setSuccess(false);
            continue;
        }
    }

    return compilerResult;
}

From source file:io.takari.maven.plugins.compile.jdt.CompilerJdt.java

License:Open Source License

@Override
public int compile() throws MojoExecutionException, IOException {
    Map<String, String> args = new HashMap<String, String>();
    // XXX figure out how to reuse source/target check from jdt
    // org.eclipse.jdt.internal.compiler.batch.Main.validateOptions(boolean)
    args.put(CompilerOptions.OPTION_TargetPlatform, getTarget()); // support 5/6/7 aliases
    args.put(CompilerOptions.OPTION_Compliance, getTarget()); // support 5/6/7 aliases
    args.put(CompilerOptions.OPTION_Source, getSource()); // support 5/6/7 aliases
    args.put(CompilerOptions.OPTION_ReportForbiddenReference, CompilerOptions.ERROR);
    Set<Debug> debug = getDebug();
    if (debug == null || debug.contains(Debug.all)) {
        args.put(CompilerOptions.OPTION_LocalVariableAttribute, CompilerOptions.GENERATE);
        args.put(CompilerOptions.OPTION_LineNumberAttribute, CompilerOptions.GENERATE);
        args.put(CompilerOptions.OPTION_SourceFileAttribute, CompilerOptions.GENERATE);
    } else if (debug.contains(Debug.none)) {
        args.put(CompilerOptions.OPTION_LocalVariableAttribute, CompilerOptions.DO_NOT_GENERATE);
        args.put(CompilerOptions.OPTION_LineNumberAttribute, CompilerOptions.DO_NOT_GENERATE);
        args.put(CompilerOptions.OPTION_SourceFileAttribute, CompilerOptions.DO_NOT_GENERATE);
    } else {//from  www  .ja v  a2  s  .c o  m
        args.put(CompilerOptions.OPTION_LocalVariableAttribute, CompilerOptions.DO_NOT_GENERATE);
        args.put(CompilerOptions.OPTION_LineNumberAttribute, CompilerOptions.DO_NOT_GENERATE);
        args.put(CompilerOptions.OPTION_SourceFileAttribute, CompilerOptions.DO_NOT_GENERATE);
        for (Debug keyword : debug) {
            switch (keyword) {
            case lines:
                args.put(CompilerOptions.OPTION_LineNumberAttribute, CompilerOptions.GENERATE);
                break;
            case source:
                args.put(CompilerOptions.OPTION_SourceFileAttribute, CompilerOptions.GENERATE);
                break;
            case vars:
                args.put(CompilerOptions.OPTION_LocalVariableAttribute, CompilerOptions.GENERATE);
                break;
            default:
                throw new IllegalArgumentException();
            }
        }
    }

    class _CompilerOptions extends CompilerOptions {
        public void setShowWarnings(boolean showWarnings) {
            if (showWarnings) {
                warningThreshold = IrritantSet.COMPILER_DEFAULT_WARNINGS;
            } else {
                warningThreshold = new IrritantSet(0);
            }
        }
    }
    _CompilerOptions compilerOptions = new _CompilerOptions();

    compilerOptions.set(args);
    compilerOptions.performMethodsFullRecovery = false;
    compilerOptions.performStatementsRecovery = false;
    compilerOptions.verbose = isVerbose();
    compilerOptions.suppressWarnings = true;
    compilerOptions.setShowWarnings(isShowWarnings());
    compilerOptions.docCommentSupport = true;

    if (isProcEscalate() && strategy instanceof IncrementalCompilationStrategy) {
        strategy.enqueueAllSources();
        strategy = new FullCompilationStrategy();
    }

    Classpath namingEnvironment = strategy.createClasspath();
    IErrorHandlingPolicy errorHandlingPolicy = DefaultErrorHandlingPolicies.exitAfterAllProblems();
    IProblemFactory problemFactory = ProblemFactory.getProblemFactory(Locale.getDefault());
    Compiler compiler = new Compiler(namingEnvironment, errorHandlingPolicy, compilerOptions, this,
            problemFactory);
    compiler.options.produceReferenceInfo = true;

    EclipseFileManager fileManager = null;
    try {
        if (!isProcNone()) {
            fileManager = new EclipseFileManager(null, getSourceEncoding());
            fileManager.setLocation(StandardLocation.ANNOTATION_PROCESSOR_PATH, dependencies);
            fileManager.setLocation(StandardLocation.CLASS_OUTPUT, Collections.singleton(getOutputDirectory()));
            fileManager.setLocation(StandardLocation.SOURCE_OUTPUT,
                    Collections.singleton(getGeneratedSourcesDirectory()));

            ProcessingEnvImpl processingEnv = new ProcessingEnvImpl(context, fileManager,
                    getAnnotationProcessorOptions(), compiler, this);

            compiler.annotationProcessorManager = new AnnotationProcessorManager(processingEnv, fileManager,
                    getAnnotationProcessors());
            compiler.options.storeAnnotations = true;
        }

        return strategy.compile(namingEnvironment, compiler);
    } finally {
        if (fileManager != null) {
            fileManager.flush();
            fileManager.close();
        }
    }
}

From source file:jetbrick.template.compiler.JdtCompiler.java

License:Open Source License

@Override
protected void generateJavaClass(JavaSource source) throws IOException {
    INameEnvironment env = new NameEnvironment(source);
    IErrorHandlingPolicy policy = DefaultErrorHandlingPolicies.proceedWithAllProblems();
    CompilerOptions options = getCompilerOptions();
    CompilerRequestor requestor = new CompilerRequestor();
    IProblemFactory problemFactory = new DefaultProblemFactory(Locale.getDefault());

    Compiler compiler = new Compiler(env, policy, options, requestor, problemFactory);
    compiler.compile(new ICompilationUnit[] { new CompilationUnit(source) });

    if (requestor.hasErrors()) {
        String sourceCode = source.getSourceCode();
        String[] sourceCodeLines = sourceCode.split("(\r\n|\r|\n)", -1);
        StringBuilder sb = new StringBuilder();
        sb.append("Compilation failed.");
        sb.append('\n');
        for (IProblem p : requestor.getErrors()) {
            sb.append(p.getMessage()).append('\n');
            int start = p.getSourceStart();
            int column = start; // default
            for (int i = start; i >= 0; i--) {
                char c = sourceCode.charAt(i);
                if (c == '\n' || c == '\r') {
                    column = start - i;/*from  ww w . j a va  2 s  .c om*/
                    break;
                }
            }
            sb.append(StringUtils.getPrettyError(sourceCodeLines, p.getSourceLineNumber(), column,
                    p.getSourceStart(), p.getSourceEnd(), 3));
        }
        sb.append(requestor.getErrors().length);
        sb.append(" error(s)\n");
        throw new CompileErrorException(sb.toString());
    }

    requestor.save(source.getOutputdir());
}

From source file:lombok.RunTestsViaEcj.java

License:Open Source License

@Override
public void transformCode(Collection<CompilerMessage> messages, StringWriter result, File file, String encoding,
        Map<String, String> formatPreferences) throws Throwable {
    final AtomicReference<CompilationResult> compilationResult_ = new AtomicReference<CompilationResult>();
    final AtomicReference<CompilationUnitDeclaration> compilationUnit_ = new AtomicReference<CompilationUnitDeclaration>();
    ICompilerRequestor bitbucketRequestor = new ICompilerRequestor() {
        @Override//w ww. j ava 2  s  .  c om
        public void acceptResult(CompilationResult result) {
            compilationResult_.set(result);
        }
    };

    String source = readFile(file);
    final CompilationUnit sourceUnit = new CompilationUnit(source.toCharArray(), file.getName(),
            encoding == null ? "UTF-8" : encoding);

    Compiler ecjCompiler = new Compiler(createFileSystem(file), ecjErrorHandlingPolicy(), ecjCompilerOptions(),
            bitbucketRequestor, new DefaultProblemFactory(Locale.ENGLISH)) {
        @Override
        protected synchronized void addCompilationUnit(ICompilationUnit inUnit,
                CompilationUnitDeclaration parsedUnit) {
            if (inUnit == sourceUnit)
                compilationUnit_.set(parsedUnit);
            super.addCompilationUnit(inUnit, parsedUnit);
        }
    };

    ecjCompiler.compile(new ICompilationUnit[] { sourceUnit });

    CompilationResult compilationResult = compilationResult_.get();
    CategorizedProblem[] problems = compilationResult.getAllProblems();

    if (problems != null)
        for (CategorizedProblem p : problems) {
            messages.add(new CompilerMessage(p.getSourceLineNumber(), p.getSourceStart(), p.isError(),
                    p.getMessage()));
        }

    CompilationUnitDeclaration cud = compilationUnit_.get();

    if (cud == null)
        result.append("---- NO CompilationUnit provided by ecj ----");
    else
        result.append(cud.toString());
}

From source file:ma.glasnost.orika.impl.generator.EclipseJdtCompiler.java

License:Apache License

public EclipseJdtCompiler(ClassLoader parentLoader) {
    this.byteCodeClassLoader = new ByteCodeClassLoader(parentLoader);
    this.formatter = ToolFactory.createCodeFormatter(getFormattingOptions());
    this.compilerNameEnvironment = new NameEnvironment(this.byteCodeClassLoader);
    this.compilerRequester = new CompilerRequestor();
    this.compiler = new Compiler(compilerNameEnvironment, DefaultErrorHandlingPolicies.proceedWithAllProblems(),
            getCompilerOptions(), compilerRequester, new DefaultProblemFactory(Locale.getDefault()));
}

From source file:net.sf.j2s.core.builder.AbstractImageBuilder.java

License:Open Source License

protected Compiler newCompiler() {
    // disable entire javadoc support if not interested in diagnostics
    Map projectOptions = this.javaBuilder.javaProject.getOptions(true);
    String option = (String) projectOptions.get(JavaCore.COMPILER_PB_INVALID_JAVADOC);
    if (option == null || option.equals(JavaCore.IGNORE)) { // TODO (frederic) see why option is null sometimes while running model tests!?
        option = (String) projectOptions.get(JavaCore.COMPILER_PB_MISSING_JAVADOC_TAGS);
        if (option == null || option.equals(JavaCore.IGNORE)) {
            option = (String) projectOptions.get(JavaCore.COMPILER_PB_MISSING_JAVADOC_COMMENTS);
            if (option == null || option.equals(JavaCore.IGNORE)) {
                option = (String) projectOptions.get(JavaCore.COMPILER_PB_UNUSED_IMPORT);
                if (option == null || option.equals(JavaCore.IGNORE)) { // Unused import need also to look inside javadoc comment
                    projectOptions.put(JavaCore.COMPILER_DOC_COMMENT_SUPPORT, JavaCore.DISABLED);
                }/*from w  w w  . ja v a2  s .c om*/
            }
        }
    }

    // called once when the builder is initialized... can override if needed
    CompilerOptions compilerOptions = new CompilerOptions(projectOptions);
    compilerOptions.performMethodsFullRecovery = true;
    compilerOptions.performStatementsRecovery = true;
    Compiler newCompiler = new Compiler(this.nameEnvironment,
            DefaultErrorHandlingPolicies.proceedWithAllProblems(), compilerOptions, this,
            ProblemFactory.getProblemFactory(Locale.getDefault()));
    CompilerOptions options = newCompiler.options;
    // temporary code to allow the compiler to revert to a single thread
    String setting = System.getProperty("jdt.compiler.useSingleThread"); //$NON-NLS-1$
    newCompiler.useSingleThread = setting != null && setting.equals("true"); //$NON-NLS-1$

    // enable the compiler reference info support
    options.produceReferenceInfo = true;

    if (options.complianceLevel >= ClassFileConstants.JDK1_6 && options.processAnnotations) {
        // support for Java 6 annotation processors
        initializeAnnotationProcessorManager(newCompiler);
    }

    return newCompiler;
}