Search in sources :

Example 56 with IJavaElement

use of org.eclipse.jdt.core.IJavaElement in project che by eclipse.

the class JavaTypeCompletionProposalComputer method computeCompletionProposals.

/*
	 * @see org.eclipse.jdt.internal.ui.text.java.JavaCompletionProposalComputer#computeCompletionProposals(org.eclipse.jface.text.contentassist.TextContentAssistInvocationContext, org.eclipse.core.runtime.IProgressMonitor)
	 */
@Override
public List<ICompletionProposal> computeCompletionProposals(ContentAssistInvocationContext context, IProgressMonitor monitor) {
    List<ICompletionProposal> types = super.computeCompletionProposals(context, monitor);
    if (!(context instanceof JavaContentAssistInvocationContext))
        return types;
    JavaContentAssistInvocationContext javaContext = (JavaContentAssistInvocationContext) context;
    CompletionContext coreContext = javaContext.getCoreContext();
    if (coreContext != null && coreContext.getTokenLocation() != CompletionContext.TL_CONSTRUCTOR_START)
        return types;
    try {
        if (types.size() > 0 && context.computeIdentifierPrefix().length() == 0) {
            IType expectedType = javaContext.getExpectedType();
            if (expectedType != null) {
                // empty prefix completion - insert LRU types if known, but prune if they already occur in the core list
                // compute minmimum relevance and already proposed list
                int relevance = Integer.MAX_VALUE;
                Set<String> proposed = new HashSet<String>();
                for (Iterator<ICompletionProposal> it = types.iterator(); it.hasNext(); ) {
                    AbstractJavaCompletionProposal p = (AbstractJavaCompletionProposal) it.next();
                    IJavaElement element = p.getJavaElement();
                    if (element instanceof IType)
                        proposed.add(((IType) element).getFullyQualifiedName());
                    relevance = Math.min(relevance, p.getRelevance());
                }
                // insert history types
                List<String> history = JavaPlugin.getDefault().getContentAssistHistory().getHistory(expectedType.getFullyQualifiedName()).getTypes();
                relevance -= history.size() + 1;
                for (Iterator<String> it = history.iterator(); it.hasNext(); ) {
                    String type = it.next();
                    if (proposed.contains(type))
                        continue;
                    IJavaCompletionProposal proposal = createTypeProposal(relevance, type, javaContext);
                    if (proposal != null)
                        types.add(proposal);
                    relevance++;
                }
            }
        }
    } catch (BadLocationException x) {
        // log & ignore
        JavaPlugin.log(x);
    } catch (JavaModelException x) {
        // log & ignore
        JavaPlugin.log(x);
    }
    return types;
}
Also used : IJavaElement(org.eclipse.jdt.core.IJavaElement) JavaContentAssistInvocationContext(org.eclipse.jdt.ui.text.java.JavaContentAssistInvocationContext) JavaModelException(org.eclipse.jdt.core.JavaModelException) IJavaCompletionProposal(org.eclipse.jdt.ui.text.java.IJavaCompletionProposal) IType(org.eclipse.jdt.core.IType) CompletionContext(org.eclipse.jdt.core.CompletionContext) ICompletionProposal(org.eclipse.che.jface.text.contentassist.ICompletionProposal) BadLocationException(org.eclipse.jface.text.BadLocationException) HashSet(java.util.HashSet)

Example 57 with IJavaElement

use of org.eclipse.jdt.core.IJavaElement in project che by eclipse.

the class JavaElementLabelComposer method appendTypeLabel.

/**
	 * Appends the label for a type. Considers the T_* flags.
	 *
	 * @param type the element to render
	 * @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()) {
        //$NON-NLS-1$
        typeName = "() -> {...}";
        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;
                    String[] superInterfaceSignatures = type.getSuperInterfaceTypeSignatures();
                    if (superInterfaceSignatures.length > 0) {
                        supertypeName = getSimpleTypeName(type, superInterfaceSignatures[0]);
                    } else {
                        supertypeName = getSimpleTypeName(type, type.getSuperclassTypeSignature());
                    }
                    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) {
                //$NON-NLS-1$
                String declaringTypeCF = tqn.substring(0, lastDollar) + ".class";
                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);
        }
    }
}
Also used : IJavaElement(org.eclipse.jdt.core.IJavaElement) IPackageFragment(org.eclipse.jdt.core.IPackageFragment) JavaModelException(org.eclipse.jdt.core.JavaModelException) BindingKey(org.eclipse.jdt.core.BindingKey) StyledString(org.eclipse.jface.viewers.StyledString) IField(org.eclipse.jdt.core.IField) IType(org.eclipse.jdt.core.IType) ISourceRange(org.eclipse.jdt.core.ISourceRange)

Example 58 with IJavaElement

use of org.eclipse.jdt.core.IJavaElement in project che by eclipse.

the class IndexSelector method getFocusedElementsAndTypes.

/*
 * Create the list of focused jars or projects.
 */
private static IJavaElement[] getFocusedElementsAndTypes(SearchPattern pattern, IJavaElement focusElement, ObjectVector superTypes) throws JavaModelException {
    if (pattern instanceof MethodPattern) {
        // For method pattern, it needs to walk along the focus type super hierarchy
        // and add jars/projects of all the encountered types.
        IType type = (IType) pattern.focus.getAncestor(IJavaElement.TYPE);
        MethodPattern methodPattern = (MethodPattern) pattern;
        String selector = new String(methodPattern.selector);
        int parameterCount = methodPattern.parameterCount;
        ITypeHierarchy superHierarchy = type.newSupertypeHierarchy(null);
        IType[] allTypes = superHierarchy.getAllSupertypes(type);
        int length = allTypes.length;
        SimpleSet focusSet = new SimpleSet(length + 1);
        if (focusElement != null)
            focusSet.add(focusElement);
        for (int i = 0; i < length; i++) {
            IMethod[] methods = allTypes[i].getMethods();
            int mLength = methods.length;
            for (int m = 0; m < mLength; m++) {
                if (parameterCount == methods[m].getNumberOfParameters() && methods[m].getElementName().equals(selector)) {
                    IPackageFragmentRoot root = (IPackageFragmentRoot) allTypes[i].getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT);
                    IJavaElement element = root.isArchive() ? root : root.getParent();
                    focusSet.add(element);
                    if (superTypes != null)
                        superTypes.add(allTypes[i]);
                    break;
                }
            }
        }
        // Rebuilt a contiguous array
        IJavaElement[] focuses = new IJavaElement[focusSet.elementSize];
        Object[] values = focusSet.values;
        int count = 0;
        for (int i = values.length; --i >= 0; ) {
            if (values[i] != null) {
                focuses[count++] = (IJavaElement) values[i];
            }
        }
        return focuses;
    }
    if (focusElement == null)
        return new IJavaElement[0];
    return new IJavaElement[] { focusElement };
}
Also used : IJavaElement(org.eclipse.jdt.core.IJavaElement) SimpleSet(org.eclipse.jdt.internal.compiler.util.SimpleSet) MethodPattern(org.eclipse.jdt.internal.core.search.matching.MethodPattern) IType(org.eclipse.jdt.core.IType) IPackageFragmentRoot(org.eclipse.jdt.core.IPackageFragmentRoot) ITypeHierarchy(org.eclipse.jdt.core.ITypeHierarchy) IMethod(org.eclipse.jdt.core.IMethod)

Example 59 with IJavaElement

use of org.eclipse.jdt.core.IJavaElement in project che by eclipse.

the class IndexSelector method canSeeFocus.

/**
	 * Returns whether elements of the given project or jar can see the given focus (an IJavaProject or
	 * a JarPackageFragmentRot) either because the focus is part of the project or the jar, or because it is
	 * accessible throught the project's classpath
	 */
public static int canSeeFocus(SearchPattern pattern, IPath projectOrJarPath) {
    try {
        IJavaModel model = JavaModelManager.getJavaModelManager().getJavaModel();
        IJavaProject project = getJavaProject(projectOrJarPath, model);
        IJavaElement[] focuses = getFocusedElementsAndTypes(pattern, project, null);
        if (focuses.length == 0)
            return PROJECT_CAN_NOT_SEE_FOCUS;
        if (project != null) {
            return canSeeFocus(focuses, (JavaProject) project, null);
        }
        // projectOrJarPath is a jar
        // it can see the focus only if it is on the classpath of a project that can see the focus
        int result = PROJECT_CAN_NOT_SEE_FOCUS;
        IJavaProject[] allProjects = model.getJavaProjects();
        for (int i = 0, length = allProjects.length; i < length; i++) {
            JavaProject otherProject = (JavaProject) allProjects[i];
            IClasspathEntry entry = otherProject.getClasspathEntryFor(projectOrJarPath);
            if (entry != null && entry.getEntryKind() == IClasspathEntry.CPE_LIBRARY) {
                int canSeeFocus = canSeeFocus(focuses, otherProject, null);
                if (canSeeFocus == PROJECT_CAN_SEE_FOCUS)
                    return PROJECT_CAN_SEE_FOCUS;
                if (canSeeFocus == PROJECT_SOURCE_CAN_NOT_SEE_FOCUS)
                    result = PROJECT_SOURCE_CAN_NOT_SEE_FOCUS;
            }
        }
        return result;
    } catch (JavaModelException e) {
        return PROJECT_CAN_NOT_SEE_FOCUS;
    }
}
Also used : IJavaElement(org.eclipse.jdt.core.IJavaElement) JavaProject(org.eclipse.jdt.internal.core.JavaProject) IJavaProject(org.eclipse.jdt.core.IJavaProject) JavaModelException(org.eclipse.jdt.core.JavaModelException) IJavaProject(org.eclipse.jdt.core.IJavaProject) IClasspathEntry(org.eclipse.jdt.core.IClasspathEntry) IJavaModel(org.eclipse.jdt.core.IJavaModel)

Example 60 with IJavaElement

use of org.eclipse.jdt.core.IJavaElement in project che by eclipse.

the class IndexSelector method initializeIndexLocations.

/*
 *  Compute the list of paths which are keying index files.
 */
private void initializeIndexLocations() {
    IPath[] projectsAndJars = this.searchScope.enclosingProjectsAndJars();
    IndexManager manager = JavaModelManager.getIndexManager();
    // use a linked set to preserve the order during search: see bug 348507
    LinkedHashSet locations = new LinkedHashSet();
    IJavaElement focus = MatchLocator.projectOrJarFocus(this.pattern);
    if (focus == null) {
        for (int i = 0; i < projectsAndJars.length; i++) {
            IPath path = projectsAndJars[i];
            Object target = JavaModel.getTarget(path, false);
            if (// case of an external folder
            target instanceof IFolder)
                path = ((IFolder) target).getFullPath();
            locations.add(manager.computeIndexLocation(path));
        }
    } else {
        try {
            // See whether the state builder might be used to reduce the number of index locations
            // find the projects from projectsAndJars that see the focus then walk those projects looking for the jars from projectsAndJars
            int length = projectsAndJars.length;
            JavaProject[] projectsCanSeeFocus = new JavaProject[length];
            SimpleSet visitedProjects = new SimpleSet(length);
            int projectIndex = 0;
            SimpleSet externalLibsToCheck = new SimpleSet(length);
            ObjectVector superTypes = new ObjectVector();
            IJavaElement[] focuses = getFocusedElementsAndTypes(this.pattern, focus, superTypes);
            char[][][] focusQualifiedNames = null;
            boolean isAutoBuilding = ResourcesPlugin.getWorkspace().getDescription().isAutoBuilding();
            if (isAutoBuilding && focus instanceof IJavaProject) {
                focusQualifiedNames = getQualifiedNames(superTypes);
            }
            IJavaModel model = JavaModelManager.getJavaModelManager().getJavaModel();
            for (int i = 0; i < length; i++) {
                IPath path = projectsAndJars[i];
                JavaProject project = (JavaProject) getJavaProject(path, model);
                if (project != null) {
                    visitedProjects.add(project);
                    /*We are adding all modules to the locations for searching in each one.
					Now the location contains not only current module and Jars on which depends, but also all modules from the workspace.*/
                    locations.add(manager.computeIndexLocation(path));
                /*int canSeeFocus = canSeeFocus(focuses, project, focusQualifiedNames);
					if (canSeeFocus == PROJECT_CAN_SEE_FOCUS) {
						locations.add(manager.computeIndexLocation(path));
					}
					if (canSeeFocus != PROJECT_CAN_NOT_SEE_FOCUS) {
						projectsCanSeeFocus[projectIndex++] = project;
					}*/
                } else {
                    externalLibsToCheck.add(path);
                }
            }
            for (int i = 0; i < projectIndex && externalLibsToCheck.elementSize > 0; i++) {
                IClasspathEntry[] entries = projectsCanSeeFocus[i].getResolvedClasspath();
                for (int j = entries.length; --j >= 0; ) {
                    IClasspathEntry entry = entries[j];
                    if (entry.getEntryKind() == IClasspathEntry.CPE_LIBRARY) {
                        IPath path = entry.getPath();
                        if (externalLibsToCheck.remove(path) != null) {
                            Object target = JavaModel.getTarget(path, false);
                            if (// case of an external folder
                            target instanceof IFolder)
                                path = ((IFolder) target).getFullPath();
                            locations.add(manager.computeIndexLocation(path));
                        }
                    }
                }
            }
            // jar files can be included in the search scope without including one of the projects that references them, so scan all projects that have not been visited
            if (externalLibsToCheck.elementSize > 0) {
                IJavaProject[] allProjects = model.getJavaProjects();
                for (int i = 0, l = allProjects.length; i < l && externalLibsToCheck.elementSize > 0; i++) {
                    JavaProject project = (JavaProject) allProjects[i];
                    if (!visitedProjects.includes(project)) {
                        IClasspathEntry[] entries = project.getResolvedClasspath();
                        for (int j = entries.length; --j >= 0; ) {
                            IClasspathEntry entry = entries[j];
                            if (entry.getEntryKind() == IClasspathEntry.CPE_LIBRARY) {
                                IPath path = entry.getPath();
                                if (externalLibsToCheck.remove(path) != null) {
                                    Object target = JavaModel.getTarget(path, false);
                                    if (// case of an external folder
                                    target instanceof IFolder)
                                        path = ((IFolder) target).getFullPath();
                                    locations.add(manager.computeIndexLocation(path));
                                }
                            }
                        }
                    }
                }
            }
        } catch (JavaModelException e) {
        // ignored
        }
    }
    // Ensure no nulls
    locations.remove(null);
    this.indexLocations = (IndexLocation[]) locations.toArray(new IndexLocation[locations.size()]);
}
Also used : LinkedHashSet(java.util.LinkedHashSet) IJavaElement(org.eclipse.jdt.core.IJavaElement) JavaProject(org.eclipse.jdt.internal.core.JavaProject) IJavaProject(org.eclipse.jdt.core.IJavaProject) SimpleSet(org.eclipse.jdt.internal.compiler.util.SimpleSet) JavaModelException(org.eclipse.jdt.core.JavaModelException) IPath(org.eclipse.core.runtime.IPath) IClasspathEntry(org.eclipse.jdt.core.IClasspathEntry) ObjectVector(org.eclipse.jdt.internal.compiler.util.ObjectVector) IndexManager(org.eclipse.jdt.internal.core.search.indexing.IndexManager) IJavaProject(org.eclipse.jdt.core.IJavaProject) IndexLocation(org.eclipse.jdt.internal.core.index.IndexLocation) IFolder(org.eclipse.core.resources.IFolder) IJavaModel(org.eclipse.jdt.core.IJavaModel)

Aggregations

IJavaElement (org.eclipse.jdt.core.IJavaElement)226 ICompilationUnit (org.eclipse.jdt.core.ICompilationUnit)49 IType (org.eclipse.jdt.core.IType)44 ArrayList (java.util.ArrayList)35 IJavaProject (org.eclipse.jdt.core.IJavaProject)35 IMethod (org.eclipse.jdt.core.IMethod)34 IPackageFragment (org.eclipse.jdt.core.IPackageFragment)32 JavaModelException (org.eclipse.jdt.core.JavaModelException)32 IResource (org.eclipse.core.resources.IResource)30 RefactoringStatus (org.eclipse.ltk.core.refactoring.RefactoringStatus)28 IPackageFragmentRoot (org.eclipse.jdt.core.IPackageFragmentRoot)23 IField (org.eclipse.jdt.core.IField)16 IMember (org.eclipse.jdt.core.IMember)14 Test (org.junit.Test)14 CoreException (org.eclipse.core.runtime.CoreException)13 StringTokenizer (java.util.StringTokenizer)11 ISourceRange (org.eclipse.jdt.core.ISourceRange)11 CompilationUnit (org.eclipse.jdt.core.dom.CompilationUnit)11 IPath (org.eclipse.core.runtime.IPath)10 HashMap (java.util.HashMap)9