Search in sources :

Example 6 with TypeNameMatch

use of org.eclipse.jdt.core.search.TypeNameMatch in project eclipse.jdt.ls by eclipse.

the class ImportOrganizeTest method createQuery.

protected IChooseImportQuery createQuery(final String name, final String[] choices, final int[] nEntries) {
    return new IChooseImportQuery() {

        @Override
        public TypeNameMatch[] chooseImports(TypeNameMatch[][] openChoices, ISourceRange[] ranges) {
            assertTrue(name + "-query-nchoices1", choices.length == openChoices.length);
            assertTrue(name + "-query-nchoices2", nEntries.length == openChoices.length);
            for (int i = 0; i < nEntries.length; i++) {
                assertTrue(name + "-query-cnt" + i, openChoices[i].length == nEntries[i]);
            }
            TypeNameMatch[] res = new TypeNameMatch[openChoices.length];
            for (int i = 0; i < openChoices.length; i++) {
                TypeNameMatch[] selection = openChoices[i];
                assertNotNull(name + "-query-setset" + i, selection);
                assertTrue(name + "-query-setlen" + i, selection.length > 0);
                TypeNameMatch found = null;
                for (int k = 0; k < selection.length; k++) {
                    if (selection[k].getFullyQualifiedName().equals(choices[i])) {
                        found = selection[k];
                    }
                }
                assertNotNull(name + "-query-notfound" + i, found);
                res[i] = found;
            }
            return res;
        }
    };
}
Also used : TypeNameMatch(org.eclipse.jdt.core.search.TypeNameMatch) IChooseImportQuery(org.eclipse.jdt.core.manipulation.OrganizeImportsOperation.IChooseImportQuery)

Example 7 with TypeNameMatch

use of org.eclipse.jdt.core.search.TypeNameMatch in project eclipse.jdt.ls by eclipse.

the class WorkspaceSymbolHandler method search.

public List<SymbolInformation> search(String query, IProgressMonitor monitor) {
    if (query == null || query.trim().isEmpty()) {
        return Collections.emptyList();
    }
    try {
        ArrayList<SymbolInformation> symbols = new ArrayList<>();
        new SearchEngine().searchAllTypeNames(null, SearchPattern.R_PATTERN_MATCH, query.toCharArray(), SearchPattern.R_CAMELCASE_MATCH, IJavaSearchConstants.TYPE, createSearchScope(), new TypeNameMatchRequestor() {

            @Override
            public void acceptTypeNameMatch(TypeNameMatch match) {
                SymbolInformation symbolInformation = new SymbolInformation();
                symbolInformation.setContainerName(match.getTypeContainerName());
                symbolInformation.setName(match.getSimpleTypeName());
                symbolInformation.setKind(mapKind(match));
                Location location;
                try {
                    if (match.getType().isBinary()) {
                        location = JDTUtils.toLocation(match.getType().getClassFile());
                    } else {
                        location = JDTUtils.toLocation(match.getType());
                    }
                } catch (Exception e) {
                    JavaLanguageServerPlugin.logException("Unable to determine location for " + match.getSimpleTypeName(), e);
                    return;
                }
                symbolInformation.setLocation(location);
                symbols.add(symbolInformation);
            }

            private SymbolKind mapKind(TypeNameMatch match) {
                int flags = match.getModifiers();
                if (Flags.isInterface(flags)) {
                    return SymbolKind.Interface;
                }
                if (Flags.isAnnotation(flags)) {
                    return SymbolKind.Property;
                }
                if (Flags.isEnum(flags)) {
                    return SymbolKind.Enum;
                }
                return SymbolKind.Class;
            }
        }, IJavaSearchConstants.WAIT_UNTIL_READY_TO_SEARCH, monitor);
        return symbols;
    } catch (Exception e) {
        JavaLanguageServerPlugin.logException("Problem getting search for" + query, e);
    }
    return Collections.emptyList();
}
Also used : SearchEngine(org.eclipse.jdt.core.search.SearchEngine) TypeNameMatch(org.eclipse.jdt.core.search.TypeNameMatch) SymbolKind(org.eclipse.lsp4j.SymbolKind) ArrayList(java.util.ArrayList) SymbolInformation(org.eclipse.lsp4j.SymbolInformation) TypeNameMatchRequestor(org.eclipse.jdt.core.search.TypeNameMatchRequestor) JavaModelException(org.eclipse.jdt.core.JavaModelException) Location(org.eclipse.lsp4j.Location)

Example 8 with TypeNameMatch

use of org.eclipse.jdt.core.search.TypeNameMatch in project webtools.sourceediting by eclipse.

the class AddImportHandler method execute.

/* (non-Javadoc)
	 * @see org.eclipse.core.commands.IHandler#execute(org.eclipse.core.commands.ExecutionEvent)
	 */
public Object execute(ExecutionEvent event) throws ExecutionException {
    final IEditorSite site = HandlerUtil.getActiveEditor(event).getEditorSite();
    final ISelectionProvider provider = site.getSelectionProvider();
    final ISelection selection = provider != null ? provider.getSelection() : null;
    if (selection instanceof IStructuredSelection && selection instanceof ITextSelection) {
        final IStructuredSelection structuredSelection = (IStructuredSelection) selection;
        final int offset = ((ITextSelection) selection).getOffset();
        final Object firstElement = structuredSelection.getFirstElement();
        if (firstElement instanceof IDOMNode) {
            final IDOMModel model = ((IDOMNode) firstElement).getModel();
            INodeAdapter adapter = model.getDocument().getAdapterFor(IJSPTranslation.class);
            if (adapter != null) {
                JSPTranslationAdapter translationAdapter = (JSPTranslationAdapter) model.getDocument().getAdapterFor(IJSPTranslation.class);
                final JSPTranslationExtension translation = translationAdapter.getJSPTranslation();
                translation.reconcileCompilationUnit();
                final ICompilationUnit cu = translation.getCompilationUnit();
                CompilationUnit astRoot = SharedASTProvider.getAST(cu, SharedASTProvider.WAIT_YES, null);
                if (astRoot != null) {
                    final ASTNode node = NodeFinder.perform(astRoot, translation.getJavaOffset(offset), 0);
                    if (node != null) {
                        SimpleName name = null;
                        if (node.getNodeType() == ASTNode.SIMPLE_NAME) {
                            name = (SimpleName) node;
                        } else if (node.getNodeType() == ASTNode.QUALIFIED_NAME) {
                            name = ((QualifiedName) node).getName();
                        }
                        if (name != null) {
                            IBinding binding = name.resolveBinding();
                            if (binding instanceof ITypeBinding && (binding.getJavaElement() == null || !binding.getJavaElement().exists())) {
                                // Look it up!
                                ITypeBinding typeBinding = (ITypeBinding) binding;
                                final IImportContainer importContainer = cu.getImportContainer();
                                if (!importContainer.getImport(typeBinding.getQualifiedName()).exists()) {
                                    final List typesFound = new ArrayList();
                                    final TypeNameMatchRequestor collector = new TypeNameMatcher(typesFound);
                                    IJavaSearchScope scope = SearchEngine.createJavaSearchScope(new IJavaElement[] { cu.getJavaProject() });
                                    final int mode = SearchPattern.R_EXACT_MATCH | SearchPattern.R_CASE_SENSITIVE;
                                    try {
                                        new SearchEngine().searchAllTypeNames(null, mode, name.getIdentifier().toCharArray(), mode, IJavaSearchConstants.CLASS_AND_INTERFACE, scope, collector, IJavaSearchConstants.WAIT_UNTIL_READY_TO_SEARCH, null);
                                        final int length = typesFound.size();
                                        final List elements = new ArrayList();
                                        for (int i = 0; i < length; i++) {
                                            final TypeNameMatch match = (TypeNameMatch) typesFound.get(i);
                                            final int modifiers = match.getModifiers();
                                            if (!Flags.isPrivate(modifiers) && !Flags.isPackageDefault(modifiers)) {
                                                elements.add(match);
                                            }
                                        }
                                        TypeNameMatch match = null;
                                        // If there's only one match, insert it; otherwise, open the dialog to choose from the list
                                        if (elements.size() == 1) {
                                            match = (TypeNameMatch) elements.get(0);
                                        } else if (elements.size() > 1) {
                                            ElementListSelectionDialog dialog = new ElementListSelectionDialog(site.getShell(), LABEL_PROVIDER);
                                            dialog.setElements(elements.toArray(new TypeNameMatch[elements.size()]));
                                            dialog.setTitle(JSPUIMessages.AddImportHandler_title);
                                            dialog.setMessage(JSPUIMessages.AddImportHandler_label);
                                            if (dialog.open() == Window.OK) {
                                                final Object result = dialog.getFirstResult();
                                                if (result instanceof TypeNameMatch) {
                                                    match = (TypeNameMatch) result;
                                                }
                                            }
                                        }
                                        addImport(match, model.getStructuredDocument());
                                    } catch (JavaModelException e) {
                                        // $NON-NLS-1$
                                        Logger.logException("Exception while determining import.", e);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    return null;
}
Also used : INodeAdapter(org.eclipse.wst.sse.core.internal.provisional.INodeAdapter) JavaModelException(org.eclipse.jdt.core.JavaModelException) IDOMModel(org.eclipse.wst.xml.core.internal.provisional.document.IDOMModel) SimpleName(org.eclipse.jdt.core.dom.SimpleName) IBinding(org.eclipse.jdt.core.dom.IBinding) ArrayList(java.util.ArrayList) IStructuredSelection(org.eclipse.jface.viewers.IStructuredSelection) IJSPTranslation(org.eclipse.jst.jsp.core.internal.java.IJSPTranslation) TypeNameMatchRequestor(org.eclipse.jdt.core.search.TypeNameMatchRequestor) SearchEngine(org.eclipse.jdt.core.search.SearchEngine) ISelectionProvider(org.eclipse.jface.viewers.ISelectionProvider) IDOMNode(org.eclipse.wst.xml.core.internal.provisional.document.IDOMNode) JSPTranslationExtension(org.eclipse.jst.jsp.core.internal.java.JSPTranslationExtension) IJavaSearchScope(org.eclipse.jdt.core.search.IJavaSearchScope) ElementListSelectionDialog(org.eclipse.ui.dialogs.ElementListSelectionDialog) ITypeBinding(org.eclipse.jdt.core.dom.ITypeBinding) IImportContainer(org.eclipse.jdt.core.IImportContainer) ISelection(org.eclipse.jface.viewers.ISelection) ASTNode(org.eclipse.jdt.core.dom.ASTNode) ArrayList(java.util.ArrayList) List(java.util.List) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) QualifiedName(org.eclipse.jdt.core.dom.QualifiedName) JSPTranslationAdapter(org.eclipse.jst.jsp.core.internal.java.JSPTranslationAdapter) ITextSelection(org.eclipse.jface.text.ITextSelection) TypeNameMatch(org.eclipse.jdt.core.search.TypeNameMatch) IEditorSite(org.eclipse.ui.IEditorSite)

Example 9 with TypeNameMatch

use of org.eclipse.jdt.core.search.TypeNameMatch in project che by eclipse.

the class JavaContext method addImport.

/**
	 * Adds an import for type with type name <code>type</code> if possible.
	 * Returns a string which can be used to reference the type.
	 *
	 * @param type the fully qualified name of the type to import
	 * @return returns a type to which the type binding can be assigned to.
	 * 	The returned type contains is unqualified when an import could be added or was already known.
	 * 	It is fully qualified, if an import conflict prevented the import.
	 * @since 3.4
	 */
public String addImport(String type) {
    if (isReadOnly())
        return type;
    ICompilationUnit cu = getCompilationUnit();
    if (cu == null)
        return type;
    try {
        boolean qualified = type.indexOf('.') != -1;
        if (!qualified) {
            IJavaSearchScope searchScope = SearchEngine.createJavaSearchScope(new IJavaElement[] { cu.getJavaProject() });
            SimpleName nameNode = null;
            TypeNameMatch[] matches = findAllTypes(type, searchScope, nameNode, null, cu);
            if (// only add import if we have a single match
            matches.length != 1)
                return type;
            type = matches[0].getFullyQualifiedName();
        }
        CompilationUnit root = getASTRoot(cu);
        if (fImportRewrite == null) {
            if (root == null) {
                fImportRewrite = StubUtility.createImportRewrite(cu, true);
            } else {
                fImportRewrite = StubUtility.createImportRewrite(root, true);
            }
        }
        ImportRewriteContext context;
        if (root == null)
            context = null;
        else
            context = new ContextSensitiveImportRewriteContext(root, getCompletionOffset(), fImportRewrite);
        return fImportRewrite.addImport(type, context);
    } catch (JavaModelException e) {
        handleException(null, e);
        return type;
    }
}
Also used : ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) CompilationUnit(org.eclipse.jdt.core.dom.CompilationUnit) ICompilationUnit(org.eclipse.jdt.core.ICompilationUnit) ContextSensitiveImportRewriteContext(org.eclipse.jdt.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext) JavaModelException(org.eclipse.jdt.core.JavaModelException) TypeNameMatch(org.eclipse.jdt.core.search.TypeNameMatch) ImportRewriteContext(org.eclipse.jdt.core.dom.rewrite.ImportRewrite.ImportRewriteContext) ContextSensitiveImportRewriteContext(org.eclipse.jdt.internal.corext.codemanipulation.ContextSensitiveImportRewriteContext) IJavaSearchScope(org.eclipse.jdt.core.search.IJavaSearchScope) SimpleName(org.eclipse.jdt.core.dom.SimpleName)

Example 10 with TypeNameMatch

use of org.eclipse.jdt.core.search.TypeNameMatch in project che by eclipse.

the class JavaContext method findAllTypes.

/*
	 * Finds a type by the simple name. From AddImportsOperation
	 */
private TypeNameMatch[] findAllTypes(String simpleTypeName, IJavaSearchScope searchScope, SimpleName nameNode, IProgressMonitor monitor, ICompilationUnit cu) throws JavaModelException {
    boolean is50OrHigher = JavaModelUtil.is50OrHigher(cu.getJavaProject());
    int typeKinds = SimilarElementsRequestor.ALL_TYPES;
    if (nameNode != null) {
        typeKinds = ASTResolving.getPossibleTypeKinds(nameNode, is50OrHigher);
    }
    ArrayList<TypeNameMatch> typeInfos = new ArrayList<TypeNameMatch>();
    TypeNameMatchCollector requestor = new TypeNameMatchCollector(typeInfos);
    new SearchEngine().searchAllTypeNames(null, 0, simpleTypeName.toCharArray(), SearchPattern.R_EXACT_MATCH | SearchPattern.R_CASE_SENSITIVE, getSearchForConstant(typeKinds), searchScope, requestor, IJavaSearchConstants.FORCE_IMMEDIATE_SEARCH, monitor);
    ArrayList<TypeNameMatch> typeRefsFound = new ArrayList<TypeNameMatch>(typeInfos.size());
    for (int i = 0, len = typeInfos.size(); i < len; i++) {
        TypeNameMatch curr = typeInfos.get(i);
        if (curr.getPackageName().length() > 0) {
            // do not suggest imports from the default package
            if (isOfKind(curr, typeKinds, is50OrHigher) && isVisible(curr, cu)) {
                typeRefsFound.add(curr);
            }
        }
    }
    return typeRefsFound.toArray(new TypeNameMatch[typeRefsFound.size()]);
}
Also used : SearchEngine(org.eclipse.jdt.core.search.SearchEngine) TypeNameMatch(org.eclipse.jdt.core.search.TypeNameMatch) ArrayList(java.util.ArrayList) TypeNameMatchCollector(org.eclipse.jdt.internal.corext.util.TypeNameMatchCollector)

Aggregations

TypeNameMatch (org.eclipse.jdt.core.search.TypeNameMatch)15 ArrayList (java.util.ArrayList)9 SearchEngine (org.eclipse.jdt.core.search.SearchEngine)8 JavaModelException (org.eclipse.jdt.core.JavaModelException)6 TypeNameMatchRequestor (org.eclipse.jdt.core.search.TypeNameMatchRequestor)6 SimpleName (org.eclipse.jdt.core.dom.SimpleName)4 IJavaSearchScope (org.eclipse.jdt.core.search.IJavaSearchScope)4 NullProgressMonitor (org.eclipse.core.runtime.NullProgressMonitor)3 ICompilationUnit (org.eclipse.jdt.core.ICompilationUnit)3 CompilationUnit (org.eclipse.jdt.core.dom.CompilationUnit)3 List (java.util.List)2 UnhandledException (org.autorefactor.util.UnhandledException)2 OperationCanceledException (org.eclipse.core.runtime.OperationCanceledException)2 SubProgressMonitor (org.eclipse.core.runtime.SubProgressMonitor)2 IType (org.eclipse.jdt.core.IType)2 ASTNode (org.eclipse.jdt.core.dom.ASTNode)2 IBinding (org.eclipse.jdt.core.dom.IBinding)2 ITypeBinding (org.eclipse.jdt.core.dom.ITypeBinding)2 QualifiedName (org.eclipse.jdt.core.dom.QualifiedName)2 ImportRewriteContext (org.eclipse.jdt.core.dom.rewrite.ImportRewrite.ImportRewriteContext)2