Example usage for org.eclipse.jdt.core ToolFactory createDefaultClassFileReader

List of usage examples for org.eclipse.jdt.core ToolFactory createDefaultClassFileReader

Introduction

In this page you can find the example usage for org.eclipse.jdt.core ToolFactory createDefaultClassFileReader.

Prototype

public static IClassFileReader createDefaultClassFileReader(String fileName, int decodingFlag) 

Source Link

Document

Create a default classfile reader, able to expose the internal representation of a given classfile according to the decoding flag used to initialize the reader.

Usage

From source file:com.inepex.classtemplater.plugin.logic.Annotation.java

License:Eclipse Public License

public Annotation(IAnnotation jdtAnnotation, ICompilationUnit compilationUnit) throws Exception {
    this.compilationUnit = compilationUnit;
    name = jdtAnnotation.getElementName();

    //default values aren't found in JDT so using AST to get them
    String[][] type = compilationUnit.findPrimaryType().resolveType(jdtAnnotation.getElementName());
    if (type != null) {
        IType annType = jdtAnnotation.getJavaProject().findType(type[0][0] + "." + type[0][1]);

        //hint to read annotation default value from a classfile
        //                  

        if (annType.getCompilationUnit() != null) {
            AnnotationASTVisitor annASTVisitor = new AnnotationASTVisitor();
            ASTParser parser = ASTParser.newParser(AST.JLS3);
            parser.setKind(ASTParser.K_COMPILATION_UNIT);
            parser.setSource(annType.getCompilationUnit());
            parser.setResolveBindings(true);
            CompilationUnit aParser = (CompilationUnit) parser.createAST(null);
            aParser.accept(annASTVisitor);
            Map<String, Object> defaultValues = annASTVisitor.getDefaultValueObjects();
            for (Entry<String, Object> entry : defaultValues.entrySet()) {
                paramObjects.put(entry.getKey(), entry.getValue());
                params.put(entry.getKey(), String.valueOf(entry.getValue()));
            }/*from w ww  . j  a v a2s.c  om*/
        } else {
            //read annotation default value from .class file
            IClassFileReader reader = ToolFactory.createDefaultClassFileReader(annType.getClassFile(),
                    IClassFileReader.ALL);
            if (reader != null) {
                for (IMethodInfo methodInfo : reader.getMethodInfos()) {
                    if (methodInfo.getAttributes().length > 0
                            && methodInfo.getAttributes()[0] instanceof AnnotationDefaultAttribute) {
                        String name = new String(methodInfo.getName());
                        Object value = parseDefaultObjectValueFromAnnotationDefaultAttribute(
                                (AnnotationDefaultAttribute) (methodInfo.getAttributes()[0]),
                                new String(methodInfo.getDescriptor()));
                        if (value != null) {
                            paramObjects.put(name, value);
                            params.put(name, String.valueOf(value));
                        }
                    }
                    //                  System.out.println(methodInfo.getName());

                }
            }
        }
    }

    for (IMemberValuePair pair : jdtAnnotation.getMemberValuePairs()) {
        try {
            params.put(pair.getMemberName(), String.valueOf(pair.getValue()));
            paramObjects.put(pair.getMemberName(), pair.getValue());
        } catch (ClassCastException e) {
            Log.log("Could not cast value of annotation-attribute: " + name + ", " + pair.getMemberName()
                    + ". \n" + "Only string values can be used for annotation-attribute");
        }
    }
}

From source file:com.redhat.ceylon.eclipse.code.wizard.ClassPathDetector.java

License:Open Source License

private IPath detectOutputFolder() throws CoreException {
    HashSet<IPath> classFolders = new HashSet<IPath>();

    for (Iterator<IResource> iter = fClassFiles.iterator(); iter.hasNext();) {
        IFile file = (IFile) iter.next();
        IClassFileReader reader = null;//from  w w  w.  ja v a  2s.  co m
        InputStream content = null;
        try {
            content = file.getContents();
            reader = ToolFactory.createDefaultClassFileReader(content, IClassFileReader.CLASSFILE_ATTRIBUTES);
        } finally {
            try {
                if (content != null)
                    content.close();
            } catch (IOException e) {
                throw new CoreException(new Status(IStatus.ERROR, JavaPlugin.getPluginId(), IStatus.ERROR,
                        Messages.format("error closing file",
                                BasicElementLabels.getPathLabel(file.getFullPath(), false)),
                        e));
            }
        }
        if (reader == null) {
            continue; // problematic class file
        }
        char[] className = reader.getClassName();
        ISourceAttribute sourceAttribute = reader.getSourceFileAttribute();
        if (className != null && sourceAttribute != null && sourceAttribute.getSourceFileName() != null) {
            IPath packPath = file.getParent().getFullPath();
            int idx = CharOperation.lastIndexOf('/', className) + 1;
            IPath relPath = new Path(new String(className, 0, idx));
            IPath cuPath = relPath.append(new String(sourceAttribute.getSourceFileName()));

            IPath resPath = null;
            if (idx == 0) {
                resPath = packPath;
            } else {
                IPath folderPath = getFolderPath(packPath, relPath);
                if (folderPath != null) {
                    resPath = folderPath;
                }
            }
            if (resPath != null) {
                IPath path = findInSourceFolders(cuPath);
                if (path != null) {
                    return resPath;
                } else {
                    classFolders.add(resPath);
                }
            }
        }
    }
    IPath projPath = fProject.getFullPath();
    if (fSourceFolders.size() == 1 && classFolders.isEmpty() && fSourceFolders.get(projPath) != null) {
        return projPath;
    } else {
        IPath path = projPath
                .append(PreferenceConstants.getPreferenceStore().getString(PreferenceConstants.SRCBIN_BINNAME));
        while (classFolders.contains(path)) {
            path = new Path(path.toString() + '1');
        }
        return path;
    }
}

From source file:com.siteview.mde.internal.ui.search.dependencies.PackageFinder.java

License:Open Source License

public static Set findPackagesInClassFiles(IClassFile[] files, IProgressMonitor monitor) {
    Set packages = new HashSet();
    monitor.beginTask(MDEUIMessages.PackageFinder_taskName, files.length);
    for (int i = 0; i < files.length; i++) {
        IClassFileReader reader = ToolFactory.createDefaultClassFileReader(files[i], IClassFileReader.ALL);
        if (reader != null)
            computeReferencedTypes(reader, packages);
        monitor.worked(1);/*from ww w . j  a va2s . c om*/
    }
    monitor.done();
    return packages;
}

From source file:de.bodden.tamiflex.resolution.MethodResolver.java

License:Open Source License

private static void disambiguateMethodByLineNumber(String containerClassName, String methodName,
        IProject containerProject, int lineNumber) {
    IJavaProject javaProject = JavaCore.create(containerProject);
    try {/*from  w w w .j av  a  2  s  .c om*/
        IType type = javaProject.findType(containerClassName, (IProgressMonitor) null);
        ICompilationUnit compilationUnit = type.getCompilationUnit();

        if (compilationUnit != null) {
            ASTParser parser = ASTParser.newParser(AST.JLS3);
            parser.setSource(compilationUnit);
            parser.setResolveBindings(true);

            CompilationUnit cu = (CompilationUnit) parser.createAST(null);
            final int linePosition = cu.getPosition(lineNumber, 0);

            cu.accept(new ASTVisitor() {

                public boolean visit(MethodDeclaration method) {
                    if (method.getStartPosition() <= linePosition
                            && method.getStartPosition() + method.getLength() >= linePosition) {
                        //method is resolved
                        resolvedMethods.clear();
                        resolvedMethods.add((IMethod) method.resolveBinding().getJavaElement());
                    }
                    return false;
                }

            });
        } else {
            IClassFile classFile = type.getClassFile();
            if (classFile != null) {
                IClassFileReader reader = ToolFactory.createDefaultClassFileReader(classFile,
                        IClassFileReader.METHOD_INFOS | IClassFileReader.METHOD_BODIES);
                for (IMethodInfo method : reader.getMethodInfos()) {
                    String currMethodName = new String(method.getName());
                    if (!currMethodName.equals(methodName))
                        continue;

                    ICodeAttribute codeAttribute = method.getCodeAttribute();
                    ILineNumberAttribute lineNumberAttribute = codeAttribute.getLineNumberAttribute();
                    if (lineNumberAttribute != null) {
                        int[][] lineNumberTable = lineNumberAttribute.getLineNumberTable();
                        if (lineNumberTable != null && lineNumberTable.length > 0) {
                            int startLine = Integer.MAX_VALUE;
                            int endLine = 0;
                            for (int[] entry : lineNumberTable) {
                                int line = entry[1];
                                startLine = Math.min(startLine, line);
                                endLine = Math.max(endLine, line);
                            }
                            if (startLine >= lineNumber && endLine <= lineNumber) {
                                char[][] parameterTypes = Signature.getParameterTypes(method.getDescriptor());
                                String[] parameterTypeNames = new String[parameterTypes.length];
                                int i = 0;
                                for (char[] cs : parameterTypes) {
                                    parameterTypeNames[i] = new String(cs);
                                    i++;
                                }
                                IMethod iMethod = type.getMethod(currMethodName, parameterTypeNames);

                                //method resolved
                                resolvedMethods.clear();
                                resolvedMethods.add(iMethod);
                            }
                        }
                    }
                }
            }
        }
    } catch (JavaModelException e) {
        e.printStackTrace();
    }
}

From source file:edu.uci.ics.sourcerer.tools.java.extractor.eclipse.NamingAdvisor.java

License:Open Source License

private void addClassFile(IClassFile classFile) {
    IClassFileReader reader = ToolFactory.createDefaultClassFileReader(classFile,
            IClassFileReader.CONSTANT_POOL | IClassFileReader.METHOD_INFOS);
    IConstantPool constants = reader.getConstantPool();
    for (int i = 0, max = constants.getConstantPoolCount(); i < max; i++) {
        switch (constants.getEntryKind(i)) {
        case IConstantPoolConstant.CONSTANT_Class: {
            IConstantPoolEntry constant = constants.decodeEntry(i);
            addClass(new String(constant.getClassInfoName()).replace('/', '.'));
            break;
        }//from   w  ww.  j  ava2 s  .c  o  m
        case IConstantPoolConstant.CONSTANT_Fieldref: {
            IConstantPoolEntry constant = constants.decodeEntry(i);
            addClassSig(constant.getFieldDescriptor());
            break;
        }
        case IConstantPoolConstant.CONSTANT_Methodref: {
            IConstantPoolEntry constant = constants.decodeEntry(i);
            addMethod(new String(constant.getClassName()), new String(constant.getMethodName()),
                    constant.getMethodDescriptor());
            break;
        }
        case IConstantPoolConstant.CONSTANT_InterfaceMethodref: {
            IConstantPoolEntry constant = constants.decodeEntry(i);
            addMethod(new String(constant.getClassName()), new String(constant.getMethodName()),
                    constant.getMethodDescriptor());
            break;
        }
        default:
        }
    }

    // Add the method parameter / return types
    for (IMethodInfo method : reader.getMethodInfos()) {
        for (char[] p : Signature.getParameterTypes(method.getDescriptor())) {
            addClassSig(p);
        }
        addClassSig(Signature.getReturnType(method.getDescriptor()));
    }
}

From source file:in.software.analytics.parichayana.core.internal.builder.ParichayanaBuilder.java

License:Open Source License

/**
 * @param delta//  w ww.  j  a v  a2s .  c  om
 * @param monitor
 * @throws CoreException 
 */
private void buildDelta(IResourceDelta delta, IProgressMonitor monitor) throws CoreException {
    final List<ICompilationUnit> units = new ArrayList<ICompilationUnit>();
    delta.accept(new IResourceDeltaVisitor() {

        @Override
        public boolean visit(IResourceDelta delta) throws CoreException {
            IResource res = delta.getResource();
            switch (res.getType()) {
            case IResource.ROOT:
                return true;
            case IResource.PROJECT:
                return true;
            case IResource.FOLDER:
                return true;
            case IResource.FILE:
                IJavaElement element = JavaCore.create(res);
                ICompilationUnit cu = null;
                if (element instanceof IClassFile) {
                    cu = getCompilationUnit((IClassFile) element);
                }
                if (element instanceof ICompilationUnit) {
                    cu = (ICompilationUnit) element;
                }
                if (cu != null) {
                    cleanupMarkers(cu.getUnderlyingResource());
                    if (units.contains(cu)) {
                        return false;
                    }
                    units.add(cu);
                }
                return false;
            default:
                return false;
            }
        }

        public ICompilationUnit getCompilationUnit(IClassFile classFile) {
            IClassFileReader classFileReader = ToolFactory.createDefaultClassFileReader(classFile,
                    IClassFileReader.CLASSFILE_ATTRIBUTES);
            if (classFileReader != null) {
                char[] className = classFileReader.getClassName();
                if (className != null) {
                    String fqn = new String(classFileReader.getClassName()).replace("/", "."); //$NON-NLS-1$ //$NON-NLS-2$
                    IJavaProject javaProject = classFile.getJavaProject();
                    IType sourceType = null;
                    try {
                        sourceType = javaProject.findType(fqn);
                        if (sourceType != null) {
                            return sourceType.getCompilationUnit();
                        }
                    } catch (JavaModelException e) {
                        // ignore
                    }
                }
            }
            return null;
        }
    });
    build(units, monitor);
}

From source file:net.rim.ejde.internal.packaging.PackagingManager.java

License:Open Source License

/**
 * Checks if a jar file is a MidletJar created by rapc.
 *
 * @param f// ww  w. j  a  v a2 s. c o m
 * @return
 */
static public int getJarFileType(File f) {
    int type = 0x0;
    if (!f.exists()) {
        return type;
    }
    java.util.jar.JarFile jar = null;
    try {
        jar = new java.util.jar.JarFile(f, false);
        java.util.jar.Manifest manifest = jar.getManifest();
        if (manifest != null) {
            java.util.jar.Attributes attributes = manifest.getMainAttributes();
            String profile = attributes.getValue("MicroEdition-Profile");
            if (profile != null) {
                if ("MIDP-1.0".equals(profile) || "MIDP-2.0".equals(profile)) {
                    type = type | MIDLET_JAR;
                }
            }
        }
        Enumeration<JarEntry> entries = jar.entries();
        JarEntry entry;
        String entryName;
        InputStream is = null;
        IClassFileReader classFileReader = null;
        // check the attribute of the class files in the jar file
        for (; entries.hasMoreElements();) {
            entry = entries.nextElement();
            entryName = entry.getName();
            if (entryName.endsWith(IConstants.CLASS_FILE_EXTENSION_WITH_DOT)) {
                is = jar.getInputStream(entry);
                classFileReader = ToolFactory.createDefaultClassFileReader(is, IClassFileReader.ALL);
                if (isEvisceratedClass(classFileReader)) {
                    type = type | EVISCERATED_JAR;
                    break;
                }
            }
        }
    } catch (IOException e) {
        _log.error(e.getMessage());
    } finally {
        try {
            if (jar != null) {
                jar.close();
            }
        } catch (IOException e) {
            _log.error(e.getMessage());
        }
    }
    return type;
}

From source file:org.codehaus.jdt.groovy.model.GroovyClassFileWorkingCopy.java

License:Open Source License

/**
 * @see Openable#openBuffer(IProgressMonitor, Object)
 *///from  w  ww. j a v  a  2 s  . com
protected IBuffer openBuffer(IProgressMonitor pm, Object info) throws JavaModelException {

    // create buffer
    IBuffer buffer = this.owner.createBuffer(this);
    if (buffer == null)
        return null;

    // set the buffer source
    if (buffer.getCharacters() == null) {
        IBuffer classFileBuffer = this.classFile.getBuffer();
        if (classFileBuffer != null) {
            buffer.setContents(classFileBuffer.getCharacters());
        } else {
            // Disassemble
            IClassFileReader reader = ToolFactory.createDefaultClassFileReader(this.classFile,
                    IClassFileReader.ALL);
            Disassembler disassembler = new Disassembler();
            String contents = disassembler.disassemble(reader, Util.getLineSeparator("", getJavaProject()), //$NON-NLS-1$
                    ClassFileBytesDisassembler.WORKING_COPY);
            buffer.setContents(contents);
        }
    }

    // add buffer to buffer cache
    BufferManager bufManager = getBufferManager();

    // GROOVY Change access to private member
    // old
    // bufManager.addBuffer(buffer);
    // new
    if (buffer.getContents() != null) {
        ReflectionUtils.executePrivateMethod(BufferManager.class, "addBuffer", new Class<?>[] { IBuffer.class }, //$NON-NLS-1$
                bufManager, new Object[] { buffer });
    }
    // GROOVY End

    // listen to buffer changes
    buffer.addBufferChangedListener(this);

    return buffer;
}

From source file:org.eclipse.acceleo.common.internal.utils.workspace.AcceleoDeltaVisitor.java

License:Open Source License

/**
 * {@inheritDoc}// w  w  w . j ava 2 s.co m
 * 
 * @see org.eclipse.core.resources.IResourceDeltaVisitor#visit(org.eclipse.core.resources.IResourceDelta)
 */
public boolean visit(IResourceDelta delta) throws CoreException {
    if (delta == null || 0 == (delta.getKind() & IResourceDelta.CHANGED)) {
        return false;
    }
    boolean visit = false;
    IResource resource = delta.getResource();
    if (resource != null) {
        switch (resource.getType()) {
        case IResource.FILE:
            if (0 == (delta.getFlags() & IResourceDelta.CONTENT)) {
                break;
            }
            if ("class".equals(resource.getFullPath().getFileExtension())) { //$NON-NLS-1$
                final IClassFileReader reader = ToolFactory.createDefaultClassFileReader(
                        resource.getLocation().toOSString(), IClassFileReader.CLASSFILE_ATTRIBUTES);
                changedClasses.add(new String(reader.getClassName()).replace("/", ".")); //$NON-NLS-1$ //$NON-NLS-2$
            }
            break;
        case IResource.PROJECT:
            changedProjects.add((IProject) resource);
            visit = true;
            break;
        default:
            visit = true;
        }
    }
    return visit;
}

From source file:org.eclipse.ajdt.internal.ui.editor.quickfix.AJSerialVersionHashOperation.java

License:Open Source License

public static Long calculateSerialVersionId(ITypeBinding typeBinding, final IProgressMonitor monitor)
        throws CoreException, IOException {
    try {//w w  w . j ava  2s.  c  o  m
        IFile classfileResource = getClassfile(typeBinding);
        if (classfileResource == null)
            return null;

        InputStream contents = classfileResource.getContents();
        try {
            IClassFileReader cfReader = ToolFactory.createDefaultClassFileReader(contents,
                    IClassFileReader.ALL);
            if (cfReader != null) {
                return calculateSerialVersionId(cfReader);
            }
        } finally {
            contents.close();
        }
        return null;
    } finally {
        if (monitor != null)
            monitor.done();
    }
}