Search in sources :

Example 6 with CompilationProblem

use of org.drools.compiler.commons.jci.problems.CompilationProblem 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)

Example 7 with CompilationProblem

use of org.drools.compiler.commons.jci.problems.CompilationProblem in project drools by kiegroup.

the class JaninoJavaCompiler method compile.

public CompilationResult compile(final String[] pSourceNames, final ResourceReader pResourceReader, final ResourceStore pStore, final ClassLoader pClassLoader, final JavaCompilerSettings pSettings) {
    final Collection problems = new ArrayList();
    final StringPattern[] pattern = StringPattern.PATTERNS_NONE;
    final Compiler compiler = new Compiler(new ResourceFinder() {

        public Resource findResource(final String pSourceName) {
            final byte[] bytes = pResourceReader.getBytes(pSourceName);
            if (bytes == null) {
                return null;
            }
            return new JciResource(pSourceName, bytes);
        }
    }, new ClassLoaderIClassLoader(pClassLoader), new ResourceFinder() {

        public Resource findResource(final String pResourceName) {
            final byte[] bytes = pStore.read(pResourceName);
            if (bytes == null) {
                return null;
            }
            return new JciResource(pResourceName, bytes);
        }
    }, new ResourceCreator() {

        public OutputStream createResource(final String pResourceName) throws IOException {
            return new JciOutputStream(pResourceName, pStore);
        }

        public boolean deleteResource(final String pResourceName) {
            pStore.remove(pResourceName);
            return true;
        }
    }, pSettings.getSourceEncoding(), false, pSettings.isDebug() ? DebuggingInformation.ALL : DebuggingInformation.NONE, new FilterWarningHandler(pattern, new WarningHandler() {

        public void handleWarning(final String pHandle, final String pMessage, final Location pLocation) {
            final CompilationProblem problem = new JaninoCompilationProblem(pLocation.getFileName(), pLocation, pMessage, false);
            if (problemHandler != null) {
                problemHandler.handle(problem);
            }
            problems.add(problem);
        }
    }));
    compiler.setCompileErrorHandler(new ErrorHandler() {

        public void handleError(final String pMessage, final Location pLocation) throws CompileException {
            final CompilationProblem problem = new JaninoCompilationProblem(pLocation.getFileName(), pLocation, pMessage, true);
            if (problemHandler != null) {
                problemHandler.handle(problem);
            }
            problems.add(problem);
        }
    });
    final Resource[] resources = new Resource[pSourceNames.length];
    for (int i = 0; i < pSourceNames.length; i++) {
        final byte[] source = pResourceReader.getBytes(pSourceNames[i]);
        resources[i] = new JciResource(pSourceNames[i], source);
    }
    try {
        compiler.compile(resources);
    } catch (ScanException e) {
        problems.add(new JaninoCompilationProblem(e));
    } catch (ParseException e) {
        problems.add(new JaninoCompilationProblem(e));
    } catch (IOException e) {
    // I'm hoping the existing compiler problems handler catches these
    } catch (CompileException e) {
    // I'm hoping the existing compiler problems handler catches these
    }
    final CompilationProblem[] result = new CompilationProblem[problems.size()];
    problems.toArray(result);
    return new CompilationResult(result);
}
Also used : OutputStream(java.io.OutputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) ArrayList(java.util.ArrayList) CompilationProblem(org.drools.compiler.commons.jci.problems.CompilationProblem) ScanException(org.codehaus.janino.Scanner.ScanException) CompileException(org.codehaus.janino.CompileException) StringPattern(org.codehaus.janino.util.StringPattern) Compiler(org.codehaus.janino.Compiler) ResourceFinder(org.codehaus.janino.util.resource.ResourceFinder) ErrorHandler(org.codehaus.janino.UnitCompiler.ErrorHandler) ResourceCreator(org.codehaus.janino.util.resource.ResourceCreator) WarningHandler(org.codehaus.janino.WarningHandler) FilterWarningHandler(org.codehaus.janino.FilterWarningHandler) Resource(org.codehaus.janino.util.resource.Resource) IOException(java.io.IOException) ClassLoaderIClassLoader(org.codehaus.janino.ClassLoaderIClassLoader) FilterWarningHandler(org.codehaus.janino.FilterWarningHandler) Collection(java.util.Collection) ParseException(org.codehaus.janino.Parser.ParseException) Location(org.codehaus.janino.Location)

Aggregations

CompilationProblem (org.drools.compiler.commons.jci.problems.CompilationProblem)7 CompilationResult (org.drools.compiler.commons.jci.compilers.CompilationResult)4 IOException (java.io.IOException)3 ArrayList (java.util.ArrayList)3 Collection (java.util.Collection)3 ByteArrayOutputStream (java.io.ByteArrayOutputStream)2 File (java.io.File)2 EclipseJavaCompiler (org.drools.compiler.commons.jci.compilers.EclipseJavaCompiler)2 JavaCompiler (org.drools.compiler.commons.jci.compilers.JavaCompiler)2 FileOutputStream (java.io.FileOutputStream)1 InputStream (java.io.InputStream)1 OutputStream (java.io.OutputStream)1 Map (java.util.Map)1 ZipFile (java.util.zip.ZipFile)1 ClassLoaderIClassLoader (org.codehaus.janino.ClassLoaderIClassLoader)1 CompileException (org.codehaus.janino.CompileException)1 Compiler (org.codehaus.janino.Compiler)1 FilterWarningHandler (org.codehaus.janino.FilterWarningHandler)1 Location (org.codehaus.janino.Location)1 ParseException (org.codehaus.janino.Parser.ParseException)1