Example usage for org.eclipse.jdt.core IType getClassFile

List of usage examples for org.eclipse.jdt.core IType getClassFile

Introduction

In this page you can find the example usage for org.eclipse.jdt.core IType getClassFile.

Prototype

@Override
IOrdinaryClassFile getClassFile();

Source Link

Document

Strengthen the contract of the inherited method to signal that the returned class file is always an IOrdinaryClassFile .

Usage

From source file:ca.uvic.chisel.diver.sequencediagrams.sc.java.model.ASTUTils.java

License:Open Source License

public static ASTNode getASTFor(IType type) {
    try {/*from  w w w. j  a va2  s .  c  om*/
        ICompilationUnit unit = type.getCompilationUnit();
        if (unit != null) {
            return getASTFor(unit);
        }
        IClassFile classFile = type.getClassFile();
        if (classFile != null) {
            return getASTFor(classFile);
        }
    } catch (Exception e) {
    }
    return null;
}

From source file:ca.uvic.chisel.javasketch.internal.ast.ASTUTils.java

License:Open Source License

public static ASTNode getASTFor(IType type) {
    try {/*w  ww . j  a  v  a  2  s.co  m*/
        synchronized (cache) {
            if (cache.containsKey(type)) {
                WeakReference<ASTNode> ref = cache.get(type);
                if (!(ref.isEnqueued() || ref.get() == null)) {
                    return ref.get();
                } else {
                    cache.remove(type);
                }
            }
            ICompilationUnit unit = type.getCompilationUnit();
            ASTNode node = null;
            if (unit != null) {
                node = getASTFor(unit);
            }
            IClassFile classFile = type.getClassFile();
            if (classFile != null) {
                node = getASTFor(classFile);
            }
            if (node != null) {
                cache.put(type, new WeakReference<ASTNode>(node));
            }
            return node;
        }
    } catch (Exception e) {
    }
    return null;
}

From source file:com.android.ide.eclipse.adt.internal.editors.layout.descriptors.CustomViewDescriptorService.java

License:Open Source License

/**
 * Find the project containing this type declaration. We cannot use
 * {@link IType#getJavaProject()} since that will return the including
 * project and we're after the library project such that we can find the
 * attrs.xml file in the same project./*from  w  ww.  ja  va2s . com*/
 */
@Nullable
private static IProject getProjectDeclaringType(IType type) {
    IClassFile classFile = type.getClassFile();
    if (classFile != null) {
        IPath path = classFile.getPath();
        IWorkspaceRoot workspace = ResourcesPlugin.getWorkspace().getRoot();
        IResource resource;
        if (path.isAbsolute()) {
            resource = AdtUtils.fileToResource(path.toFile());
        } else {
            resource = workspace.findMember(path);
        }
        if (resource != null && resource.getProject() != null) {
            return resource.getProject();
        }
    }

    return null;
}

From source file:com.android.ide.eclipse.adt.internal.editors.manifest.ManifestInfo.java

License:Open Source License

/**
 * Returns all activities found in the given project (including those in libraries,
 * except for android.jar itself)// w ww .j a v a  2  s .c o m
 *
 * @param project the project
 * @return a list of activity classes as fully qualified class names
 */
@SuppressWarnings("restriction") // BinaryType
@NonNull
public static List<String> getProjectActivities(IProject project) {
    final List<String> activities = new ArrayList<String>();
    try {
        final IJavaProject javaProject = BaseProjectHelper.getJavaProject(project);
        if (javaProject != null) {
            IType[] activityTypes = new IType[0];
            IType activityType = javaProject.findType(CLASS_ACTIVITY);
            if (activityType != null) {
                ITypeHierarchy hierarchy = activityType.newTypeHierarchy(javaProject,
                        new NullProgressMonitor());
                activityTypes = hierarchy.getAllSubtypes(activityType);
                for (IType type : activityTypes) {
                    if (type instanceof BinaryType
                            && (type.getClassFile() == null || type.getClassFile().getResource() == null)) {
                        continue;
                    }
                    activities.add(type.getFullyQualifiedName());
                }
            }
        }
    } catch (CoreException e) {
        AdtPlugin.log(e, null);
    }

    return activities;
}

From source file:com.android.ide.eclipse.auidt.internal.editors.manifest.ManifestInfo.java

License:Open Source License

/**
 * Returns all activities found in the given project (including those in libraries,
 * except for android.jar itself)/*from  w  w w.j  a v  a  2 s  .c  om*/
 *
 * @param project the project
 * @return a list of activity classes as fully qualified class names
 */
@SuppressWarnings("restriction") // BinaryType
@NonNull
public static List<String> getProjectActivities(IProject project) {
    final List<String> activities = new ArrayList<String>();
    try {
        final IJavaProject javaProject = BaseProjectHelper.getJavaProject(project);
        if (javaProject != null) {
            IType[] activityTypes = new IType[0];
            IType activityType = javaProject.findType(SdkConstants.CLASS_ACTIVITY);
            if (activityType != null) {
                ITypeHierarchy hierarchy = activityType.newTypeHierarchy(javaProject,
                        new NullProgressMonitor());
                activityTypes = hierarchy.getAllSubtypes(activityType);
                for (IType type : activityTypes) {
                    if (type instanceof BinaryType
                            && (type.getClassFile() == null || type.getClassFile().getResource() == null)) {
                        continue;
                    }
                    activities.add(type.getFullyQualifiedName());
                }
            }
        }
    } catch (CoreException e) {
        AdtPlugin.log(e, null);
    }

    return activities;
}

From source file:com.codenvy.ide.ext.java.server.internal.codeassist.SelectionEngine.java

License:Open Source License

/**
 * Asks the engine to compute the selection of the given type
 * from the given context//w  w  w.  j  a v  a  2 s  .  c  o m
 *
 *  @param typeName char[]
 *      a type name which is to be resolved in the context of a compilation unit.
 *      NOTE: the type name is supposed to be correctly reduced (no whitespaces, no unicodes left)
 *
 *  @param context org.eclipse.jdt.core.IType
 *      the context in which code assist is invoked.
 */
public void selectType(char[] typeName, IType context) throws JavaModelException {
    try {
        this.acceptedAnswer = false;

        // only the type erasure are returned by IType.resolvedType(...)
        if (CharOperation.indexOf('<', typeName) != -1) {
            char[] typeSig = Signature.createCharArrayTypeSignature(typeName, false/*not resolved*/);
            typeSig = Signature.getTypeErasure(typeSig);
            typeName = Signature.toCharArray(typeSig);
        }

        CompilationUnitDeclaration parsedUnit = null;
        TypeDeclaration typeDeclaration = null;
        org.eclipse.jdt.core.ICompilationUnit cu = context.getCompilationUnit();
        if (cu != null) {
            IType[] topLevelTypes = cu.getTypes();
            int length = topLevelTypes.length;
            SourceTypeElementInfo[] topLevelInfos = new SourceTypeElementInfo[length];
            for (int i = 0; i < length; i++) {
                topLevelInfos[i] = (SourceTypeElementInfo) ((SourceType) topLevelTypes[i]).getElementInfo();
            }
            CompilationResult result = new CompilationResult(
                    (org.eclipse.jdt.internal.compiler.env.ICompilationUnit) cu, 1, 1,
                    this.compilerOptions.maxProblemsPerUnit);
            int flags = SourceTypeConverter.FIELD_AND_METHOD | SourceTypeConverter.MEMBER_TYPE;
            if (context.isAnonymous() || context.isLocal())
                flags |= SourceTypeConverter.LOCAL_TYPE;
            parsedUnit = SourceTypeConverter.buildCompilationUnit(topLevelInfos, flags,
                    this.parser.problemReporter(), result);
            if (parsedUnit != null && parsedUnit.types != null) {
                if (DEBUG) {
                    System.out.println("SELECTION - Diet AST :"); //$NON-NLS-1$
                    System.out.println(parsedUnit.toString());
                }
                // find the type declaration that corresponds to the original source type
                typeDeclaration = new ASTNodeFinder(parsedUnit).findType(context);
            }
        } else { // binary type
            ClassFile classFile = (ClassFile) context.getClassFile();
            ClassFileReader reader = (ClassFileReader) classFile.getBinaryTypeInfo(
                    (IFile) null/*classFile.resource()*/,
                    false/*don't fully initialize so as to keep constant pool (used below)*/);
            CompilationResult result = new CompilationResult(reader.getFileName(), 1, 1,
                    this.compilerOptions.maxProblemsPerUnit);
            parsedUnit = new CompilationUnitDeclaration(this.parser.problemReporter(), result, 0);
            HashSetOfCharArrayArray typeNames = new HashSetOfCharArrayArray();

            BinaryTypeConverter converter = new BinaryTypeConverter(this.parser.problemReporter(), result,
                    typeNames);
            typeDeclaration = converter.buildTypeDeclaration(context, parsedUnit);
            parsedUnit.imports = converter.buildImports(reader);
        }

        if (typeDeclaration != null) {

            // add fake field with the type we're looking for
            // note: since we didn't ask for fields above, there is no field defined yet
            FieldDeclaration field = new FieldDeclaration();
            int dot;
            if ((dot = CharOperation.lastIndexOf('.', typeName)) == -1) {
                this.selectedIdentifier = typeName;
                field.type = new SelectionOnSingleTypeReference(typeName, -1);
                // position not used
            } else {
                char[][] previousIdentifiers = CharOperation.splitOn('.', typeName, 0, dot);
                char[] selectionIdentifier = CharOperation.subarray(typeName, dot + 1, typeName.length);
                this.selectedIdentifier = selectionIdentifier;
                field.type = new SelectionOnQualifiedTypeReference(previousIdentifiers, selectionIdentifier,
                        new long[previousIdentifiers.length + 1]);
            }
            field.name = "<fakeField>".toCharArray(); //$NON-NLS-1$
            typeDeclaration.fields = new FieldDeclaration[] { field };

            // build bindings
            this.lookupEnvironment.buildTypeBindings(parsedUnit, null /*no access restriction*/);
            if ((this.unitScope = parsedUnit.scope) != null) {
                try {
                    // build fields
                    // note: this builds fields only in the parsed unit (the buildFieldsAndMethods flag is not passed along)
                    this.lookupEnvironment.completeTypeBindings(parsedUnit, true);

                    // resolve
                    parsedUnit.scope.faultInTypes();
                    parsedUnit.resolve();
                } catch (SelectionNodeFound e) {
                    if (e.binding != null) {
                        if (DEBUG) {
                            System.out.println("SELECTION - Selection binding :"); //$NON-NLS-1$
                            System.out.println(e.binding.toString());
                        }
                        // if null then we found a problem in the selection node
                        selectFrom(e.binding, parsedUnit, e.isDeclaration);
                    }
                }
            }
        }
        if (this.noProposal && this.problem != null) {
            this.requestor.acceptError(this.problem);
        }
    } catch (AbortCompilation e) { // ignore this exception for now since it typically means we cannot find java.lang.Object
    } finally {
        reset(true);
    }
}

From source file:com.codenvy.ide.ext.java.server.internal.core.ClassFile.java

License:Open Source License

/**
 * Opens and returns buffer on the source code associated with this class file.
 * Maps the source code to the children elements of this class file.
 * If no source code is associated with this class file,
 * <code>null</code> is returned.
 *
 * @see Openable/*from w  w  w .  ja  va  2  s  .  co  m*/
 */
protected IBuffer openBuffer(IProgressMonitor pm, Object info) throws JavaModelException {
    // Check the cache for the top-level type first
    IType outerMostEnclosingType = getOuterMostEnclosingType();
    IBuffer buffer = getBufferManager().getBuffer(outerMostEnclosingType.getClassFile());
    if (buffer == null) {
        SourceMapper mapper = getSourceMapper();
        IBinaryType typeInfo = info instanceof IBinaryType ? (IBinaryType) info : null;
        if (mapper != null) {
            buffer = mapSource(mapper, typeInfo, outerMostEnclosingType.getClassFile());
        }
    }
    return buffer;
}

From source file:com.codenvy.ide.ext.java.server.internal.core.search.matching.FieldLocator.java

License:Open Source License

protected void reportDeclaration(FieldBinding fieldBinding, MatchLocator locator, SimpleSet knownFields)
        throws CoreException {
    // ignore length field
    if (fieldBinding == ArrayBinding.ArrayLength)
        return;/*from   w  ww . j a  v a  2s.c  om*/

    ReferenceBinding declaringClass = fieldBinding.declaringClass;
    IType type = locator.lookupType(declaringClass);
    if (type == null)
        return; // case of a secondary type

    char[] bindingName = fieldBinding.name;
    IField field = type.getField(new String(bindingName));
    if (knownFields.addIfNotIncluded(field) == null)
        return;

    IResource resource = type.getResource();
    boolean isBinary = type.isBinary();
    IBinaryType info = null;
    if (isBinary) {
        if (resource == null)
            resource = type.getJavaProject().getProject();
        info = locator.getBinaryInfo((org.eclipse.jdt.internal.core.ClassFile) type.getClassFile(), resource);
        locator.reportBinaryMemberDeclaration(resource, field, fieldBinding, info, SearchMatch.A_ACCURATE);
    } else {
        if (declaringClass instanceof ParameterizedTypeBinding)
            declaringClass = ((ParameterizedTypeBinding) declaringClass).genericType();
        ClassScope scope = ((SourceTypeBinding) declaringClass).scope;
        if (scope != null) {
            TypeDeclaration typeDecl = scope.referenceContext;
            FieldDeclaration fieldDecl = null;
            FieldDeclaration[] fieldDecls = typeDecl.fields;
            int length = fieldDecls == null ? 0 : fieldDecls.length;
            for (int i = 0; i < length; i++) {
                if (CharOperation.equals(bindingName, fieldDecls[i].name)) {
                    fieldDecl = fieldDecls[i];
                    break;
                }
            }
            if (fieldDecl != null) {
                int offset = fieldDecl.sourceStart;
                this.match = new FieldDeclarationMatch(((JavaElement) field).resolved(fieldBinding),
                        SearchMatch.A_ACCURATE, offset, fieldDecl.sourceEnd - offset + 1,
                        locator.getParticipant(), resource);
                locator.report(this.match);
            }
        }
    }
}

From source file:com.codenvy.ide.ext.java.server.internal.core.search.matching.MatchLocator.java

License:Open Source License

public static ClassFileReader classFileReader(IType type) {
    IClassFile classFile = type.getClassFile();
    JavaModelManager manager = JavaModelManager.getJavaModelManager();
    if (classFile.isOpen())
        return (ClassFileReader) manager.getInfo(type);

    PackageFragment pkg = (PackageFragment) type.getPackageFragment();
    IPackageFragmentRoot root = (IPackageFragmentRoot) pkg.getParent();
    try {/*from w w  w  . j  av a  2 s  .c o  m*/
        if (!root.isArchive())
            return Util.newClassFileReader(((JavaElement) type).resource());

        ZipFile zipFile = null;
        try {
            IPath zipPath = root.getPath();
            if (JavaModelManager.ZIP_ACCESS_VERBOSE)
                System.out.println("(" + Thread.currentThread()
                        + ") [MatchLocator.classFileReader()] Creating ZipFile on " + zipPath); //$NON-NLS-1$   //$NON-NLS-2$
            zipFile = manager.getZipFile(zipPath);
            String classFileName = classFile.getElementName();
            String path = Util.concatWith(pkg.names, classFileName, '/');
            return ClassFileReader.read(zipFile, path);
        } finally {
            manager.closeZipFile(zipFile);
        }
    } catch (ClassFormatException e) {
        // invalid class file: return null
    } catch (CoreException e) {
        // cannot read class file: return null
    } catch (IOException e) {
        // cannot read class file: return null
    }
    return null;
}

From source file:com.codenvy.ide.ext.java.server.internal.core.search.matching.MatchLocator.java

License:Open Source License

protected BinaryTypeBinding cacheBinaryType(IType type, IBinaryType binaryType) throws JavaModelException {
    IType enclosingType = type.getDeclaringType();
    if (enclosingType != null)
        cacheBinaryType(enclosingType, null); // cache enclosing types first, so that binary type can be found in lookup enviroment
    if (binaryType == null) {
        ClassFile classFile = (ClassFile) type.getClassFile();
        try {//from w  w w.j  av  a2  s.c o  m
            binaryType = getBinaryInfo(classFile, classFile.resource());
        } catch (CoreException e) {
            if (e instanceof JavaModelException) {
                throw (JavaModelException) e;
            } else {
                throw new JavaModelException(e);
            }
        }
    }
    BinaryTypeBinding binding = this.lookupEnvironment.cacheBinaryType(binaryType,
            null /*no access restriction*/);
    if (binding == null) { // it was already cached as a result of a previous query
        char[][] compoundName = CharOperation.splitOn('.', type.getFullyQualifiedName().toCharArray());
        ReferenceBinding referenceBinding = this.lookupEnvironment.getCachedType(compoundName);
        if (referenceBinding != null && (referenceBinding instanceof BinaryTypeBinding))
            binding = (BinaryTypeBinding) referenceBinding; // if the binding could be found and if it comes from a binary type
    }
    return binding;
}