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

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

Introduction

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

Prototype

public char[] fileName() 

Source Link

Document

INTERNAL USE-ONLY This methods returns a char[] representing the file name of the receiver

Usage

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

License:Apache License

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

    // compile/*from   w  w w. j a v a2 s  .  co  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:io.gige.compiler.internal.CompilerRequestorImpl.java

License:Apache License

@Override
public void acceptResult(CompilationResult result) {
    if (result.hasProblems()) {
        report(Kind.ERROR, result.getErrors());
    }/*from   www.java 2 s .  c  o  m*/
    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

@Override
public void acceptResult(CompilationResult result) {
    if (result == null) {
        return; // ah?
    }//from   w w  w.  j a  v a  2s.  com
    final String sourceName = new String(result.getFileName());
    final File sourceFile = new File(sourceName);

    Resource<File> input = context.getProcessedSource(sourceFile);

    // track type references
    if (result.rootReferences != null && result.qualifiedReferences != null
            && result.simpleNameReferences != null) {
        context.setAttribute(input.getResource(), ATTR_REFERENCES, new ReferenceCollection(
                result.rootReferences, result.qualifiedReferences, result.simpleNameReferences));
    }

    if (result.hasProblems() && (!isLenientProcOnly() || isShowWarnings())) {
        for (CategorizedProblem problem : result.getProblems()) {
            MessageSeverity severity = isLenientProcOnly() ? MessageSeverity.WARNING
                    : problem.isError() ? MessageSeverity.ERROR : MessageSeverity.WARNING;
            input.addMessage(problem.getSourceLineNumber(), ((DefaultProblem) problem).column,
                    problem.getMessage(), severity, null /* cause */);
        }
    }

    try {
        if (!result.hasErrors() && !isProcOnly()) {
            for (ClassFile classFile : result.getClassFiles()) {
                char[] filename = classFile.fileName();
                int length = filename.length;
                char[] relativeName = new char[length + 6];
                System.arraycopy(filename, 0, relativeName, 0, length);
                System.arraycopy(SuffixConstants.SUFFIX_class, 0, relativeName, length, 6);
                CharOperation.replace(relativeName, '/', File.separatorChar);
                String relativeStringName = new String(relativeName);
                writeClassFile(input, relativeStringName, classFile);
            }
        }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    // XXX double check affected sources are recompiled when this source has errors
}

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 {// w  w  w .j av a 2 s  .c o 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:net.sf.j2s.core.builder.AbstractImageBuilder.java

License:Open Source License

protected char[] writeClassFile(ClassFile classFile, SourceFile compilationUnit, boolean isTopLevelType)
        throws CoreException {
    String fileName = new String(classFile.fileName()); // the qualified type name "p1/p2/A"
    IPath filePath = new Path(fileName);
    IContainer outputFolder = compilationUnit.sourceLocation.binaryFolder;
    IContainer container = outputFolder;
    if (filePath.segmentCount() > 1) {
        container = createFolder(filePath.removeLastSegments(1), outputFolder);
        filePath = new Path(filePath.lastSegment());
    }//  www.  j ava 2  s .c  o  m

    IFile file = container.getFile(filePath.addFileExtension(SuffixConstants.EXTENSION_class));
    writeClassFileContents(classFile, file, fileName, isTopLevelType, compilationUnit);
    // answer the name of the class file as in Y or Y$M
    return filePath.lastSegment().toCharArray();
}

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

License:Open Source License

protected void acceptSecondaryType(ClassFile classFile) {
    if (this.secondaryTypes != null)
        this.secondaryTypes.add(classFile.fileName());
}

From source file:org.eclipse.objectteams.otdt.tests.compiler.smap.Requestor.java

License:Open Source License

protected void outputClassFiles(CompilationResult unitResult) {
    if ((unitResult != null) && (!unitResult.hasErrors() || forceOutputGeneration)) {
        ClassFile[] classFiles = unitResult.getClassFiles();
        for (int i = 0, fileCount = classFiles.length; i < fileCount; i++) {
            // retrieve the key and the corresponding classfile
            ClassFile classFile = classFiles[i];
            if (outputPath != null) {
                String relativeName = new String(classFile.fileName()).replace('/', File.separatorChar)
                        + ".class";
                try {
                    org.eclipse.jdt.internal.compiler.util.Util.writeToDisk(true, outputPath, relativeName,
                            classFile);/*from  w w  w.  j av  a  2  s  .c o  m*/
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (this.lineNumbers != null) {
                ClassFileReader cfr;
                try {
                    cfr = new ClassFileReader(classFile.getBytes(),
                            IClassFileReader.METHOD_INFOS | IClassFileReader.METHOD_BODIES);
                } catch (ClassFormatException e) {
                    throw new AssertionFailedError("Can't read class file: " + e.getMessage());
                }
                for (IMethodInfo method : cfr.getMethodInfos()) {
                    String fullMethodDesignator = String
                            .valueOf(CharOperation.concatWith(classFile.getCompoundName(),
                                    CharOperation.concat(method.getName(), method.getDescriptor()), '.'));
                    int[] expectedNumbers = this.lineNumbers.get(fullMethodDesignator);
                    if (expectedNumbers != null) {
                        this.lineNumbers.remove(fullMethodDesignator);
                        ILineNumberAttribute lineNumberAttribute = method.getCodeAttribute()
                                .getLineNumberAttribute();
                        int[][] table = lineNumberAttribute.getLineNumberTable();
                        Assert.assertEquals("wrong number of line numbers", expectedNumbers.length,
                                table.length);
                        for (int n = 0; n < expectedNumbers.length; n++)
                            Assert.assertEquals("wrong line numeber", expectedNumbers[n], table[n][1]);
                    }
                }
            }
        }
    }
}

From source file:spoon.support.ByteCodeOutputProcessor.java

License:Open Source License

@Override
public void processingDone() {
    try {//from  w ww.  ja va2s  .  c  o m
        // Do compilation
        JDTCompiler compiler = new JDTCompiler();
        compiler.getCompilerOption().sourceLevel = getJavaCompliance();
        compiler.getCompilerOption().targetJDK = getJavaCompliance();
        compiler.compile(units.toArray(new ICompilationUnit[0]));

        getOutputDirectory().mkdirs();

        for (ClassFile f : compiler.getClassFiles()) {
            String fileName = new String(f.fileName()).replace('/', File.separatorChar) + CLASS_EXT;
            //            System.out.println("--- adjusting "+fileName);
            ClassFileUtil.adjustLineNumbers(f.getBytes(), f.headerOffset + f.methodCountOffset - 1,
                    javaPrinter.getLineNumberMappings().get(new String(f.fileName()).replace('/', '.')));
            ClassFileUtil.writeToDisk(true, getOutputDirectory().getAbsolutePath(), fileName, f.getBytes());

            printed.add(new File(getOutputDirectory(), fileName));
            printedTypes.add(new String(f.fileName()).replace('/', '.'));
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

}