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

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

Introduction

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

Prototype

public byte[] getBytes() 

Source Link

Document

EXTERNAL API Answer the actual bytes of the class file This method encodes the receiver structure into a byte array which is the content of the classfile.

Usage

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

License:Open Source License

CompiledClass(TypeDeclaration typeDeclaration, CompiledClass enclosingClass) {
    this.enclosingClass = enclosingClass;
    SourceTypeBinding binding = typeDeclaration.binding;
    this.internalName = CharOperation.charToString(binding.constantPoolName());
    this.isLocal = isLocalType(binding);
    ClassFile classFile = getClassFile(typeDeclaration, internalName);
    if (classFile != null) {
        m_bytes = classFile.getBytes();
    } else {/*from   www . j a  va  2  s  . c o m*/
        m_bytes = ArrayUtils.EMPTY_BYTE_ARRAY;
    }
}

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

License:Apache License

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

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

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

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

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

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

    INameEnvironment env = new INameEnvironment() {

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

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

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

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

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

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

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

        @Override
        public void cleanup() {
        }

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

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

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

        }
    };

    ICompilerRequestor requestor = new ICompilerRequestor() {

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

    problemList.clear();

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

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

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

License:Apache License

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

    final Map settingsMap = settings.getMap();
    final Set clazzIndex = new HashSet();
    ICompilationUnit[] compilationUnits = new ICompilationUnit[pClazzNames.length];
    for (int i = 0; i < compilationUnits.length; i++) {
        final String clazzName = pClazzNames[i];
        compilationUnits[i] = new CompilationUnit(pReader, clazzName);
        clazzIndex.add(clazzName);//from w  w  w  . jav a2s .  com
        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.gige.compiler.internal.CompilerRequestorImpl.java

License:Apache License

@Override
public void acceptResult(CompilationResult result) {
    if (result.hasProblems()) {
        report(Kind.ERROR, result.getErrors());
    }/*  w  w  w  .  ja v  a  2s.c  om*/
    if (result.hasTasks()) {
        report(Kind.NOTE, result.getTasks());
    }
    try {
        for (ClassFile cf : result.getClassFiles()) {
            String className = new String(cf.fileName());
            JavaFileObject obj = this.manager.getJavaFileForOutput(StandardLocation.CLASS_OUTPUT, className,
                    javax.tools.JavaFileObject.Kind.CLASS, null);
            try (OutputStream out = obj.openOutputStream()) {
                out.write(cf.getBytes());
            }
        }
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}

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()));
    }/*ww w. j  a v a 2 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  ww  . j  av a 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

protected void writeClassFileContents(ClassFile classFile, IFile file, String qualifiedFileName,
        boolean isTopLevelType, SourceFile compilationUnit) throws CoreException {
    //   InputStream input = new SequenceInputStream(
    //         new ByteArrayInputStream(classFile.header, 0, classFile.headerOffset),
    //         new ByteArrayInputStream(classFile.contents, 0, classFile.contentsOffset));
    InputStream input = new ByteArrayInputStream(classFile.getBytes());
    if (file.exists()) {
        // Deal with shared output folders... last one wins... no collision cases detected
        if (JavaBuilder.DEBUG)
            System.out.println("Writing changed class file " + file.getName());//$NON-NLS-1$
        if (!file.isDerived())
            file.setDerived(true, null);
        file.setContents(input, true, false, null);
    } else {/*from   w  ww  . j a  v  a2  s  .  com*/
        // Default implementation just writes out the bytes for the new class file...
        if (JavaBuilder.DEBUG)
            System.out.println("Writing new class file " + file.getName());//$NON-NLS-1$
        file.create(input, IResource.FORCE | IResource.DERIVED, null);
    }
}

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

License:Open Source License

/**
 * @see org.eclipse.jdt.internal.core.builder.AbstractImageBuilder#writeClassFileContents(org.eclipse.jdt.internal.compiler.ClassFile, org.eclipse.core.resources.IFile, java.lang.String, boolean, org.eclipse.jdt.internal.core.builder.SourceFile)
 *//*from   w  w  w  . ja va  2  s . co  m*/
protected void writeClassFileContents(ClassFile classfile, IFile file, String qualifiedFileName,
        boolean isTopLevelType, SourceFile compilationUnit) throws CoreException {
    // Before writing out the class file, compare it to the previous file
    // If structural changes occurred then add dependent source files
    byte[] bytes = classfile.getBytes();
    if (file.exists()) {
        if (writeClassFileCheck(file, qualifiedFileName, bytes) || compilationUnit.updateClassFile) { // see 46093
            if (JavaBuilder.DEBUG)
                System.out.println("Writing changed class file " + file.getName());//$NON-NLS-1$
            if (!file.isDerived())
                file.setDerived(true, null);
            file.setContents(new ByteArrayInputStream(bytes), true, false, null);
        } else if (JavaBuilder.DEBUG) {
            System.out.println("Skipped over unchanged class file " + file.getName());//$NON-NLS-1$
        }
    } else {
        if (isTopLevelType)
            addDependentsOf(new Path(qualifiedFileName), true); // new type
        if (JavaBuilder.DEBUG)
            System.out.println("Writing new class file " + file.getName());//$NON-NLS-1$
        try {
            file.create(new ByteArrayInputStream(bytes), IResource.FORCE | IResource.DERIVED, null);
        } catch (CoreException e) {
            if (e.getStatus().getCode() == IResourceStatus.CASE_VARIANT_EXISTS) {
                IStatus status = e.getStatus();
                if (status instanceof IResourceStatus) {
                    IPath oldFilePath = ((IResourceStatus) status).getPath();
                    char[] oldTypeName = oldFilePath.removeFileExtension().lastSegment().toCharArray();
                    char[][] previousTypeNames = this.newState
                            .getDefinedTypeNamesFor(compilationUnit.typeLocator());
                    boolean fromSameFile = false;
                    if (previousTypeNames == null) {
                        fromSameFile = CharOperation.equals(compilationUnit.getMainTypeName(), oldTypeName);
                    } else {
                        for (int i = 0, l = previousTypeNames.length; i < l; i++) {
                            if (CharOperation.equals(previousTypeNames[i], oldTypeName)) {
                                fromSameFile = true;
                                break;
                            }
                        }
                    }
                    if (fromSameFile) {
                        // file is defined by the same compilationUnit, but won't be deleted until later so do it now
                        IFile collision = file.getParent().getFile(new Path(oldFilePath.lastSegment()));
                        collision.delete(true, false, null);
                        boolean success = false;
                        try {
                            file.create(new ByteArrayInputStream(bytes), IResource.FORCE | IResource.DERIVED,
                                    null);
                            success = true;
                        } catch (CoreException ignored) {
                            // ignore the second exception
                        }
                        if (success)
                            return;
                    }
                }
                // catch the case that a type has been renamed and collides on disk with an as-yet-to-be-deleted type
                throw new AbortCompilation(true, new AbortIncrementalBuildException(qualifiedFileName));
            }
            throw e; // rethrow
        }
    }
}

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

License:Open Source License

/**
 * {@inheritDoc}/*from  w w  w .  jav a  2  s  . 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;/*  w ww.  jav  a  2  s .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;
            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;
}