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

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

Introduction

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

Prototype

boolean isBinary();

Source Link

Document

Returns whether this member is from a class file.

Usage

From source file:at.bestsolution.fxide.jdt.text.viewersupport.JavaElementLabelComposer.java

License:Open Source License

/**
 * Appends the label for a type. Considers the T_* flags.
 *
 * @param type the element to render//from   w  w  w. j  a v  a2s  .  c o m
 * @param flags the rendering flags. Flags with names starting with 'T_' are considered.
 */
public void appendTypeLabel(IType type, long flags) {

    if (getFlag(flags, JavaElementLabels.T_FULLY_QUALIFIED)) {
        IPackageFragment pack = type.getPackageFragment();
        if (!pack.isDefaultPackage()) {
            appendPackageFragmentLabel(pack, (flags & QUALIFIER_FLAGS));
            fBuffer.append('.');
        }
    }
    IJavaElement parent = type.getParent();
    if (getFlag(flags, JavaElementLabels.T_FULLY_QUALIFIED | JavaElementLabels.T_CONTAINER_QUALIFIED)) {
        IType declaringType = type.getDeclaringType();
        if (declaringType != null) {
            appendTypeLabel(declaringType, JavaElementLabels.T_CONTAINER_QUALIFIED | (flags & QUALIFIER_FLAGS));
            fBuffer.append('.');
        }
        int parentType = parent.getElementType();
        if (parentType == IJavaElement.METHOD || parentType == IJavaElement.FIELD
                || parentType == IJavaElement.INITIALIZER) { // anonymous or local
            appendElementLabel(parent, 0);
            fBuffer.append('.');
        }
    }

    String typeName;
    boolean isAnonymous = false;
    if (type.isLambda()) {
        typeName = "() -> {...}"; //$NON-NLS-1$
        try {
            String[] superInterfaceSignatures = type.getSuperInterfaceTypeSignatures();
            if (superInterfaceSignatures.length > 0) {
                typeName = typeName + ' ' + getSimpleTypeName(type, superInterfaceSignatures[0]);
            }
        } catch (JavaModelException e) {
            //ignore
        }

    } else {
        typeName = getElementName(type);
        try {
            isAnonymous = type.isAnonymous();
        } catch (JavaModelException e1) {
            // should not happen, but let's play safe:
            isAnonymous = typeName.length() == 0;
        }
        if (isAnonymous) {
            try {
                if (parent instanceof IField && type.isEnum()) {
                    typeName = '{' + JavaElementLabels.ELLIPSIS_STRING + '}';
                } else {
                    String supertypeName = null;
                    String[] superInterfaceSignatures = type.getSuperInterfaceTypeSignatures();
                    if (superInterfaceSignatures.length > 0) {
                        supertypeName = getSimpleTypeName(type, superInterfaceSignatures[0]);
                    } else {
                        String supertypeSignature = type.getSuperclassTypeSignature();
                        if (supertypeSignature != null) {
                            supertypeName = getSimpleTypeName(type, supertypeSignature);
                        }
                    }
                    if (supertypeName == null) {
                        typeName = JavaUIMessages.JavaElementLabels_anonym;
                    } else {
                        typeName = Messages.format(JavaUIMessages.JavaElementLabels_anonym_type, supertypeName);
                    }
                }
            } catch (JavaModelException e) {
                //ignore
                typeName = JavaUIMessages.JavaElementLabels_anonym;
            }
        }
    }
    fBuffer.append(typeName);

    if (getFlag(flags, JavaElementLabels.T_TYPE_PARAMETERS)) {
        if (getFlag(flags, JavaElementLabels.USE_RESOLVED) && type.isResolved()) {
            BindingKey key = new BindingKey(type.getKey());
            if (key.isParameterizedType()) {
                String[] typeArguments = key.getTypeArguments();
                appendTypeArgumentSignaturesLabel(type, typeArguments, flags);
            } else {
                String[] typeParameters = Signature.getTypeParameters(key.toSignature());
                appendTypeParameterSignaturesLabel(typeParameters, flags);
            }
        } else if (type.exists()) {
            try {
                appendTypeParametersLabels(type.getTypeParameters(), flags);
            } catch (JavaModelException e) {
                // ignore
            }
        }
    }

    // category
    if (getFlag(flags, JavaElementLabels.T_CATEGORY) && type.exists()) {
        try {
            appendCategoryLabel(type, flags);
        } catch (JavaModelException e) {
            // ignore
        }
    }

    // post qualification
    if (getFlag(flags, JavaElementLabels.T_POST_QUALIFIED)) {
        int offset = fBuffer.length();
        fBuffer.append(JavaElementLabels.CONCAT_STRING);
        IType declaringType = type.getDeclaringType();
        if (declaringType == null && type.isBinary() && isAnonymous) {
            // workaround for Bug 87165: [model] IType#getDeclaringType() does not work for anonymous binary type
            String tqn = type.getTypeQualifiedName();
            int lastDollar = tqn.lastIndexOf('$');
            if (lastDollar != 1) {
                String declaringTypeCF = tqn.substring(0, lastDollar) + ".class"; //$NON-NLS-1$
                declaringType = type.getPackageFragment().getClassFile(declaringTypeCF).getType();
                try {
                    ISourceRange typeSourceRange = type.getSourceRange();
                    if (declaringType.exists() && SourceRange.isAvailable(typeSourceRange)) {
                        IJavaElement realParent = declaringType.getTypeRoot()
                                .getElementAt(typeSourceRange.getOffset() - 1);
                        if (realParent != null) {
                            parent = realParent;
                        }
                    }
                } catch (JavaModelException e) {
                    // ignore
                }
            }
        }
        if (declaringType != null) {
            appendTypeLabel(declaringType, JavaElementLabels.T_FULLY_QUALIFIED | (flags & QUALIFIER_FLAGS));
            int parentType = parent.getElementType();
            if (parentType == IJavaElement.METHOD || parentType == IJavaElement.FIELD
                    || parentType == IJavaElement.INITIALIZER) { // anonymous or local
                fBuffer.append('.');
                appendElementLabel(parent, 0);
            }
        } else {
            appendPackageFragmentLabel(type.getPackageFragment(), flags & QUALIFIER_FLAGS);
        }
        //         if (getFlag(flags, JavaElementLabels.COLORIZE)) {
        //            fBuffer.setStyle(offset, fBuffer.length() - offset, QUALIFIER_STYLE);
        //         }
    }
}

From source file:ca.uvic.chisel.javasketch.internal.JavaSearchUtils.java

License:Open Source License

private static IJavaElement searchForType(String classSignature, IJavaSearchScope scope,
        IProgressMonitor monitor) throws CoreException, InterruptedException {
    try {// www . j  a  v  a  2s. c o m
        synchronized (cachedTypes) {
            IType found = cachedTypes.get(classSignature);
            if (found != null) {
                return found;
            }
            SearchEngine engine = new SearchEngine();
            SearchPattern pattern = null;
            SearchParticipant participant = SearchEngine.getDefaultSearchParticipant();
            LocalSearchRequestor requestor = new LocalSearchRequestor();
            pattern = SearchPattern.createPattern(classSignature.replace('$', '.'), IJavaSearchConstants.CLASS,
                    IJavaSearchConstants.DECLARATIONS, SearchPattern.R_EXACT_MATCH);

            engine.search(pattern, new SearchParticipant[] { participant }, scope, requestor, monitor);
            if (requestor.matches.size() > 0) {
                found = (IType) requestor.matches.get(0).getElement();
                if (found.getFullyQualifiedName().equals(classSignature)) {
                    cachedTypes.put(classSignature, found);
                    return found;
                }

            }
            String[] className = classSignature.split("\\$");
            found = cachedTypes.get(className[0]);
            if (found == null) {

                //find the class
                pattern = SearchPattern.createPattern(className[0], IJavaSearchConstants.CLASS,
                        IJavaSearchConstants.DECLARATIONS, SearchPattern.R_EXACT_MATCH);

                engine.search(pattern, new SearchParticipant[] { participant }, scope, requestor, monitor);
                if (monitor.isCanceled()) {
                    throw new InterruptedException();
                }
                if (requestor.matches.size() > 0) {
                    found = (IType) requestor.matches.get(0).getElement();
                    if (found.getFullyQualifiedName().equals(classSignature)) {
                        for (SearchMatch match : requestor.matches) {
                            IType temp = (IType) match.getElement();
                            if (temp.getTypeRoot() instanceof ICompilationUnit) {
                                //prefer source types.
                                found = temp;
                                break;
                            }
                        }
                        if (cachedTypes.size() > 100) {
                            cachedTypes.clear();
                        }
                        cachedTypes.put(className[0], found);
                    } else {
                        found = null;
                    }
                }
            }
            if (found == null)
                return null;
            StringBuilder childTypeName = new StringBuilder();
            childTypeName.append(className[0]);
            //check each of the indexes for the sub-types
            for (int i = 1; i < className.length; i++) {
                childTypeName.append('$');
                childTypeName.append(className[i]);
                IType parent = found;
                found = cachedTypes.get(childTypeName.toString());

                if (found == null) {
                    boolean isAnonymous = false;
                    Integer occurrenceCount = -1;
                    try {
                        occurrenceCount = Integer.parseInt(className[i]);
                        isAnonymous = true;
                    } catch (NumberFormatException e) {
                        isAnonymous = false;
                    }
                    if (isAnonymous) {
                        if (!parent.isBinary()) {
                            found = parent.getType("", occurrenceCount);
                            if (found != null) {
                                if (found.exists()) {
                                    cachedTypes.put(childTypeName.toString(), found);
                                    continue;
                                } else {
                                    found = null;
                                }
                            }
                        } else {
                            //if it is a binary type, there is no hope for 
                            //finding an anonymous inner class. Use the number
                            //as the type name, and cache the handle.
                            found = parent.getType(className[i]);
                            cachedTypes.put(childTypeName.toString(), found);
                            continue;
                        }
                    }
                    ArrayList<IType> childTypes = new ArrayList<IType>();
                    LinkedList<IJavaElement> children = new LinkedList<IJavaElement>();
                    children.addAll(Arrays.asList(parent.getChildren()));
                    while (children.size() > 0) {
                        IJavaElement child = children.removeFirst();
                        if (child instanceof IType) {
                            childTypes.add((IType) child);
                        } else if (child instanceof IMember) {
                            children.addAll(Arrays.asList(((IMember) child).getChildren()));
                        }
                    }
                    int numIndex = 0;
                    while (numIndex < className[i].length()
                            && Character.isDigit(className[i].charAt(numIndex))) {
                        numIndex++;
                    }
                    String name = className[i];
                    try {
                        //get a number at the beginning to find out if 
                        //there is an occurrence count
                        if (numIndex <= name.length()) {
                            occurrenceCount = parseInt(name.substring(0, numIndex));
                            if (occurrenceCount == null) {
                                occurrenceCount = 1;
                            }
                            if (numIndex < name.length() - 1) {
                                name = name.substring(numIndex);
                            } else {
                                name = "";
                            }
                        }
                        for (IType childType : childTypes) {
                            if ("".equals(name)) {
                                if (childType.getOccurrenceCount() == occurrenceCount) {
                                    found = childType;
                                    break;
                                }
                            } else {
                                if (name.equals(childType.getElementName())
                                        && childType.getOccurrenceCount() == occurrenceCount) {
                                    found = childType;
                                    break;
                                }
                            }
                        }
                        if (found == null) {
                            if ("".equals(name)) {
                                found = parent.getTypeRoot().getJavaProject().findType(classSignature);
                                //found = parent.getType("" + occurrenceCount);
                            } else {
                                found = parent.getType(name, occurrenceCount);
                            }
                        }
                        cachedTypes.put(childTypeName.toString(), found);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

            }
            return found;
        }
    } catch (Exception e) {
        SketchPlugin.getDefault().log(e);
        return null;
    }
}

From source file:ca.uwaterloo.gsd.wpi.code.WpiMappingInterpreter.java

License:Open Source License

public WorkspacePluginModel getWorkspacePluginModel(IJavaProject project, IType type) {
    IFile pluginXml = null;/*from   w w w.j  av  a  2 s.co m*/
    InputStream pluginXmlInputStream = null;

    if (!type.isBinary() && type.getJavaProject().equals(project))
        pluginXml = project.getProject().getFile("plugin.xml");
    else {
        IJavaElement parent = type.getPackageFragment().getParent();
        if (parent instanceof IPackageFragmentRoot) {
            IPackageFragmentRoot root = (IPackageFragmentRoot) parent;
            Object[] resources;
            try {
                resources = root.getNonJavaResources();
                for (int i = 0; i < resources.length; i++) {
                    if (resources[i] instanceof IFile) {
                        IFile file = (IFile) resources[i];
                        if (file.getName().equals("plugin.xml")) {
                            pluginXml = file;
                            break;
                        }
                    } else if (resources[i] instanceof JarEntryFile) {
                        JarEntryFile file = (JarEntryFile) resources[i];
                        if (file.getName().equals("plugin.xml")) {
                            pluginXmlInputStream = file.getContents();
                            break;
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    if (pluginXml != null && pluginXml.exists() || pluginXmlInputStream != null) {
        WorkspacePluginModel pluginModel = new WorkspacePluginModel(pluginXml, false);
        if (pluginModel != null) {
            if (pluginXmlInputStream != null) {
                try {
                    pluginModel.reload(pluginXmlInputStream, false);
                } catch (CoreException e) {
                    e.printStackTrace();
                }
            } else
                pluginModel.load();
        }
        return pluginModel;
    }
    return null;
}

From source file:ch.qos.logback.beagle.util.EditorUtil.java

License:Open Source License

private static String getFullyQualifiedName(IType type) {
    try {//from   ww w  .  j a v a2  s.  c o m
        if (type.isBinary() && !type.isAnonymous()) {
            IType declaringType = type.getDeclaringType();
            if (declaringType != null) {
                return getFullyQualifiedName(declaringType) + '.' + type.getElementName();
            }
        }
    } catch (JavaModelException e) {
        // ignore
    }
    return type.getFullyQualifiedName('.');
}

From source file:com.android.ide.eclipse.adt.internal.refactorings.core.RenameResourceXmlTextAction.java

License:Open Source License

@Nullable
private IType findType(@NonNull String className, @NonNull IProject project) {
    IType type = null;
    try {//from w w  w  .  j ava  2  s.com
        IJavaProject javaProject = BaseProjectHelper.getJavaProject(project);
        type = javaProject.findType(className);
        if (type == null || !type.exists()) {
            return null;
        }
        if (!type.isBinary()) {
            return type;
        }
        // See if this class is coming through a library project jar file and
        // if so locate the real class
        ProjectState projectState = Sdk.getProjectState(project);
        if (projectState != null) {
            List<IProject> libraries = projectState.getFullLibraryProjects();
            for (IProject library : libraries) {
                javaProject = BaseProjectHelper.getJavaProject(library);
                type = javaProject.findType(className);
                if (type != null && type.exists() && !type.isBinary()) {
                    return type;
                }
            }
        }
    } catch (CoreException e) {
        AdtPlugin.log(e, null);
    }

    return null;
}

From source file:com.android.ide.eclipse.cheatsheets.actions.SetBreakpoint.java

License:Open Source License

/**
  * Returns the package qualified name, while accounting for the fact that a source file might
  * not have a project/* ww  w .j  av a2s  .  co  m*/
  * @param type the type to ensure the package qualified name is created for
  * @return the package qualified name
  * @since 3.3
  */
private String createQualifiedTypeName(IType type) {
    String tname = pruneAnonymous(type);
    try {
        String packName = null;
        if (type.isBinary()) {
            packName = type.getPackageFragment().getElementName();
        } else {
            IPackageDeclaration[] pd = type.getCompilationUnit().getPackageDeclarations();
            if (pd.length > 0) {
                packName = pd[0].getElementName();
            }
        }
        if (packName != null && !packName.equals(EMPTY_STRING)) {
            tname = packName + "." + tname; //$NON-NLS-1$
        }
    } catch (JavaModelException e) {
    }
    return tname;
}

From source file:com.astamuse.asta4d.ide.eclipse.util.JdtUtils.java

License:Open Source License

public static String resolveClassName(String className, IType type) {
    if (className == null || type == null) {
        return className;
    }//from  w w w.j av  a2s.c  o  m
    // replace binary $ inner class name syntax with . for source level
    className = className.replace('$', '.');
    String dotClassName = new StringBuilder().append('.').append(className).toString();

    IProject project = type.getJavaProject().getProject();

    try {
        // Special handling for some well-know classes
        if (className.startsWith("java.lang") && getJavaType(project, className) != null) {
            return className;
        }

        // Check if the class is imported
        if (!type.isBinary()) {

            // Strip className to first segment to support ReflectionUtils.MethodCallback
            int ix = className.lastIndexOf('.');
            String firstClassNameSegment = className;
            if (ix > 0) {
                firstClassNameSegment = className.substring(0, ix);
            }

            // Iterate the imports
            for (IImportDeclaration importDeclaration : type.getCompilationUnit().getImports()) {
                String importName = importDeclaration.getElementName();
                // Wildcard imports -> check if the package + className is a valid type
                if (importDeclaration.isOnDemand()) {
                    String newClassName = new StringBuilder(importName.substring(0, importName.length() - 1))
                            .append(className).toString();
                    if (getJavaType(project, newClassName) != null) {
                        return newClassName;
                    }
                }
                // Concrete import matching .className at the end -> check if type exists
                else if (importName.endsWith(dotClassName) && getJavaType(project, importName) != null) {
                    return importName;
                }
                // Check if className is multi segmented (ReflectionUtils.MethodCallback)
                // -> check if the first segment
                else if (!className.equals(firstClassNameSegment)) {
                    if (importName.endsWith(firstClassNameSegment)) {
                        String newClassName = new StringBuilder(
                                importName.substring(0, importName.lastIndexOf('.') + 1)).append(className)
                                        .toString();
                        if (getJavaType(project, newClassName) != null) {
                            return newClassName;
                        }
                    }
                }
            }
        }

        // Check if the class is in the same package as the type
        String packageName = type.getPackageFragment().getElementName();
        String newClassName = new StringBuilder(packageName).append(dotClassName).toString();
        if (getJavaType(project, newClassName) != null) {
            return newClassName;
        }

        // Check if the className is sufficient (already fully-qualified)
        if (getJavaType(project, className) != null) {
            return className;
        }

        // Check if the class is coming from the java.lang
        newClassName = new StringBuilder("java.lang").append(dotClassName).toString();
        if (getJavaType(project, newClassName) != null) {
            return newClassName;
        }

        // Fall back to full blown resolution
        String[][] fullInter = type.resolveType(className);
        if (fullInter != null && fullInter.length > 0) {
            return fullInter[0][0] + "." + fullInter[0][1];
        }
    } catch (JavaModelException e) {
        // SpringCore.log(e);
    }

    return className;
}

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

License:Open Source License

public String[] getCategories() throws JavaModelException {
    IType type = (IType) getAncestor(IJavaElement.TYPE);
    if (type == null)
        return CharOperation.NO_STRINGS;
    if (type.isBinary()) {
        return CharOperation.NO_STRINGS;
    } else {//from  w  ww  . j a  v  a2 s .co m
        SourceTypeElementInfo info = (SourceTypeElementInfo) ((SourceType) type).getElementInfo();
        HashMap map = info.getCategories();
        if (map == null)
            return CharOperation.NO_STRINGS;
        String[] categories = (String[]) map.get(this);
        if (categories == null)
            return CharOperation.NO_STRINGS;
        return categories;
    }
}

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

License:Open Source License

private boolean enclosesType(IType type, boolean recurse) {
    if (this.subTypes != null) {
        // searching subtypes
        if (this.subTypes.contains(type)) {
            return true;
        }//w  w w. j a  v a  2  s.c om
        // be flexible: look at original element (see bug 14106 and below)
        IType original = type.isBinary() ? null : (IType) type.getPrimaryElement();
        if (original != type && this.subTypes.contains(original)) {
            return true;
        }
    } else {
        if (this.hierarchy.contains(type)) {
            return true;
        } else {
            // be flexible: look at original element (see bug 14106 Declarations in Hierarchy does not find declarations in hierarchy)
            IType original;
            if (!type.isBinary() && (original = (IType) type.getPrimaryElement()) != null) {
                if (this.hierarchy.contains(original)) {
                    return true;
                }
            }
        }
    }
    if (recurse) {
        // queried type is enclosed in this scope if one of its members is:
        try {
            IType[] memberTypes = type.getTypes();
            for (int i = 0; i < memberTypes.length; i++) {
                if (enclosesType(memberTypes[i], recurse)) {
                    return true;
                }
            }
        } catch (JavaModelException e) {
            return false;
        }
    }
    return false;
}

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  ww w.  jav a2 s. c o m

    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);
            }
        }
    }
}