Example usage for org.eclipse.jdt.internal.compiler ClassFile getCompoundName

List of usage examples for org.eclipse.jdt.internal.compiler ClassFile getCompoundName

Introduction

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

Prototype

public char[][] getCompoundName() 

Source Link

Document

EXTERNAL API Answer the compound name of the class file.

Usage

From source file:com.google.gwt.dev.javac.CompiledClass.java

License:Open Source License

private static ClassFile getClassFile(TypeDeclaration typeDecl, String binaryName) {
    for (ClassFile tryClassFile : typeDecl.compilationResult().getClassFiles()) {
        char[] tryBinaryName = CharOperation.concatWith(tryClassFile.getCompoundName(), '/');
        if (binaryName.equals(String.valueOf(tryBinaryName))) {
            return tryClassFile;
        }//  ww w  . ja va  2 s  .  c  o m
    }
    assert false;
    return null;
}

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 a v  a 2s.  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:io.takari.maven.plugins.compile.jdt.CompilerJdt.java

License:Open Source License

private void writeClassFile(Resource<File> input, String relativeStringName, ClassFile classFile)
        throws IOException {
    final byte[] bytes = classFile.getBytes();
    final File outputFile = new File(getOutputDirectory(), relativeStringName);
    final Output<File> output = context.associatedOutput(input, outputFile);

    boolean significantChange = digestClassFile(output, bytes);

    if (significantChange) {
        // find all sources that reference this type and put them into work queue
        strategy.addDependentsOf(CharOperation.toString(classFile.getCompoundName()));
    }/*from ww w  .  j av a2  s.c  o  m*/

    final BufferedOutputStream os = new BufferedOutputStream(output.newOutputStream());
    try {
        os.write(bytes);
        os.flush();
    } finally {
        os.close();
    }
}

From source file:ma.glasnost.orika.impl.generator.eclipsejdt.CompilerRequestor.java

License:Apache License

public void acceptResult(CompilationResult result) {
    boolean hasErrors = false;

    if (result.hasProblems()) {
        problems = result.getProblems();
    }/*from   w  w  w. ja  va  2 s.c om*/

    if (!hasErrors) {

        ClassFile[] classFiles = result.getClassFiles();

        for (int i = 0; i < classFiles.length; i++) {
            ClassFile classFile = classFiles[i];
            char[][] compoundName = classFile.getCompoundName();
            StringBuilder className = new StringBuilder();
            String sep = "";

            for (int j = 0; j < compoundName.length; j++) {
                className.append(sep);
                className.append(new String(compoundName[j]));
                sep = ".";
            }

            byte[] bytes = classFile.getBytes();
            compiledClassFiles.put(className.toString(), bytes);
        }

    }
}

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

License:Open Source License

public void acceptResult(CompilationResult result) {
    // In Batch mode, we write out the class files, hold onto the dependency info
    // & additional types and report problems.

    // In Incremental mode, when writing out a class file we need to compare it
    // against the previous file, remembering if structural changes occured.
    // Before reporting the new problems, we need to update the problem count &
    // remove the old problems. Plus delete additional class files that no longer exist.

    SourceFile compilationUnit = (SourceFile) result.getCompilationUnit(); // go directly back to the sourceFile
    if (!this.workQueue.isCompiled(compilationUnit)) {
        this.workQueue.finished(compilationUnit);

        try {/*from  w  w w.  j  av a 2 s  .co m*/
            updateProblemsFor(compilationUnit, result); // record compilation problems before potentially adding duplicate errors
            updateTasksFor(compilationUnit, result); // record tasks
        } catch (CoreException e) {
            throw internalException(e);
        }

        if (result.hasInconsistentToplevelHierarchies)
            // ensure that this file is always retrieved from source for the rest of the build
            if (!this.problemSourceFiles.contains(compilationUnit))
                this.problemSourceFiles.add(compilationUnit);

        IType mainType = null;
        String mainTypeName = null;
        String typeLocator = compilationUnit.typeLocator();
        ClassFile[] classFiles = result.getClassFiles();
        int length = classFiles.length;
        ArrayList duplicateTypeNames = null;
        ArrayList definedTypeNames = new ArrayList(length);
        for (int i = 0; i < length; i++) {
            ClassFile classFile = classFiles[i];

            char[][] compoundName = classFile.getCompoundName();
            char[] typeName = compoundName[compoundName.length - 1];
            boolean isNestedType = classFile.isNestedType;

            // Look for a possible collision, if one exists, report an error but do not write the class file
            if (isNestedType) {
                String qualifiedTypeName = new String(classFile.outerMostEnclosingClassFile().fileName());
                if (this.newState.isDuplicateLocator(qualifiedTypeName, typeLocator))
                    continue;
            } else {
                String qualifiedTypeName = new String(classFile.fileName()); // the qualified type name "p1/p2/A"
                if (this.newState.isDuplicateLocator(qualifiedTypeName, typeLocator)) {
                    if (duplicateTypeNames == null)
                        duplicateTypeNames = new ArrayList();
                    duplicateTypeNames.add(compoundName);
                    if (mainType == null) {
                        try {
                            mainTypeName = compilationUnit.initialTypeName; // slash separated qualified name "p1/p1/A"
                            mainType = this.javaBuilder.javaProject.findType(mainTypeName.replace('/', '.'));
                        } catch (JavaModelException e) {
                            // ignore
                        }
                    }
                    IType type;
                    if (qualifiedTypeName.equals(mainTypeName)) {
                        type = mainType;
                    } else {
                        String simpleName = qualifiedTypeName.substring(qualifiedTypeName.lastIndexOf('/') + 1);
                        type = mainType == null ? null : mainType.getCompilationUnit().getType(simpleName);
                    }
                    createProblemFor(compilationUnit.resource, type,
                            Messages.bind(Messages.build_duplicateClassFile, new String(typeName)),
                            JavaCore.ERROR);
                    continue;
                }
                this.newState.recordLocatorForType(qualifiedTypeName, typeLocator);
                if (result.checkSecondaryTypes && !qualifiedTypeName.equals(compilationUnit.initialTypeName))
                    acceptSecondaryType(classFile);
            }
            try {
                definedTypeNames.add(writeClassFile(classFile, compilationUnit, !isNestedType));
            } catch (CoreException e) {
                Util.log(e, "JavaBuilder handling CoreException"); //$NON-NLS-1$
                if (e.getStatus().getCode() == IResourceStatus.CASE_VARIANT_EXISTS)
                    createProblemFor(compilationUnit.resource, null,
                            Messages.bind(Messages.build_classFileCollision, e.getMessage()), JavaCore.ERROR);
                else
                    createProblemFor(compilationUnit.resource, null, Messages.build_inconsistentClassFile,
                            JavaCore.ERROR);
            }
        }
        if (result.hasAnnotations && this.filesWithAnnotations != null) // only initialized if an annotation processor is attached
            this.filesWithAnnotations.add(compilationUnit);

        this.compiler.lookupEnvironment.releaseClassFiles(classFiles);
        finishedWith(typeLocator, result, compilationUnit.getMainTypeName(), definedTypeNames,
                duplicateTypeNames);
        this.notifier.compiled(compilationUnit);
    }
}

From source file:org.ant4eclipse.lib.jdt.ecj.internal.tools.CompilerRequestorImpl.java

License:Open Source License

/**
 * {@inheritDoc}//  w  ww  . j a  va 2s . c  o m
 */
public void acceptResult(CompilationResult result) {

    // get the compilation unit...
    CompilationUnitImpl compilationUnitImpl = (CompilationUnitImpl) result.getCompilationUnit();

    // ...and the source file
    SourceFile sourceFile = compilationUnitImpl.getSourceFile();

    // return immediately if the source file is a ReferableSourceFile
    if (sourceFile instanceof ReferableSourceFile) {

        // add the problems...
        if (result.getAllProblems() != null) {
            if (A4ELogging.isTraceingEnabled()) {
                A4ELogging.trace("Could not compile referenced class '%s'. Reason: %s",
                        sourceFile.getSourceFileName(), Arrays.asList(result.getAllProblems()));
            }
        }

        return;
    }

    // get the destination directory
    File destinationDirectory = sourceFile.getDestinationFolder();

    if (!result.hasErrors()) {
        ClassFile[] classFiles = result.getClassFiles();
        for (ClassFile classFile2 : classFiles) {
            char[][] compoundName = classFile2.getCompoundName();
            StringBuffer classFileName = new StringBuffer();
            for (int j = 0; j < compoundName.length; j++) {
                classFileName.append(compoundName[j]);
                if (j < compoundName.length - 1) {
                    classFileName.append('/');
                }
            }
            classFileName.append(".class");
            File classFile = new File(destinationDirectory, classFileName.toString());
            File classDir = classFile.getParentFile();
            if (!classDir.exists()) {
                classDir.mkdirs();
            }
            try {
                A4ELogging.debug("writing class file: '%s'", classFile);
                Utilities.writeFile(classFile, classFile2.getBytes());
                this._compiledClassFiles.put(classFileName.toString(), classFile);
            } catch (Ant4EclipseException ioe) {
                A4ELogging.error("Could not write classfile '%s': %s", classFileName.toString(),
                        ioe.toString());
                ioe.printStackTrace();
                this._compilationSuccessful = false;
            }
        }
    } else {
        this._compilationSuccessful = false;
    }

    // add the problems...
    if (result.getAllProblems() != null) {
        this._categorizedProblems.addAll(Arrays.asList(result.getAllProblems()));
    }
}

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;/*from  w  w  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  . j a va 2 s  .  co 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;
                }

                @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
 *///from   w  w w.  j  ava 2  s . com
@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;/*from   w w w. j a v a 2s  .co 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;
            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[] {});
}