Search in sources :

Example 11 with CompilerOptions

use of org.eclipse.jdt.internal.compiler.impl.CompilerOptions in project jetbrick-template-1x by subchen.

the class JdtCompiler method generateJavaClass.

@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();
            // default
            int column = start;
            for (int i = start; i >= 0; i--) {
                char c = sourceCode.charAt(i);
                if (c == '\n' || c == '\r') {
                    column = start - i;
                    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());
}
Also used : Compiler(org.eclipse.jdt.internal.compiler.Compiler) IProblem(org.eclipse.jdt.core.compiler.IProblem) CompilerOptions(org.eclipse.jdt.internal.compiler.impl.CompilerOptions) DefaultProblemFactory(org.eclipse.jdt.internal.compiler.problem.DefaultProblemFactory)

Example 12 with CompilerOptions

use of org.eclipse.jdt.internal.compiler.impl.CompilerOptions in project opennms by OpenNMS.

the class CustomJRJdtCompiler method getJdtSettings.

protected CompilerOptions getJdtSettings() {
    final Map<String, String> settings = new HashMap<String, String>();
    settings.put(CompilerOptions.OPTION_LineNumberAttribute, CompilerOptions.GENERATE);
    settings.put(CompilerOptions.OPTION_SourceFileAttribute, CompilerOptions.GENERATE);
    settings.put(CompilerOptions.OPTION_ReportDeprecation, CompilerOptions.IGNORE);
    List<JRPropertiesUtil.PropertySuffix> properties = JRPropertiesUtil.getInstance(jasperReportsContext).getProperties(JDT_PROPERTIES_PREFIX);
    for (Iterator<JRPropertiesUtil.PropertySuffix> it = properties.iterator(); it.hasNext(); ) {
        JRPropertiesUtil.PropertySuffix property = it.next();
        String propVal = property.getValue();
        if (propVal != null && propVal.length() > 0) {
            settings.put(property.getKey(), propVal);
        }
    }
    Properties systemProps = System.getProperties();
    for (@SuppressWarnings("unchecked") Enumeration<String> it = (Enumeration<String>) systemProps.propertyNames(); it.hasMoreElements(); ) {
        String propName = it.nextElement();
        if (propName.startsWith(JDT_PROPERTIES_PREFIX)) {
            String propVal = systemProps.getProperty(propName);
            if (propVal != null && propVal.length() > 0) {
                settings.put(propName, propVal);
            }
        }
    }
    return new CompilerOptions(settings);
}
Also used : Enumeration(java.util.Enumeration) HashMap(java.util.HashMap) Properties(java.util.Properties) JRPropertiesUtil(net.sf.jasperreports.engine.JRPropertiesUtil) CompilerOptions(org.eclipse.jdt.internal.compiler.impl.CompilerOptions)

Example 13 with CompilerOptions

use of org.eclipse.jdt.internal.compiler.impl.CompilerOptions in project opennms by OpenNMS.

the class CustomJRJdtCompiler method compileUnits.

@Override
protected String compileUnits(final JRCompilationUnit[] units, String classpath, File tempDirFile) {
    final INameEnvironment env = getNameEnvironment(units);
    final IErrorHandlingPolicy policy = DefaultErrorHandlingPolicies.proceedWithAllProblems();
    final CompilerOptions options = getJdtSettings();
    final IProblemFactory problemFactory = new DefaultProblemFactory(Locale.getDefault());
    final CompilerRequestor requestor = getCompilerRequestor(units);
    final Compiler compiler = new Compiler(env, policy, options, requestor, problemFactory);
    do {
        CompilationUnit[] compilationUnits = requestor.processCompilationUnits();
        compiler.compile(compilationUnits);
    } while (requestor.hasMissingMethods());
    requestor.processProblems();
    return requestor.getFormattedProblems();
}
Also used : IErrorHandlingPolicy(org.eclipse.jdt.internal.compiler.IErrorHandlingPolicy) JRCompilationUnit(net.sf.jasperreports.engine.design.JRCompilationUnit) ICompilationUnit(org.eclipse.jdt.internal.compiler.env.ICompilationUnit) JRAbstractJavaCompiler(net.sf.jasperreports.engine.design.JRAbstractJavaCompiler) Compiler(org.eclipse.jdt.internal.compiler.Compiler) ICompilerRequestor(org.eclipse.jdt.internal.compiler.ICompilerRequestor) CompilerOptions(org.eclipse.jdt.internal.compiler.impl.CompilerOptions) INameEnvironment(org.eclipse.jdt.internal.compiler.env.INameEnvironment) DefaultProblemFactory(org.eclipse.jdt.internal.compiler.problem.DefaultProblemFactory) IProblemFactory(org.eclipse.jdt.internal.compiler.IProblemFactory)

Example 14 with CompilerOptions

use of org.eclipse.jdt.internal.compiler.impl.CompilerOptions in project sling by apache.

the class EclipseJavaCompiler method compile.

/**
     * @see org.apache.sling.commons.compiler.JavaCompiler#compile(org.apache.sling.commons.compiler.CompilationUnit[], org.apache.sling.commons.compiler.Options)
     */
@Override
public CompilationResult compile(final CompilationUnit[] units, final Options compileOptions) {
    // make sure we have an options object (to avoid null checks all over the place)
    final Options options = (compileOptions != null ? compileOptions : EMPTY_OPTIONS);
    // get classloader and classloader writer
    final ClassLoaderWriter writer = this.getClassLoaderWriter(options);
    if (writer == null) {
        return new CompilationResultImpl("Class loader writer for compilation is not available.");
    }
    final ClassLoader loader = this.getClassLoader(options, writer);
    if (loader == null) {
        return new CompilationResultImpl("Class loader for compilation is not available.");
    }
    // check sources for compilation
    boolean needsCompilation = isForceCompilation(options);
    if (!needsCompilation) {
        for (final CompilationUnit unit : units) {
            if (this.isOutDated(unit, writer)) {
                needsCompilation = true;
                break;
            }
        }
    }
    if (!needsCompilation) {
        logger.debug("All source files are recent - no compilation required.");
        return new CompilationResultImpl(writer);
    }
    // delete old class files
    for (final CompilationUnit unit : units) {
        final String name = '/' + unit.getMainClassName().replace('.', '/') + ".class";
        writer.delete(name);
    }
    // create properties for the settings object
    final Map<String, String> props = new HashMap<>();
    if (options.isGenerateDebugInfo()) {
        props.put(CompilerOptions.OPTION_LocalVariableAttribute, "generate");
        props.put(CompilerOptions.OPTION_LineNumberAttribute, "generate");
        props.put(CompilerOptions.OPTION_SourceFileAttribute, "generate");
    }
    if (options.getSourceVersion() != null) {
        props.put(CompilerOptions.OPTION_Source, options.getSourceVersion());
        props.put(CompilerOptions.OPTION_Compliance, options.getSourceVersion());
    }
    if (options.getTargetVersion() != null) {
        props.put(CompilerOptions.OPTION_TargetPlatform, options.getTargetVersion());
    }
    props.put(CompilerOptions.OPTION_Encoding, "UTF8");
    // create the settings
    final CompilerOptions settings = new CompilerOptions(props);
    logger.debug("Compiling with settings {}.", settings);
    // create the result
    final CompilationResultImpl result = new CompilationResultImpl(isIgnoreWarnings(options), writer);
    // create the context
    final CompileContext context = new CompileContext(units, result, writer, loader);
    // create the compiler
    final org.eclipse.jdt.internal.compiler.Compiler compiler = new org.eclipse.jdt.internal.compiler.Compiler(context, this.policy, settings, context, this.problemFactory, null, null);
    // compile
    compiler.compile(context.getSourceUnits());
    return result;
}
Also used : CompilationUnit(org.apache.sling.commons.compiler.CompilationUnit) ICompilationUnit(org.eclipse.jdt.internal.compiler.env.ICompilationUnit) CompilerOptions(org.eclipse.jdt.internal.compiler.impl.CompilerOptions) Options(org.apache.sling.commons.compiler.Options) ClassLoaderWriter(org.apache.sling.commons.classloader.ClassLoaderWriter) JavaCompiler(org.apache.sling.commons.compiler.JavaCompiler) HashMap(java.util.HashMap) CompilerOptions(org.eclipse.jdt.internal.compiler.impl.CompilerOptions)

Example 15 with CompilerOptions

use of org.eclipse.jdt.internal.compiler.impl.CompilerOptions in project drools by kiegroup.

the class EclipseJavaCompiler method compile.

public org.drools.compiler.commons.jci.compilers.CompilationResult compile(final String[] pSourceFiles, final ResourceReader pReader, final ResourceStore pStore, final ClassLoader pClassLoader, final JavaCompilerSettings pSettings) {
    final Collection problems = new ArrayList();
    final ICompilationUnit[] compilationUnits = new ICompilationUnit[pSourceFiles.length];
    for (int i = 0; i < compilationUnits.length; i++) {
        final String sourceFile = pSourceFiles[i];
        if (pReader.isAvailable(sourceFile)) {
            compilationUnits[i] = new CompilationUnit(pReader, sourceFile);
        } else {
            // log.error("source not found " + sourceFile);
            final CompilationProblem problem = new CompilationProblem() {

                public int getEndColumn() {
                    return 0;
                }

                public int getEndLine() {
                    return 0;
                }

                public String getFileName() {
                    return sourceFile;
                }

                public String getMessage() {
                    return "Source " + sourceFile + " could not be found";
                }

                public int getStartColumn() {
                    return 0;
                }

                public int getStartLine() {
                    return 0;
                }

                public boolean isError() {
                    return true;
                }

                public String toString() {
                    return getMessage();
                }
            };
            if (problemHandler != null) {
                problemHandler.handle(problem);
            }
            problems.add(problem);
        }
    }
    if (problems.size() > 0) {
        final CompilationProblem[] result = new CompilationProblem[problems.size()];
        problems.toArray(result);
        return new org.drools.compiler.commons.jci.compilers.CompilationResult(result);
    }
    final IErrorHandlingPolicy policy = DefaultErrorHandlingPolicies.proceedWithAllProblems();
    final IProblemFactory problemFactory = new DefaultProblemFactory(Locale.getDefault());
    final INameEnvironment nameEnvironment = new INameEnvironment() {

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

        public NameEnvironmentAnswer findType(final char[] pTypeName, final char[][] pPackageName) {
            final StringBuilder result = new StringBuilder();
            for (int i = 0; i < pPackageName.length; i++) {
                result.append(pPackageName[i]);
                result.append('.');
            }
            // log.debug("finding typeName=" + new String(typeName) + " packageName=" + result.toString());
            result.append(pTypeName);
            return findType(result.toString());
        }

        private NameEnvironmentAnswer findType(final String pClazzName) {
            final String resourceName = ClassUtils.convertClassToResourcePath(pClazzName);
            final byte[] clazzBytes = pStore.read(resourceName);
            if (clazzBytes != null) {
                try {
                    return createNameEnvironmentAnswer(pClazzName, clazzBytes);
                } catch (final ClassFormatException e) {
                    throw new RuntimeException("ClassFormatException in loading class '" + pClazzName + "' with JCI.");
                }
            }
            InputStream is = null;
            ByteArrayOutputStream baos = null;
            try {
                is = pClassLoader.getResourceAsStream(resourceName);
                if (is == null) {
                    return null;
                }
                if (ClassUtils.isWindows() || ClassUtils.isOSX()) {
                    // check it really is a class, this issue is due to windows case sensitivity issues for the class org.kie.Process and path org/droosl/process
                    try {
                        pClassLoader.loadClass(pClazzName);
                    } catch (ClassNotFoundException e) {
                        return null;
                    } catch (NoClassDefFoundError e) {
                        return null;
                    }
                }
                final byte[] buffer = new byte[8192];
                baos = new ByteArrayOutputStream(buffer.length);
                int count;
                while ((count = is.read(buffer, 0, buffer.length)) > 0) {
                    baos.write(buffer, 0, count);
                }
                baos.flush();
                return createNameEnvironmentAnswer(pClazzName, baos.toByteArray());
            } catch (final IOException e) {
                throw new RuntimeException("could not read class", e);
            } catch (final ClassFormatException e) {
                throw new RuntimeException("wrong class format", e);
            } finally {
                try {
                    if (baos != null) {
                        baos.close();
                    }
                } catch (final IOException oe) {
                    throw new RuntimeException("could not close output stream", oe);
                }
                try {
                    if (is != null) {
                        is.close();
                    }
                } catch (final IOException ie) {
                    throw new RuntimeException("could not close input stream", ie);
                }
            }
        }

        private NameEnvironmentAnswer createNameEnvironmentAnswer(final String pClazzName, final byte[] clazzBytes) throws ClassFormatException {
            final char[] fileName = pClazzName.toCharArray();
            final ClassFileReader classFileReader = new ClassFileReader(clazzBytes, fileName, true);
            return new NameEnvironmentAnswer(classFileReader, null);
        }

        private boolean isSourceAvailable(final String pClazzName, final ResourceReader pReader) {
            // FIXME: this should not be tied to the extension
            final String javaSource = pClazzName.replace('.', '/') + ".java";
            final String classSource = pClazzName.replace('.', '/') + ".class";
            return pReader.isAvailable(prefix + javaSource) || pReader.isAvailable(prefix + classSource);
        }

        private boolean isPackage(final String pClazzName) {
            InputStream is = null;
            try {
                is = pClassLoader.getResourceAsStream(ClassUtils.convertClassToResourcePath(pClazzName));
                if (is != null) {
                    if (ClassUtils.isWindows() || ClassUtils.isOSX()) {
                        try {
                            Class cls = pClassLoader.loadClass(pClazzName);
                            if (cls != null) {
                                return false;
                            }
                        } catch (ClassNotFoundException e) {
                            return true;
                        } catch (NoClassDefFoundError e) {
                            return true;
                        }
                    }
                }
                boolean result = is == null && !isSourceAvailable(pClazzName, pReader);
                return result;
            } finally {
                if (is != null) {
                    try {
                        is.close();
                    } catch (IOException e) {
                        throw new RuntimeException("Unable to close stream for resource: " + pClazzName);
                    }
                }
            }
        }

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

        public void cleanup() {
        }
    };
    final ICompilerRequestor compilerRequestor = new ICompilerRequestor() {

        public void acceptResult(final CompilationResult pResult) {
            if (pResult.hasProblems()) {
                final IProblem[] iproblems = pResult.getProblems();
                for (int i = 0; i < iproblems.length; i++) {
                    final IProblem iproblem = iproblems[i];
                    final CompilationProblem problem = new EclipseCompilationProblem(iproblem);
                    if (problemHandler != null) {
                        problemHandler.handle(problem);
                    }
                    problems.add(problem);
                }
            }
            if (!pResult.hasErrors()) {
                final ClassFile[] clazzFiles = pResult.getClassFiles();
                for (int i = 0; i < clazzFiles.length; i++) {
                    final ClassFile clazzFile = clazzFiles[i];
                    final char[][] compoundName = clazzFile.getCompoundName();
                    final StringBuilder clazzName = new StringBuilder();
                    for (int j = 0; j < compoundName.length; j++) {
                        if (j != 0) {
                            clazzName.append('.');
                        }
                        clazzName.append(compoundName[j]);
                    }
                    pStore.write(clazzName.toString().replace('.', '/') + ".class", clazzFile.getBytes());
                }
            }
        }
    };
    final Map settingsMap = new EclipseJavaCompilerSettings(pSettings).toNativeSettings();
    CompilerOptions compilerOptions = new CompilerOptions(settingsMap);
    compilerOptions.parseLiteralExpressionsAsConstants = false;
    final Compiler compiler = new Compiler(nameEnvironment, policy, compilerOptions, compilerRequestor, problemFactory);
    if (ClassGenerator.DUMP_GENERATED_CLASSES) {
        dumpUnits(compilationUnits, pReader);
    }
    compiler.compile(compilationUnits);
    final CompilationProblem[] result = new CompilationProblem[problems.size()];
    problems.toArray(result);
    return new org.drools.compiler.commons.jci.compilers.CompilationResult(result);
}
Also used : IErrorHandlingPolicy(org.eclipse.jdt.internal.compiler.IErrorHandlingPolicy) ResourceReader(org.drools.compiler.commons.jci.readers.ResourceReader) NameEnvironmentAnswer(org.eclipse.jdt.internal.compiler.env.NameEnvironmentAnswer) ClassFileReader(org.eclipse.jdt.internal.compiler.classfmt.ClassFileReader) ArrayList(java.util.ArrayList) CompilationProblem(org.drools.compiler.commons.jci.problems.CompilationProblem) ClassFormatException(org.eclipse.jdt.internal.compiler.classfmt.ClassFormatException) INameEnvironment(org.eclipse.jdt.internal.compiler.env.INameEnvironment) DefaultProblemFactory(org.eclipse.jdt.internal.compiler.problem.DefaultProblemFactory) IProblemFactory(org.eclipse.jdt.internal.compiler.IProblemFactory) ICompilationUnit(org.eclipse.jdt.internal.compiler.env.ICompilationUnit) ICompilationUnit(org.eclipse.jdt.internal.compiler.env.ICompilationUnit) Compiler(org.eclipse.jdt.internal.compiler.Compiler) ClassFile(org.eclipse.jdt.internal.compiler.ClassFile) ICompilerRequestor(org.eclipse.jdt.internal.compiler.ICompilerRequestor) InputStream(java.io.InputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) IProblem(org.eclipse.jdt.core.compiler.IProblem) CompilerOptions(org.eclipse.jdt.internal.compiler.impl.CompilerOptions) Collection(java.util.Collection) CompilationResult(org.eclipse.jdt.internal.compiler.CompilationResult) Map(java.util.Map)

Aggregations

CompilerOptions (org.eclipse.jdt.internal.compiler.impl.CompilerOptions)15 DefaultProblemFactory (org.eclipse.jdt.internal.compiler.problem.DefaultProblemFactory)7 HashMap (java.util.HashMap)6 Compiler (org.eclipse.jdt.internal.compiler.Compiler)4 IProblemFactory (org.eclipse.jdt.internal.compiler.IProblemFactory)4 ICompilationUnit (org.eclipse.jdt.internal.compiler.env.ICompilationUnit)4 IOException (java.io.IOException)3 Map (java.util.Map)3 IProblem (org.eclipse.jdt.core.compiler.IProblem)3 CompilationResult (org.eclipse.jdt.internal.compiler.CompilationResult)3 ICompilerRequestor (org.eclipse.jdt.internal.compiler.ICompilerRequestor)3 IErrorHandlingPolicy (org.eclipse.jdt.internal.compiler.IErrorHandlingPolicy)3 CompilationUnitDeclaration (org.eclipse.jdt.internal.compiler.ast.CompilationUnitDeclaration)3 INameEnvironment (org.eclipse.jdt.internal.compiler.env.INameEnvironment)3 ByteArrayOutputStream (java.io.ByteArrayOutputStream)2 InputStream (java.io.InputStream)2 ArrayList (java.util.ArrayList)2 IJavaProject (org.eclipse.jdt.core.IJavaProject)2 CategorizedProblem (org.eclipse.jdt.core.compiler.CategorizedProblem)2 ClassFile (org.eclipse.jdt.internal.compiler.ClassFile)2