Example usage for org.eclipse.jdt.internal.compiler.env INameEnvironment INameEnvironment

List of usage examples for org.eclipse.jdt.internal.compiler.env INameEnvironment INameEnvironment

Introduction

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

Prototype

INameEnvironment

Source Link

Usage

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/*  w  w w .  j  av a 2 s .  c  om*/
    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);//from  w  ww . j av  a2  s.  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:net.sf.jasperreports.engine.design.JRJdtCompiler.java

License:LGPL

protected INameEnvironment getNameEnvironment(final JRCompilationUnit[] units) {
    final INameEnvironment env = new INameEnvironment() {
        public NameEnvironmentAnswer findType(char[][] compoundTypeName) {
            StringBuffer result = new StringBuffer();
            String sep = "";
            for (int i = 0; i < compoundTypeName.length; i++) {
                result.append(sep);/*from  ww  w  . j  a  v  a2  s.co  m*/
                result.append(compoundTypeName[i]);
                sep = ".";
            }
            return findType(result.toString());
        }

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

        private int getClassIndex(String className) {
            int classIdx;
            for (classIdx = 0; classIdx < units.length; ++classIdx) {
                if (className.equals(units[classIdx].getName())) {
                    break;
                }
            }

            if (classIdx >= units.length) {
                classIdx = -1;
            }

            return classIdx;
        }

        private NameEnvironmentAnswer findType(String className) {
            try {
                int classIdx = getClassIndex(className);

                if (classIdx >= 0) {
                    ICompilationUnit compilationUnit = new CompilationUnit(units[classIdx].getSourceCode(),
                            className);
                    if (is2ArgsConstr) {
                        return (NameEnvironmentAnswer) constrNameEnvAnsCompUnit2Args
                                .newInstance(new Object[] { compilationUnit, null });
                    }

                    return (NameEnvironmentAnswer) constrNameEnvAnsCompUnit
                            .newInstance(new Object[] { compilationUnit });
                }

                String resourceName = className.replace('.', '/') + ".class";
                InputStream is = getResource(resourceName);
                if (is != null) {
                    byte[] classBytes;
                    byte[] buf = new byte[8192];
                    ByteArrayOutputStream baos = new ByteArrayOutputStream(buf.length);
                    int count;
                    while ((count = is.read(buf, 0, buf.length)) > 0) {
                        baos.write(buf, 0, count);
                    }
                    baos.flush();
                    classBytes = baos.toByteArray();
                    char[] fileName = className.toCharArray();
                    ClassFileReader classFileReader = new ClassFileReader(classBytes, fileName, true);

                    if (is2ArgsConstr) {
                        return (NameEnvironmentAnswer) constrNameEnvAnsBin2Args
                                .newInstance(new Object[] { classFileReader, null });
                    }

                    return (NameEnvironmentAnswer) constrNameEnvAnsBin
                            .newInstance(new Object[] { classFileReader });
                }
            } catch (IOException exc) {
                log.error("Compilation error", exc);
            } catch (org.eclipse.jdt.internal.compiler.classfmt.ClassFormatException exc) {
                log.error("Compilation error", exc);
            } catch (InvocationTargetException e) {
                throw new JRRuntimeException("Not able to create NameEnvironmentAnswer", e);
            } catch (IllegalArgumentException e) {
                throw new JRRuntimeException("Not able to create NameEnvironmentAnswer", e);
            } catch (InstantiationException e) {
                throw new JRRuntimeException("Not able to create NameEnvironmentAnswer", e);
            } catch (IllegalAccessException e) {
                throw new JRRuntimeException("Not able to create NameEnvironmentAnswer", e);
            }
            return null;
        }

        private boolean isPackage(String result) {
            int classIdx = getClassIndex(result);
            if (classIdx >= 0) {
                return false;
            }

            String resourceName = result.replace('.', '/') + ".class";

            boolean isPackage = true;

            InputStream is = getResource(resourceName);

            if (is != null)// cannot just test for null; need to read from "is" to avoid bug 
            { // with sun.plugin.cache.EmptyInputStream on JRE 1.5 plugin
                try // http://sourceforge.net/tracker/index.php?func=detail&aid=1478460&group_id=36382&atid=416703
                {
                    isPackage = (is.read() > 0);
                } catch (IOException e) {
                    //ignore
                } finally {
                    try {
                        is.close();
                    } catch (IOException e) {
                        //ignore
                    }
                }
            }

            return isPackage;
        }

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

        public void cleanup() {
        }

    };

    return env;
}

From source file:org.apache.cocoon.components.language.programming.java.EclipseJavaCompiler.java

License:Apache License

public boolean compile() throws IOException {
    final String targetClassName = makeClassName(sourceFile);
    final ClassLoader classLoader = ClassUtils.getClassLoader();
    String[] fileNames = new String[] { sourceFile };
    String[] classNames = new String[] { targetClassName };
    class CompilationUnit implements ICompilationUnit {

        String className;/*  ww w  .  j a v a  2s . c  o  m*/
        String sourceFile;

        CompilationUnit(String sourceFile, String className) {
            this.className = className;
            this.sourceFile = sourceFile;
        }

        public char[] getFileName() {
            return className.toCharArray();
        }

        public char[] getContents() {
            char[] result = null;
            FileReader fr = null;
            try {
                fr = new FileReader(sourceFile);
                Reader reader = new BufferedReader(fr);
                if (reader != null) {
                    char[] chars = new char[8192];
                    StringBuffer buf = new StringBuffer();
                    int count;
                    while ((count = reader.read(chars, 0, chars.length)) > 0) {
                        buf.append(chars, 0, count);
                    }
                    result = new char[buf.length()];
                    buf.getChars(0, result.length, result, 0);
                }
            } catch (IOException e) {
                handleError(className, -1, -1, e.getMessage());
            }
            return result;
        }

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

        public char[][] getPackageName() {
            StringTokenizer izer = new StringTokenizer(className, ".");
            char[][] result = new char[izer.countTokens() - 1][];
            for (int i = 0; i < result.length; i++) {
                String tok = izer.nextToken();
                result[i] = tok.toCharArray();
            }
            return result;
        }
    }

    final INameEnvironment env = new INameEnvironment() {

        public NameEnvironmentAnswer findType(char[][] compoundTypeName) {
            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(char[] typeName, char[][] packageName) {
            StringBuffer result = new StringBuffer();
            for (int i = 0; i < packageName.length; i++) {
                if (i > 0) {
                    result.append(".");
                }
                result.append(packageName[i]);
            }
            result.append(".");
            result.append(typeName);
            return findType(result.toString());
        }

        private NameEnvironmentAnswer findType(String className) {

            try {
                if (className.equals(targetClassName)) {
                    ICompilationUnit compilationUnit = new CompilationUnit(sourceFile, className);
                    return new NameEnvironmentAnswer(compilationUnit);
                }
                String resourceName = className.replace('.', '/') + ".class";
                InputStream is = classLoader.getResourceAsStream(resourceName);
                if (is != null) {
                    byte[] classBytes;
                    byte[] buf = new byte[8192];
                    ByteArrayOutputStream baos = new ByteArrayOutputStream(buf.length);
                    int count;
                    while ((count = is.read(buf, 0, buf.length)) > 0) {
                        baos.write(buf, 0, count);
                    }
                    baos.flush();
                    classBytes = baos.toByteArray();
                    char[] fileName = className.toCharArray();
                    ClassFileReader classFileReader = new ClassFileReader(classBytes, fileName, true);
                    return new NameEnvironmentAnswer(classFileReader);
                }
            } catch (IOException exc) {
                handleError(className, -1, -1, exc.getMessage());
            } catch (org.eclipse.jdt.internal.compiler.classfmt.ClassFormatException exc) {
                handleError(className, -1, -1, exc.getMessage());
            }
            return null;
        }

        private boolean isPackage(String result) {
            if (result.equals(targetClassName)) {
                return false;
            }
            String resourceName = result.replace('.', '/') + ".class";
            InputStream is = classLoader.getResourceAsStream(resourceName);
            return is == null;
        }

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

        public void cleanup() {
            // EMPTY
        }
    };
    final IErrorHandlingPolicy policy = DefaultErrorHandlingPolicies.proceedWithAllProblems();
    final Map settings = new HashMap(9);
    settings.put(CompilerOptions.OPTION_LineNumberAttribute, CompilerOptions.GENERATE);
    settings.put(CompilerOptions.OPTION_SourceFileAttribute, CompilerOptions.GENERATE);
    settings.put(CompilerOptions.OPTION_ReportDeprecation, CompilerOptions.IGNORE);
    settings.put(CompilerOptions.OPTION_ReportUnusedImport, CompilerOptions.IGNORE);
    if (sourceEncoding != null) {
        settings.put(CompilerOptions.OPTION_Encoding, sourceEncoding);
    }
    if (debug) {
        settings.put(CompilerOptions.OPTION_LocalVariableAttribute, CompilerOptions.GENERATE);
    }
    // Set the sourceCodeVersion
    switch (this.compilerComplianceLevel) {
    case 150:
        settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_5);
        settings.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_1_5);
        break;
    case 140:
        settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_4);
        break;
    default:
        settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_3);
    }
    // Set the target platform
    switch (SystemUtils.JAVA_VERSION_INT) {
    case 150:
        settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_5);
        break;
    case 140:
        settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_4);
        break;
    default:
        settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_3);
    }
    final IProblemFactory problemFactory = new DefaultProblemFactory(Locale.getDefault());

    final ICompilerRequestor requestor = new ICompilerRequestor() {
        public void acceptResult(CompilationResult result) {
            try {
                if (result.hasErrors()) {
                    IProblem[] errors = result.getErrors();
                    for (int i = 0; i < errors.length; i++) {
                        IProblem error = errors[i];
                        String name = new String(errors[i].getOriginatingFileName());
                        handleError(name, error.getSourceLineNumber(), -1, error.getMessage());
                    }
                } else {
                    ClassFile[] classFiles = result.getClassFiles();
                    for (int i = 0; i < classFiles.length; i++) {
                        ClassFile classFile = classFiles[i];
                        char[][] compoundName = classFile.getCompoundName();
                        StringBuffer className = new StringBuffer();
                        for (int j = 0; j < compoundName.length; j++) {
                            if (j > 0) {
                                className.append(".");
                            }
                            className.append(compoundName[j]);
                        }
                        byte[] bytes = classFile.getBytes();
                        String outFile = destDir + "/" + className.toString().replace('.', '/') + ".class";
                        FileOutputStream fout = new FileOutputStream(outFile);
                        BufferedOutputStream bos = new BufferedOutputStream(fout);
                        bos.write(bytes);
                        bos.close();
                    }
                }
            } catch (IOException exc) {
                exc.printStackTrace();
            }
        }
    };
    ICompilationUnit[] compilationUnits = new ICompilationUnit[classNames.length];
    for (int i = 0; i < compilationUnits.length; i++) {
        String className = classNames[i];
        compilationUnits[i] = new CompilationUnit(fileNames[i], className);
    }
    Compiler compiler = new Compiler(env, policy, settings, requestor, problemFactory);
    compiler.compile(compilationUnits);
    return errors.size() == 0;
}

From source file:org.apache.commons.jci.compilers.EclipseJavaCompiler.java

License:Apache License

public org.apache.commons.jci.compilers.CompilationResult compile(final String[] pSourceFiles,
        final ResourceReader pReader, final ResourceStore pStore, final ClassLoader pClassLoader,
        final JavaCompilerSettings pSettings) {

    final Map<String, String> settingsMap = new EclipseJavaCompilerSettings(pSettings).toNativeSettings();

    final Collection<CompilationProblem> problems = new ArrayList<CompilationProblem>();

    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);
            log.debug("compiling " + sourceFile);
        } else {//ww w. java 2 s  .com
            // 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;
                }

                @Override
                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.apache.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]);
            }

            //log.debug("finding compoundTypeName=" + result.toString());

            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) {

            if (isPackage(pClazzName)) {
                return null;
            }

            log.debug("finding " + pClazzName);

            final String resourceName = ConversionUtils.convertClassToResourcePath(pClazzName);

            final byte[] clazzBytes = pStore.read(resourceName);
            if (clazzBytes != null) {
                log.debug("loading from store " + pClazzName);

                final char[] fileName = pClazzName.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);
                    return null;
                }
            }

            log.debug("not in store " + pClazzName);

            final InputStream is = pClassLoader.getResourceAsStream(resourceName);
            if (is == null) {
                log.debug("class " + pClazzName + " not found");
                return 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();
                final char[] fileName = pClazzName.toCharArray();
                final ClassFileReader classFileReader = new ClassFileReader(baos.toByteArray(), fileName, true);
                return new NameEnvironmentAnswer(classFileReader, null);
            } catch (final IOException e) {
                log.error("could not read class", e);
                return null;
            } catch (final ClassFormatException e) {
                log.error("wrong class format", e);
                return null;
            } 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);
                }
            }
        }

        private boolean isPackage(final String pClazzName) {

            // reject this early as it is cheap
            if (pClazzName.contains("-")) { // "-" is not valid in package names
                return false;
            }

            final InputStream is = pClassLoader
                    .getResourceAsStream(ConversionUtils.convertClassToResourcePath(pClazzName));
            if (is != null) {
                log.debug("found the class for " + pClazzName + "- no package");
                try {
                    is.close();
                } catch (final IOException ie) {
                    log.error("could not close input stream", ie);
                }
                return false;
            }

            // FIXME: this should not be tied to the extension
            final String source = pClazzName.replace('.', '/') + ".java";
            if (pReader.isAvailable(source)) {
                log.debug("found the source " + source + " for " + pClazzName + " - no package ");
                return false;
            }

            /*
             * See https://issues.apache.org/jira/browse/JCI-59
             * At present, the code assumes that anything else is a package name
             * This is wrong, as for example jci.AdditionalTopLevel is not a package name.
             * It's not clear how to fix this in general.
             * It would seem to need access to the input classpath and/or the generated classes.
             */
            return true;
        }

        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]);
                }
            }

            //                log.debug("isPackage parentPackageName=" + result.toString() + " packageName=" + new String(packageName));

            if (parentPackageName != null && parentPackageName.length > 0) {
                result.append('.');
            }
            result.append(pPackageName);
            return isPackage(result.toString());
        }

        public void cleanup() {
            log.debug("cleanup");
        }
    };

    final ICompilerRequestor compilerRequestor = new ICompilerRequestor() {
        public void acceptResult(final CompilationResult pResult) {
            if (pResult.hasProblems()) {
                for (IProblem iproblem : pResult.getProblems()) {
                    final CompilationProblem problem = new EclipseCompilationProblem(iproblem);
                    if (problemHandler != null) {
                        problemHandler.handle(problem);
                    }
                    problems.add(problem);
                }
            }
            if (!pResult.hasErrors()) {
                final ClassFile[] clazzFiles = pResult.getClassFiles();
                for (ClassFile clazzFile : clazzFiles) {
                    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 Compiler compiler = new Compiler(nameEnvironment, policy, new CompilerOptions(settingsMap),
            compilerRequestor, problemFactory);

    compiler.compile(compilationUnits);

    final CompilationProblem[] result = new CompilationProblem[problems.size()];
    problems.toArray(result);
    return new org.apache.commons.jci.compilers.CompilationResult(result);
}

From source file:org.apache.jasper.compiler.JDTCompiler.java

License:Apache License

/** 
 * Compile the servlet from .java file to .class file
 *///  www .j a  v  a2s .  c  o m
@Override
protected void generateClass(String[] smap) throws FileNotFoundException, JasperException, Exception {

    long t1 = 0;
    if (log.isDebugEnabled()) {
        t1 = System.currentTimeMillis();
    }

    final String sourceFile = ctxt.getServletJavaFileName();
    final String outputDir = ctxt.getOptions().getScratchDir().getAbsolutePath();
    String packageName = ctxt.getServletPackageName();
    final String targetClassName = ((packageName.length() != 0) ? (packageName + ".") : "")
            + ctxt.getServletClassName();
    final ClassLoader classLoader = ctxt.getJspLoader();
    String[] fileNames = new String[] { sourceFile };
    String[] classNames = new String[] { targetClassName };
    final ArrayList<JavacErrorDetail> problemList = new ArrayList<JavacErrorDetail>();

    class CompilationUnit implements ICompilationUnit {

        private final String className;
        private final String sourceFile;

        CompilationUnit(String sourceFile, String className) {
            this.className = className;
            this.sourceFile = sourceFile;
        }

        @Override
        public char[] getFileName() {
            return sourceFile.toCharArray();
        }

        @Override
        public char[] getContents() {
            char[] result = null;
            FileInputStream is = null;
            InputStreamReader isr = null;
            Reader reader = null;
            try {
                is = new FileInputStream(sourceFile);
                isr = new InputStreamReader(is, ctxt.getOptions().getJavaEncoding());
                reader = new BufferedReader(isr);
                char[] chars = new char[8192];
                StringBuilder buf = new StringBuilder();
                int count;
                while ((count = reader.read(chars, 0, chars.length)) > 0) {
                    buf.append(chars, 0, count);
                }
                result = new char[buf.length()];
                buf.getChars(0, result.length, result, 0);
            } catch (IOException e) {
                log.error("Compilation error", e);
            } finally {
                if (reader != null) {
                    try {
                        reader.close();
                    } catch (IOException ioe) {
                        /*Ignore*/}
                }
                if (isr != null) {
                    try {
                        isr.close();
                    } catch (IOException ioe) {
                        /*Ignore*/}
                }
                if (is != null) {
                    try {
                        is.close();
                    } catch (IOException exc) {
                        /*Ignore*/}
                }
            }
            return result;
        }

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

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

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

    final INameEnvironment env = new INameEnvironment() {

        @Override
        public NameEnvironmentAnswer findType(char[][] compoundTypeName) {
            String result = "";
            String sep = "";
            for (int i = 0; i < compoundTypeName.length; i++) {
                result += sep;
                result += new String(compoundTypeName[i]);
                sep = ".";
            }
            return findType(result);
        }

        @Override
        public NameEnvironmentAnswer findType(char[] typeName, char[][] packageName) {
            String result = "";
            String sep = "";
            for (int i = 0; i < packageName.length; i++) {
                result += sep;
                result += new String(packageName[i]);
                sep = ".";
            }
            result += sep;
            result += new String(typeName);
            return findType(result);
        }

        private NameEnvironmentAnswer findType(String className) {

            InputStream is = null;
            try {
                if (className.equals(targetClassName)) {
                    ICompilationUnit compilationUnit = new CompilationUnit(sourceFile, className);
                    return new NameEnvironmentAnswer(compilationUnit, null);
                }
                String resourceName = className.replace('.', '/') + ".class";
                is = classLoader.getResourceAsStream(resourceName);
                if (is != null) {
                    byte[] classBytes;
                    byte[] buf = new byte[8192];
                    ByteArrayOutputStream baos = new ByteArrayOutputStream(buf.length);
                    int count;
                    while ((count = is.read(buf, 0, buf.length)) > 0) {
                        baos.write(buf, 0, count);
                    }
                    baos.flush();
                    classBytes = baos.toByteArray();
                    char[] fileName = className.toCharArray();
                    ClassFileReader classFileReader = new ClassFileReader(classBytes, fileName, true);
                    return new NameEnvironmentAnswer(classFileReader, null);
                }
            } catch (IOException exc) {
                log.error("Compilation error", exc);
            } catch (org.eclipse.jdt.internal.compiler.classfmt.ClassFormatException exc) {
                log.error("Compilation error", exc);
            } finally {
                if (is != null) {
                    try {
                        is.close();
                    } catch (IOException exc) {
                        // Ignore
                    }
                }
            }
            return null;
        }

        private boolean isPackage(String result) {
            if (result.equals(targetClassName)) {
                return false;
            }
            String resourceName = result.replace('.', '/') + ".class";
            InputStream is = classLoader.getResourceAsStream(resourceName);
            return is == null;
        }

        @Override
        public boolean isPackage(char[][] parentPackageName, char[] packageName) {
            String result = "";
            String sep = "";
            if (parentPackageName != null) {
                for (int i = 0; i < parentPackageName.length; i++) {
                    result += sep;
                    String str = new String(parentPackageName[i]);
                    result += str;
                    sep = ".";
                }
            }
            String str = new String(packageName);
            if (Character.isUpperCase(str.charAt(0))) {
                if (!isPackage(result)) {
                    return false;
                }
            }
            result += sep;
            result += str;
            return isPackage(result);
        }

        @Override
        public void cleanup() {
        }

    };

    final IErrorHandlingPolicy policy = DefaultErrorHandlingPolicies.proceedWithAllProblems();

    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);
    if (ctxt.getOptions().getJavaEncoding() != null) {
        settings.put(CompilerOptions.OPTION_Encoding, ctxt.getOptions().getJavaEncoding());
    }
    if (ctxt.getOptions().getClassDebugInfo()) {
        settings.put(CompilerOptions.OPTION_LocalVariableAttribute, CompilerOptions.GENERATE);
    }

    // Source JVM
    if (ctxt.getOptions().getCompilerSourceVM() != null) {
        String opt = ctxt.getOptions().getCompilerSourceVM();
        if (opt.equals("1.1")) {
            settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_1);
        } else if (opt.equals("1.2")) {
            settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_2);
        } else if (opt.equals("1.3")) {
            settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_3);
        } else if (opt.equals("1.4")) {
            settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_4);
        } else if (opt.equals("1.5")) {
            settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_5);
        } else if (opt.equals("1.6")) {
            settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_6);
        } else if (opt.equals("1.7")) {
            settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_7);
        } else {
            log.warn("Unknown source VM " + opt + " ignored.");
            settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_5);
        }
    } else {
        // Default to 1.5
        settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_5);
    }

    // Target JVM
    if (ctxt.getOptions().getCompilerTargetVM() != null) {
        String opt = ctxt.getOptions().getCompilerTargetVM();
        if (opt.equals("1.1")) {
            settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_1);
        } else if (opt.equals("1.2")) {
            settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_2);
        } else if (opt.equals("1.3")) {
            settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_3);
        } else if (opt.equals("1.4")) {
            settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_4);
        } else if (opt.equals("1.5")) {
            settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_5);
            settings.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_1_5);
        } else if (opt.equals("1.6")) {
            settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_6);
            settings.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_1_6);
        } else if (opt.equals("1.7")) {
            settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_7);
            settings.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_1_7);
        } else {
            log.warn("Unknown target VM " + opt + " ignored.");
            settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_5);
        }
    } else {
        // Default to 1.5
        settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_5);
        settings.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_1_5);
    }

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

    final ICompilerRequestor requestor = new ICompilerRequestor() {
        @Override
        public void acceptResult(CompilationResult result) {
            try {
                if (result.hasProblems()) {
                    IProblem[] problems = result.getProblems();
                    for (int i = 0; i < problems.length; i++) {
                        IProblem problem = problems[i];
                        if (problem.isError()) {
                            String name = new String(problems[i].getOriginatingFileName());
                            try {
                                problemList.add(ErrorDispatcher.createJavacError(name, pageNodes,
                                        new StringBuilder(problem.getMessage()), problem.getSourceLineNumber(),
                                        ctxt));
                            } catch (JasperException e) {
                                log.error("Error visiting node", e);
                            }
                        }
                    }
                }
                if (problemList.isEmpty()) {
                    ClassFile[] classFiles = result.getClassFiles();
                    for (int i = 0; i < classFiles.length; i++) {
                        ClassFile classFile = classFiles[i];
                        char[][] compoundName = classFile.getCompoundName();
                        String className = "";
                        String sep = "";
                        for (int j = 0; j < compoundName.length; j++) {
                            className += sep;
                            className += new String(compoundName[j]);
                            sep = ".";
                        }
                        byte[] bytes = classFile.getBytes();
                        String outFile = outputDir + "/" + className.replace('.', '/') + ".class";
                        FileOutputStream fout = new FileOutputStream(outFile);
                        BufferedOutputStream bos = new BufferedOutputStream(fout);
                        bos.write(bytes);
                        bos.close();
                    }
                }
            } catch (IOException exc) {
                log.error("Compilation error", exc);
            }
        }
    };

    ICompilationUnit[] compilationUnits = new ICompilationUnit[classNames.length];
    for (int i = 0; i < compilationUnits.length; i++) {
        String className = classNames[i];
        compilationUnits[i] = new CompilationUnit(fileNames[i], className);
    }
    CompilerOptions cOptions = new CompilerOptions(settings);
    cOptions.parseLiteralExpressionsAsConstants = true;
    Compiler compiler = new Compiler(env, policy, cOptions, requestor, problemFactory);
    compiler.compile(compilationUnits);

    if (!ctxt.keepGenerated()) {
        File javaFile = new File(ctxt.getServletJavaFileName());
        javaFile.delete();
    }

    if (!problemList.isEmpty()) {
        JavacErrorDetail[] jeds = problemList.toArray(new JavacErrorDetail[0]);
        errDispatcher.javacError(jeds);
    }

    if (log.isDebugEnabled()) {
        long t2 = System.currentTimeMillis();
        log.debug("Compiled " + ctxt.getServletJavaFileName() + " " + (t2 - t1) + "ms");
    }

    if (ctxt.isPrototypeMode()) {
        return;
    }

    // JSR45 Support
    if (!options.isSmapSuppressed()) {
        SmapUtil.installSmap(smap);
    }

}

From source file:org.apache.jasper.compiler.JDTJavaCompiler.java

License:Open Source License

public JavacErrorDetail[] compile(final String targetClassName, final Node.Nodes pageNodes)
        throws JasperException {

    final String sourceFile = ctxt.getServletJavaFileName();
    final String outputDir = ctxt.getOptions().getScratchDir().getAbsolutePath();
    String packageName = ctxt.getServletPackageName();

    final ClassLoader classLoader = ctxt.getJspLoader();
    String[] fileNames = new String[] { sourceFile };
    String[] classNames = new String[] { targetClassName };
    final ArrayList<JavacErrorDetail> problemList = new ArrayList<JavacErrorDetail>();

    class CompilationUnit implements ICompilationUnit {

        String className;// ww  w  .  ja  v  a 2 s . c  om
        String sourceFile;

        CompilationUnit(String sourceFile, String className) {
            this.className = className;
            this.sourceFile = sourceFile;
        }

        public char[] getFileName() {
            return className.toCharArray();
        }

        public char[] getContents() {
            char[] result = null;
            Reader reader = null;
            try {
                InputStreamReader isReader = new InputStreamReader(new FileInputStream(sourceFile),
                        ctxt.getOptions().getJavaEncoding());
                reader = new BufferedReader(isReader);
                if (reader != null) {
                    char[] chars = new char[8192];
                    StringBuilder buf = new StringBuilder();
                    int count;
                    while ((count = reader.read(chars, 0, chars.length)) > 0) {
                        buf.append(chars, 0, count);
                    }
                    result = new char[buf.length()];
                    buf.getChars(0, result.length, result, 0);
                }
            } catch (IOException e) {
                log.log(Level.SEVERE, "Compilation error", e);
            } finally {
                if (reader != null) {
                    try {
                        reader.close();
                    } catch (IOException ioe) {
                        // Ignore
                    }
                }
            }
            return result;
        }

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

        public char[][] getPackageName() {
            StringTokenizer izer = new StringTokenizer(className, ".");
            char[][] result = new char[izer.countTokens() - 1][];
            for (int i = 0; i < result.length; i++) {
                String tok = izer.nextToken();
                result[i] = tok.toCharArray();
            }
            return result;
        }
    }

    final INameEnvironment env = new INameEnvironment() {

        public NameEnvironmentAnswer findType(char[][] compoundTypeName) {
            String result = "";
            String sep = "";
            for (int i = 0; i < compoundTypeName.length; i++) {
                result += sep;
                result += new String(compoundTypeName[i]);
                sep = ".";
            }
            return findType(result);
        }

        public NameEnvironmentAnswer findType(char[] typeName, char[][] packageName) {
            String result = "";
            String sep = "";
            for (int i = 0; i < packageName.length; i++) {
                result += sep;
                result += new String(packageName[i]);
                sep = ".";
            }
            result += sep;
            result += new String(typeName);
            return findType(result);
        }

        private NameEnvironmentAnswer findType(String className) {

            InputStream is = null;
            try {
                if (className.equals(targetClassName)) {
                    ICompilationUnit compilationUnit = new CompilationUnit(sourceFile, className);
                    return new NameEnvironmentAnswer(compilationUnit, null);
                }
                String resourceName = className.replace('.', '/') + ".class";
                is = classLoader.getResourceAsStream(resourceName);
                if (is != null) {
                    byte[] classBytes;
                    byte[] buf = new byte[8192];
                    ByteArrayOutputStream baos = new ByteArrayOutputStream(buf.length);
                    int count;
                    while ((count = is.read(buf, 0, buf.length)) > 0) {
                        baos.write(buf, 0, count);
                    }
                    baos.flush();
                    classBytes = baos.toByteArray();
                    char[] fileName = className.toCharArray();
                    ClassFileReader classFileReader = new ClassFileReader(classBytes, fileName, true);
                    return new NameEnvironmentAnswer(classFileReader, null);
                }
            } catch (IOException exc) {
                log.log(Level.SEVERE, "Compilation error", exc);
            } catch (org.eclipse.jdt.internal.compiler.classfmt.ClassFormatException exc) {
                log.log(Level.SEVERE, "Compilation error", exc);
            } finally {
                if (is != null) {
                    try {
                        is.close();
                    } catch (IOException exc) {
                        // Ignore
                    }
                }
            }
            return null;
        }

        private boolean isPackage(String result) {
            if (result.equals(targetClassName)) {
                return false;
            }
            String resourceName = result.replace('.', '/') + ".class";
            InputStream is = classLoader.getResourceAsStream(resourceName);
            return is == null;
        }

        public boolean isPackage(char[][] parentPackageName, char[] packageName) {
            String result = "";
            String sep = "";
            if (parentPackageName != null) {
                for (int i = 0; i < parentPackageName.length; i++) {
                    result += sep;
                    String str = new String(parentPackageName[i]);
                    result += str;
                    sep = ".";
                }
            }
            String str = new String(packageName);
            if (Character.isUpperCase(str.charAt(0))) {
                if (!isPackage(result)) {
                    return false;
                }
            }
            result += sep;
            result += str;
            return isPackage(result);
        }

        public void cleanup() {
        }

    };

    final IErrorHandlingPolicy policy = DefaultErrorHandlingPolicies.proceedWithAllProblems();

    if (ctxt.getOptions().getJavaEncoding() != null) {
        settings.put(CompilerOptions.OPTION_Encoding, ctxt.getOptions().getJavaEncoding());
    }

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

    final ICompilerRequestor requestor = new ICompilerRequestor() {
        public void acceptResult(CompilationResult result) {
            try {
                if (result.hasProblems()) {
                    IProblem[] problems = safeGetProblems(result);
                    for (int i = 0; i < problems.length; i++) {
                        IProblem problem = problems[i];
                        if (problem.isError()) {
                            String name = new String(problems[i].getOriginatingFileName());
                            try {
                                problemList.add(ErrorDispatcher.createJavacError(name, pageNodes,
                                        new StringBuilder(problem.getMessage()),
                                        problem.getSourceLineNumber()));
                            } catch (JasperException e) {
                                log.log(Level.SEVERE, "Error visiting node", e);
                            }
                        }
                    }
                }
                if (problemList.isEmpty()) {
                    ClassFile[] classFiles = result.getClassFiles();
                    for (int i = 0; i < classFiles.length; i++) {
                        ClassFile classFile = classFiles[i];
                        char[][] compoundName = classFile.getCompoundName();
                        String className = "";
                        String sep = "";
                        for (int j = 0; j < compoundName.length; j++) {
                            className += sep;
                            className += new String(compoundName[j]);
                            sep = ".";
                        }
                        byte[] bytes = classFile.getBytes();
                        String outFile = outputDir + "/" + className.replace('.', '/') + ".class";
                        FileOutputStream fout = new FileOutputStream(outFile);
                        BufferedOutputStream bos = new BufferedOutputStream(fout);
                        bos.write(bytes);
                        bos.close();
                    }
                }
            } catch (IOException exc) {
                log.log(Level.SEVERE, "Compilation error", exc);
            }
        }
    };

    ICompilationUnit[] compilationUnits = new ICompilationUnit[classNames.length];
    for (int i = 0; i < compilationUnits.length; i++) {
        compilationUnits[i] = new CompilationUnit(fileNames[i], classNames[i]);
    }

    Compiler compiler = new Compiler(env, policy, settings, requestor, problemFactory);
    compiler.compile(compilationUnits);

    if (problemList.isEmpty()) {
        return null;
    }
    return problemList.toArray(new JavacErrorDetail[] {});
}

From source file:org.apache.sling.scripting.jsp.jasper.compiler.JDTCompiler.java

License:Apache License

/**
 * Compile the servlet from .java file to .class file
 *//*  ww  w  . j a v  a2  s  . c  o m*/
protected void generateClass(String[] smap) throws FileNotFoundException, JasperException, Exception {

    long t1 = 0;
    if (log.isDebugEnabled()) {
        t1 = System.currentTimeMillis();
    }

    final String sourceFile = ctxt.getServletJavaFileName();
    final String outputDir = ctxt.getOptions().getScratchDir();
    String packageName = ctxt.getServletPackageName();
    final String targetClassName = ((packageName.length() != 0) ? (packageName + ".") : "")
            + ctxt.getServletClassName();
    String[] fileNames = new String[] { sourceFile };
    String[] classNames = new String[] { targetClassName };
    final ArrayList problemList = new ArrayList();

    class CompilationUnit implements ICompilationUnit {

        String className;
        String sourceFile;

        CompilationUnit(String sourceFile, String className) {
            this.className = className;
            this.sourceFile = sourceFile;
        }

        public char[] getFileName() {
            return sourceFile.toCharArray();
        }

        public char[] getContents() {
            char[] result = null;
            InputStream is = null;
            try {
                is = ctxt.getInputStream(sourceFile);
                Reader reader = new BufferedReader(
                        new InputStreamReader(is, ctxt.getOptions().getJavaEncoding()));
                if (reader != null) {
                    char[] chars = new char[8192];
                    StringBuffer buf = new StringBuffer();
                    int count;
                    while ((count = reader.read(chars, 0, chars.length)) > 0) {
                        buf.append(chars, 0, count);
                    }
                    result = new char[buf.length()];
                    buf.getChars(0, result.length, result, 0);
                }
            } catch (IOException e) {
                log.error("Compilation error", e);
            } finally {
                if (is != null) {
                    try {
                        is.close();
                    } catch (IOException exc) {
                        // Ignore
                    }
                }
            }
            return result;
        }

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

        public char[][] getPackageName() {
            StringTokenizer izer = new StringTokenizer(className, ".");
            char[][] result = new char[izer.countTokens() - 1][];
            for (int i = 0; i < result.length; i++) {
                String tok = izer.nextToken();
                result[i] = tok.toCharArray();
            }
            return result;
        }
    }

    final INameEnvironment env = new INameEnvironment() {

        public NameEnvironmentAnswer findType(char[][] compoundTypeName) {
            String result = "";
            String sep = "";
            for (int i = 0; i < compoundTypeName.length; i++) {
                result += sep;
                result += new String(compoundTypeName[i]);
                sep = ".";
            }
            return findType(result);
        }

        public NameEnvironmentAnswer findType(char[] typeName, char[][] packageName) {
            String result = "";
            String sep = "";
            for (int i = 0; i < packageName.length; i++) {
                result += sep;
                result += new String(packageName[i]);
                sep = ".";
            }
            result += sep;
            result += new String(typeName);
            return findType(result);
        }

        private NameEnvironmentAnswer findType(String className) {

            InputStream is = null;
            try {
                if (className.equals(targetClassName)) {
                    ICompilationUnit compilationUnit = new CompilationUnit(sourceFile, className);
                    return new NameEnvironmentAnswer(compilationUnit, null);
                }
                String resourceName = className.replace('.', '/') + ".class";
                is = ctxt.getClassLoader().getResourceAsStream(resourceName);
                if (is != null) {
                    byte[] classBytes;
                    byte[] buf = new byte[8192];
                    ByteArrayOutputStream baos = new ByteArrayOutputStream(buf.length);
                    int count;
                    while ((count = is.read(buf, 0, buf.length)) > 0) {
                        baos.write(buf, 0, count);
                    }
                    baos.flush();
                    classBytes = baos.toByteArray();
                    char[] fileName = className.toCharArray();
                    ClassFileReader classFileReader = new ClassFileReader(classBytes, fileName, true);
                    return new NameEnvironmentAnswer(classFileReader, null);
                }
            } catch (IOException exc) {
                log.error("Compilation error", exc);
            } catch (org.eclipse.jdt.internal.compiler.classfmt.ClassFormatException exc) {
                log.error("Compilation error", exc);
            } finally {
                if (is != null) {
                    try {
                        is.close();
                    } catch (IOException exc) {
                        // Ignore
                    }
                }
            }
            return null;
        }

        private boolean isPackage(String result) {
            if (result.equals(targetClassName)) {
                return false;
            }
            String resourceName = result.replace('.', '/') + ".class";
            InputStream is = ctxt.getClassLoader().getResourceAsStream(resourceName);
            return is == null;
        }

        public boolean isPackage(char[][] parentPackageName, char[] packageName) {
            String result = "";
            String sep = "";
            if (parentPackageName != null) {
                for (int i = 0; i < parentPackageName.length; i++) {
                    result += sep;
                    String str = new String(parentPackageName[i]);
                    result += str;
                    sep = ".";
                }
            }
            String str = new String(packageName);
            if (Character.isUpperCase(str.charAt(0))) {
                if (!isPackage(result)) {
                    return false;
                }
            }
            result += sep;
            result += str;
            return isPackage(result);
        }

        public void cleanup() {
        }

    };

    final IErrorHandlingPolicy policy = DefaultErrorHandlingPolicies.proceedWithAllProblems();

    final Map settings = new HashMap();
    settings.put(CompilerOptions.OPTION_LineNumberAttribute, CompilerOptions.GENERATE);
    settings.put(CompilerOptions.OPTION_SourceFileAttribute, CompilerOptions.GENERATE);
    settings.put(CompilerOptions.OPTION_ReportDeprecation, CompilerOptions.IGNORE);
    if (ctxt.getOptions().getJavaEncoding() != null) {
        settings.put(CompilerOptions.OPTION_Encoding, ctxt.getOptions().getJavaEncoding());
    }
    if (ctxt.getOptions().getClassDebugInfo()) {
        settings.put(CompilerOptions.OPTION_LocalVariableAttribute, CompilerOptions.GENERATE);
    }

    // Source JVM
    if (ctxt.getOptions().getCompilerSourceVM() != null) {
        String opt = ctxt.getOptions().getCompilerSourceVM();
        if (opt.equals("1.1")) {
            settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_1);
        } else if (opt.equals("1.2")) {
            settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_2);
        } else if (opt.equals("1.3")) {
            settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_3);
        } else if (opt.equals("1.4")) {
            settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_4);
        } else if (opt.equals("1.5")) {
            settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_5);
        } else {
            log.warn("Unknown source VM " + opt + " ignored.");
            settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_5);
        }
    } else {
        // Default to 1.5
        settings.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_5);
    }

    // Target JVM
    if (ctxt.getOptions().getCompilerTargetVM() != null) {
        String opt = ctxt.getOptions().getCompilerTargetVM();
        if (opt.equals("1.1")) {
            settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_1);
        } else if (opt.equals("1.2")) {
            settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_2);
        } else if (opt.equals("1.3")) {
            settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_3);
        } else if (opt.equals("1.4")) {
            settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_4);
        } else if (opt.equals("1.5")) {
            settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_5);
            settings.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_1_5);
        } else {
            log.warn("Unknown target VM " + opt + " ignored.");
            settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_5);
        }
    } else {
        // Default to 1.5
        settings.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_5);
        settings.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_1_5);
    }

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

    final ICompilerRequestor requestor = new ICompilerRequestor() {
        public void acceptResult(CompilationResult result) {
            try {
                if (result.hasProblems()) {
                    IProblem[] problems = result.getProblems();
                    for (int i = 0; i < problems.length; i++) {
                        IProblem problem = problems[i];
                        if (problem.isError()) {
                            String name = new String(problems[i].getOriginatingFileName());
                            try {
                                problemList.add(ErrorDispatcher.createJavacError(name, pageNodes,
                                        new StringBuffer(problem.getMessage()), problem.getSourceLineNumber(),
                                        ctxt));
                            } catch (JasperException e) {
                                log.error("Error visiting node", e);
                            }
                        }
                    }
                }
                if (problemList.isEmpty()) {
                    ClassFile[] classFiles = result.getClassFiles();
                    for (int i = 0; i < classFiles.length; i++) {
                        ClassFile classFile = classFiles[i];
                        char[][] compoundName = classFile.getCompoundName();
                        String className = "";
                        String sep = "";
                        for (int j = 0; j < compoundName.length; j++) {
                            className += sep;
                            className += new String(compoundName[j]);
                            sep = ".";
                        }
                        byte[] bytes = classFile.getBytes();
                        String outFile = outputDir + "/" + className.replace('.', '/') + ".class";
                        OutputStream out = ctxt.getOutputStream(outFile);
                        BufferedOutputStream bos = new BufferedOutputStream(out);
                        bos.write(bytes);
                        bos.close();
                    }
                }
            } catch (IOException exc) {
                log.error("Compilation error", exc);
            }
        }
    };

    ICompilationUnit[] compilationUnits = new ICompilationUnit[classNames.length];
    for (int i = 0; i < compilationUnits.length; i++) {
        String className = classNames[i];
        compilationUnits[i] = new CompilationUnit(fileNames[i], className);
    }
    Compiler compiler = new Compiler(env, policy, settings, requestor, problemFactory, true);
    compiler.compile(compilationUnits);

    if (!ctxt.keepGenerated()) {
        ctxt.delete(ctxt.getServletJavaFileName());
    }

    if (!problemList.isEmpty()) {
        JavacErrorDetail[] jeds = (JavacErrorDetail[]) problemList.toArray(new JavacErrorDetail[0]);
        errDispatcher.javacError(jeds);
    }

    if (log.isDebugEnabled()) {
        long t2 = System.currentTimeMillis();
        log.debug("Compiled " + ctxt.getServletJavaFileName() + " " + (t2 - t1) + "ms");
    }

    if (ctxt.isPrototypeMode()) {
        return;
    }

    // JSR45 Support
    if (!options.isSmapSuppressed()) {
        SmapUtil.installSmap(getCompilationContext(), smap);
    }

}

From source file:org.auroraide.server.jci.compilers.EclipseJavaCompiler.java

License:Apache License

public org.apache.commons.jci.compilers.CompilationResult compile(final String[] pSourceFiles,
        final ResourceReader pReader, final ResourceStore pStore, final ClassLoader pClassLoader,
        final JavaCompilerSettings pSettings) {

    final Map<?, ?> settingsMap = ((EclipseJavaCompilerSettings) defaultSettings).getMap();

    final Collection<CompilationProblem> problems = new ArrayList<CompilationProblem>();

    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);
            log.debug("compiling " + sourceFile);
        } else {/*from  w  ww.j a v  a2s  . c  o m*/
            // 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.apache.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 StringBuffer result = new StringBuffer();
            for (int i = 0; i < pCompoundTypeName.length; i++) {
                if (i != 0) {
                    result.append('.');
                }
                result.append(pCompoundTypeName[i]);
            }

            //log.debug("finding compoundTypeName=" + result.toString());

            return findType(result.toString());
        }

        public NameEnvironmentAnswer findType(final char[] pTypeName, final char[][] pPackageName) {
            final StringBuffer result = new StringBuffer();
            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) {

            if (isPackage(pClazzName)) {
                return null;
            }

            log.debug("finding " + pClazzName);

            final String resourceName = ConversionUtils.convertClassToResourcePath(pClazzName);

            final byte[] clazzBytes = pStore.read(pClazzName);
            if (clazzBytes != null) {
                log.debug("loading from store " + pClazzName);

                final char[] fileName = pClazzName.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);
                    return null;
                }
            }

            log.debug("not in store " + pClazzName);

            final InputStream is = pClassLoader.getResourceAsStream(resourceName);
            if (is == null) {
                log.debug("class " + pClazzName + " not found");
                return 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();
                final char[] fileName = pClazzName.toCharArray();
                final ClassFileReader classFileReader = new ClassFileReader(baos.toByteArray(), fileName, true);
                return new NameEnvironmentAnswer(classFileReader, null);
            } catch (final IOException e) {
                log.error("could not read class", e);
                return null;
            } catch (final ClassFormatException e) {
                log.error("wrong class format", e);
                return null;
            } 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);
                }
            }
        }

        private boolean isPackage(final String pClazzName) {

            final InputStream is = pClassLoader
                    .getResourceAsStream(ConversionUtils.convertClassToResourcePath(pClazzName));
            if (is != null) {
                log.debug("found the class for " + pClazzName + "- no package");
                return false;
            }

            // FIXME: this should not be tied to the extension
            final String source = pClazzName.replace('.', '/') + ".java";
            if (pReader.isAvailable(source)) {
                log.debug("found the source " + source + " for " + pClazzName + " - no package ");
                return false;
            }

            return true;
        }

        public boolean isPackage(char[][] parentPackageName, char[] pPackageName) {
            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]);
                }
            }

            //                log.debug("isPackage parentPackageName=" + result.toString() + " packageName=" + new String(packageName));

            if (parentPackageName != null && parentPackageName.length > 0) {
                result.append('.');
            }
            result.append(pPackageName);
            return isPackage(result.toString());
        }

        public void cleanup() {
            log.debug("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 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().replace('.', '/') + ".class", clazzFile.getBytes());
                }
            }
        }
    };

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

    compiler.compile(compilationUnits);

    final CompilationProblem[] result = new CompilationProblem[problems.size()];
    problems.toArray(result);
    return new org.apache.commons.jci.compilers.CompilationResult(result);
}

From source file:org.drools.commons.jci.compilers.EclipseJavaCompiler.java

License:Apache License

public org.drools.commons.jci.compilers.CompilationResult compile(final String[] pSourceFiles,
        final ResourceReader pReader, final ResourceStore pStore, final ClassLoader pClassLoader,
        final JavaCompilerSettings pSettings) {

    final Map settingsMap = new EclipseJavaCompilerSettings(pSettings).toNativeSettings();

    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 {/* w ww. j ava2s .  c o m*/
            // 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.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]);
            }

            //log.debug("finding compoundTypeName=" + result.toString());

            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;
                }

                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 source = pClazzName.replace('.', '/') + ".java";
            return pReader.isAvailable(source);
        }

        private boolean isPackage(final String pClazzName) {
            InputStream is = null;
            try {
                is = pClassLoader.getResourceAsStream(ClassUtils.convertClassToResourcePath(pClazzName));
                return is == null && !isSourceAvailable(pClazzName, pReader);
            } 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]);
                }
            }

            //                log.debug("isPackage parentPackageName=" + result.toString() + " packageName=" + new String(packageName));

            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 Compiler compiler = new Compiler(nameEnvironment, policy, settingsMap, compilerRequestor,
            problemFactory, false);

    compiler.compile(compilationUnits);

    final CompilationProblem[] result = new CompilationProblem[problems.size()];
    problems.toArray(result);
    return new org.drools.commons.jci.compilers.CompilationResult(result);
}