Example usage for org.eclipse.jdt.core.search SearchEngine createHierarchyScope

List of usage examples for org.eclipse.jdt.core.search SearchEngine createHierarchyScope

Introduction

In this page you can find the example usage for org.eclipse.jdt.core.search SearchEngine createHierarchyScope.

Prototype

public static IJavaSearchScope createHierarchyScope(IType type) throws JavaModelException 

Source Link

Document

Returns a Java search scope limited to the hierarchy of the given type.

Usage

From source file:at.bestsolution.efxclipse.tooling.fxml.editors.FXMLCompletionProposalComputer.java

License:Open Source License

private void createSubtypeProposals(final ContentAssistRequest contentAssistRequest,
        final CompletionProposalInvocationContext context, IType superType) {
    IJavaProject jproject = findProject(contentAssistRequest);

    try {/*from  w  w  w  .j a v  a  2  s  .com*/
        IJavaSearchScope hierarchyScope = SearchEngine.createHierarchyScope(superType);
        IJavaSearchScope projectScope = SearchEngine.createJavaSearchScope(new IJavaElement[] { jproject });
        IJavaSearchScope scope = new IntersectingJavaSearchScope(projectScope, hierarchyScope);
        SearchEngine searchEngine = new SearchEngine();

        char[] typeName = null;
        char[] packageName = null;
        if (!contentAssistRequest.getMatchString().isEmpty()) {
            typeName = contentAssistRequest.getMatchString().toCharArray();
        }

        searchEngine.searchAllTypeNames(packageName, SearchPattern.R_PATTERN_MATCH, typeName,
                SearchPattern.R_PREFIX_MATCH | SearchPattern.R_CAMELCASE_MATCH, IJavaSearchConstants.CLASS,
                scope, new TypeNameRequestor() {
                    @Override
                    public void acceptType(int modifiers, char[] packageName, char[] simpleTypeName,
                            char[][] enclosingTypeNames, String path) {
                        String sPackageName = new String(packageName);
                        int priority = PRIORITY_LOWER_1;
                        if (sPackageName.startsWith("com.sun.javafx")) {
                            priority -= 10;
                        }
                        StyledString s = new StyledString(new String(simpleTypeName));
                        s.append(" - " + sPackageName, StyledString.QUALIFIER_STYLER);
                        FXMLCompletionProposal prop = createElementProposal(contentAssistRequest, context,
                                sPackageName + "." + new String(simpleTypeName) + " ", s, false, priority,
                                IconKeys.getIcon(IconKeys.CLASS_KEY), FQN_MATCHER);

                        if (prop != null) {
                            prop.setMatcher(FQN_MATCHER);
                            prop.setTextApplier(new IReplacementTextApplier() {

                                @Override
                                public void apply(IDocument document, ConfigurableCompletionProposal proposal)
                                        throws BadLocationException {
                                    String proposalReplacementString = proposal.getReplacementString();
                                    List<String> s = getImportedTypes(contentAssistRequest);
                                    String shortened = proposalReplacementString
                                            .substring(proposalReplacementString.lastIndexOf('.') + 1);

                                    if (s.contains(proposalReplacementString.trim())) {
                                        proposal.setCursorPosition(shortened.length());
                                        document.replace(proposal.getReplacementOffset(),
                                                proposal.getReplacementLength(), shortened);
                                    } else {
                                        DocumentRewriteSession rewriteSession = null;
                                        try {
                                            if (document instanceof IDocumentExtension4) {
                                                rewriteSession = ((IDocumentExtension4) document)
                                                        .startRewriteSession(
                                                                DocumentRewriteSessionType.UNRESTRICTED_SMALL);
                                            }

                                        } finally {
                                            if (rewriteSession != null) {
                                                ((IDocumentExtension4) document)
                                                        .stopRewriteSession(rewriteSession);
                                            }
                                            // if (viewerExtension != null)
                                            // viewerExtension.setRedraw(true);
                                        }

                                        boolean startWithLineBreak = true;
                                        boolean endWithLineBreak = false;
                                        Document xmlDoc = contentAssistRequest.getNode().getOwnerDocument();
                                        NodeList list = xmlDoc.getChildNodes();
                                        int offset = 0;
                                        List<Node> prs = new ArrayList<Node>();
                                        for (int i = 0; i < list.getLength(); i++) {
                                            Node n = list.item(i);
                                            if (n.getNodeType() == Node.PROCESSING_INSTRUCTION_NODE) {
                                                prs.add(n);
                                            }
                                        }

                                        if (!prs.isEmpty()) {
                                            offset = ((IDOMNode) prs.get(prs.size() - 1)).getEndOffset();
                                        }

                                        offset = Math.min(proposal.getReplacementOffset(), offset);
                                        proposal.setCursorPosition(shortened.length());
                                        document.replace(proposal.getReplacementOffset(),
                                                proposal.getReplacementLength(), shortened);

                                        String importStatement = (startWithLineBreak ? "\n<?import "
                                                : "import ") + proposalReplacementString.trim();
                                        importStatement += "?>";

                                        if (endWithLineBreak)
                                            importStatement += "\n\n";
                                        document.replace(offset, 0, importStatement.toString());
                                        proposal.setCursorPosition(
                                                proposal.getCursorPosition() + importStatement.length());
                                    }
                                }
                            });
                            contentAssistRequest.addProposal(prop);
                        }
                    }
                }, IJavaSearchConstants.WAIT_UNTIL_READY_TO_SEARCH, new NullProgressMonitor());
    } catch (JavaModelException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:com.aliyun.odps.eclipse.create.wizard.NewDriverWizardPage.java

License:Apache License

private Text createBrowseClassControl(final Composite composite, final String string, String browseButtonLabel,
        final String baseClassName, final String dialogTitle) {
    Label label = new Label(composite, SWT.NONE);
    GridData data = new GridData(GridData.FILL_HORIZONTAL);
    label.setText(string);//from w  ww  .  j  a  va 2  s. c o m
    label.setLayoutData(data);

    final Text text = new Text(composite, SWT.SINGLE | SWT.BORDER);
    GridData data2 = new GridData(GridData.FILL_HORIZONTAL);
    data2.horizontalSpan = 2;
    text.setLayoutData(data2);

    Button browse = new Button(composite, SWT.NONE);
    browse.setText(browseButtonLabel);
    GridData data3 = new GridData(GridData.FILL_HORIZONTAL);
    browse.setLayoutData(data3);
    browse.addListener(SWT.Selection, new Listener() {
        public void handleEvent(Event event) {
            IType baseType;
            try {
                baseType = getPackageFragmentRoot().getJavaProject().findType(baseClassName);

                // edit this to limit the scope
                SelectionDialog dialog = JavaUI.createTypeDialog(composite.getShell(),
                        new ProgressMonitorDialog(composite.getShell()),
                        SearchEngine.createHierarchyScope(baseType),
                        IJavaElementSearchConstants.CONSIDER_CLASSES, false);

                dialog.setMessage("&Choose a type:");
                dialog.setBlockOnOpen(true);
                dialog.setTitle(dialogTitle);
                dialog.open();

                if ((dialog.getReturnCode() == Window.OK) && (dialog.getResult().length > 0)) {
                    IType type = (IType) dialog.getResult()[0];
                    text.setText(type.getFullyQualifiedName());
                }
            } catch (JavaModelException e) {
                e.printStackTrace();
            }
        }
    });

    if (!showContainerSelector) {
        label.setEnabled(false);
        text.setEnabled(false);
        browse.setEnabled(false);
    }

    return text;
}

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

License:Open Source License

/**
 * Opens a Java method referenced by the given on click attribute method name
 *
 * @param project the project containing the click handler
 * @param method the method name of the on click handler
 * @return true if the method was opened, false otherwise
 *//*w ww .  j  a  v a2s.  c  o  m*/
public static boolean openOnClickMethod(IProject project, String method) {
    // Search for the method in the Java index, filtering by the required click handler
    // method signature (public and has a single View parameter), and narrowing the scope
    // first to Activity classes, then to the whole workspace.
    final AtomicBoolean success = new AtomicBoolean(false);
    SearchRequestor requestor = new SearchRequestor() {
        @Override
        public void acceptSearchMatch(SearchMatch match) throws CoreException {
            Object element = match.getElement();
            if (element instanceof IMethod) {
                IMethod methodElement = (IMethod) element;
                String[] parameterTypes = methodElement.getParameterTypes();
                if (parameterTypes != null && parameterTypes.length == 1
                        && ("Qandroid.view.View;".equals(parameterTypes[0]) //$NON-NLS-1$
                                || "QView;".equals(parameterTypes[0]))) { //$NON-NLS-1$
                    // Check that it's public
                    if (Flags.isPublic(methodElement.getFlags())) {
                        JavaUI.openInEditor(methodElement);
                        success.getAndSet(true);
                    }
                }
            }
        }
    };
    try {
        IJavaSearchScope scope = null;
        IType activityType = null;
        IJavaProject javaProject = BaseProjectHelper.getJavaProject(project);
        if (javaProject != null) {
            activityType = javaProject.findType(CLASS_ACTIVITY);
            if (activityType != null) {
                scope = SearchEngine.createHierarchyScope(activityType);
            }
        }
        if (scope == null) {
            scope = SearchEngine.createWorkspaceScope();
        }

        SearchParticipant[] participants = new SearchParticipant[] {
                SearchEngine.getDefaultSearchParticipant() };
        int matchRule = SearchPattern.R_PATTERN_MATCH | SearchPattern.R_CASE_SENSITIVE;
        SearchPattern pattern = SearchPattern.createPattern("*." + method, IJavaSearchConstants.METHOD,
                IJavaSearchConstants.DECLARATIONS, matchRule);
        SearchEngine engine = new SearchEngine();
        engine.search(pattern, participants, scope, requestor, new NullProgressMonitor());

        boolean ok = success.get();
        if (!ok && activityType != null) {
            // TODO: Create a project+dependencies scope and search only that scope

            // Try searching again with a complete workspace scope this time
            scope = SearchEngine.createWorkspaceScope();
            engine.search(pattern, participants, scope, requestor, new NullProgressMonitor());

            // TODO: There could be more than one match; add code to consider them all
            // and pick the most likely candidate and open only that one.

            ok = success.get();
        }
        return ok;
    } catch (CoreException e) {
        AdtPlugin.log(e, null);
    }
    return false;
}

From source file:com.android.ide.eclipse.adt.internal.editors.layout.gle2.CustomViewFinder.java

License:Open Source License

private Pair<List<String>, List<String>> findViews(final boolean layoutsOnly) {
    final Set<String> customViews = new HashSet<String>();
    final Set<String> thirdPartyViews = new HashSet<String>();

    ProjectState state = Sdk.getProjectState(mProject);
    final List<IProject> libraries = state != null ? state.getFullLibraryProjects()
            : Collections.<IProject>emptyList();

    SearchRequestor requestor = new SearchRequestor() {
        @Override/*  ww  w  .  j  a v a2 s.c  o  m*/
        public void acceptSearchMatch(SearchMatch match) throws CoreException {
            // Ignore matches in comments
            if (match.isInsideDocComment()) {
                return;
            }

            Object element = match.getElement();
            if (element instanceof ResolvedBinaryType) {
                // Third party view
                ResolvedBinaryType type = (ResolvedBinaryType) element;
                IPackageFragment fragment = type.getPackageFragment();
                IPath path = fragment.getPath();
                String last = path.lastSegment();
                // Filter out android.jar stuff
                if (last.equals(FN_FRAMEWORK_LIBRARY)) {
                    return;
                }
                if (!isValidView(type, layoutsOnly)) {
                    return;
                }

                IProject matchProject = match.getResource().getProject();
                if (mProject == matchProject || libraries.contains(matchProject)) {
                    String fqn = type.getFullyQualifiedName();
                    thirdPartyViews.add(fqn);
                }
            } else if (element instanceof ResolvedSourceType) {
                // User custom view
                IProject matchProject = match.getResource().getProject();
                if (mProject == matchProject || libraries.contains(matchProject)) {
                    ResolvedSourceType type = (ResolvedSourceType) element;
                    if (!isValidView(type, layoutsOnly)) {
                        return;
                    }
                    String fqn = type.getFullyQualifiedName();
                    fqn = fqn.replace('$', '.');
                    customViews.add(fqn);
                }
            }
        }
    };
    try {
        IJavaProject javaProject = BaseProjectHelper.getJavaProject(mProject);
        if (javaProject != null) {
            String className = layoutsOnly ? CLASS_VIEWGROUP : CLASS_VIEW;
            IType viewType = javaProject.findType(className);
            if (viewType != null) {
                IJavaSearchScope scope = SearchEngine.createHierarchyScope(viewType);
                SearchParticipant[] participants = new SearchParticipant[] {
                        SearchEngine.getDefaultSearchParticipant() };
                int matchRule = SearchPattern.R_PATTERN_MATCH | SearchPattern.R_CASE_SENSITIVE;

                SearchPattern pattern = SearchPattern.createPattern("*", IJavaSearchConstants.CLASS,
                        IJavaSearchConstants.IMPLEMENTORS, matchRule);
                SearchEngine engine = new SearchEngine();
                engine.search(pattern, participants, scope, requestor, new NullProgressMonitor());
            }
        }
    } catch (CoreException e) {
        AdtPlugin.log(e, null);
    }

    List<String> custom = new ArrayList<String>(customViews);
    List<String> thirdParty = new ArrayList<String>(thirdPartyViews);

    if (!layoutsOnly) {
        // Update our cached answers (unless we were filtered on only layouts)
        mCustomViews = custom;
        mThirdPartyViews = thirdParty;
    }

    return Pair.of(custom, thirdParty);
}

From source file:com.android.ide.eclipse.adt.internal.editors.xml.Hyperlinks.java

License:Open Source License

/**
 * Opens a Java method referenced by the given on click attribute method name
 *
 * @param project the project containing the click handler
 * @param method the method name of the on click handler
 * @return true if the method was opened, false otherwise
 *//*from  ww  w .j  a v a2 s .c  o m*/
public static boolean openOnClickMethod(IProject project, String method) {
    // Search for the method in the Java index, filtering by the required click handler
    // method signature (public and has a single View parameter), and narrowing the scope
    // first to Activity classes, then to the whole workspace.
    final AtomicBoolean success = new AtomicBoolean(false);
    SearchRequestor requestor = new SearchRequestor() {
        @Override
        public void acceptSearchMatch(SearchMatch match) throws CoreException {
            Object element = match.getElement();
            if (element instanceof IMethod) {
                IMethod methodElement = (IMethod) element;
                String[] parameterTypes = methodElement.getParameterTypes();
                if (parameterTypes != null && parameterTypes.length == 1
                        && ("Qandroid.view.View;".equals(parameterTypes[0]) //$NON-NLS-1$
                                || "QView;".equals(parameterTypes[0]))) { //$NON-NLS-1$
                    // Check that it's public
                    if (Flags.isPublic(methodElement.getFlags())) {
                        JavaUI.openInEditor(methodElement);
                        success.getAndSet(true);
                    }
                }
            }
        }
    };
    try {
        IJavaSearchScope scope = null;
        IType activityType = null;
        IJavaProject javaProject = BaseProjectHelper.getJavaProject(project);
        if (javaProject != null) {
            activityType = javaProject.findType(SdkConstants.CLASS_ACTIVITY);
            if (activityType != null) {
                scope = SearchEngine.createHierarchyScope(activityType);
            }
        }
        if (scope == null) {
            scope = SearchEngine.createWorkspaceScope();
        }

        SearchParticipant[] participants = new SearchParticipant[] {
                SearchEngine.getDefaultSearchParticipant() };
        int matchRule = SearchPattern.R_PATTERN_MATCH | SearchPattern.R_CASE_SENSITIVE;
        SearchPattern pattern = SearchPattern.createPattern("*." + method, IJavaSearchConstants.METHOD,
                IJavaSearchConstants.DECLARATIONS, matchRule);
        SearchEngine engine = new SearchEngine();
        engine.search(pattern, participants, scope, requestor, new NullProgressMonitor());

        boolean ok = success.get();
        if (!ok && activityType != null) {
            // TODO: Create a project+dependencies scope and search only that scope

            // Try searching again with a complete workspace scope this time
            scope = SearchEngine.createWorkspaceScope();
            engine.search(pattern, participants, scope, requestor, new NullProgressMonitor());

            // TODO: There could be more than one match; add code to consider them all
            // and pick the most likely candidate and open only that one.

            ok = success.get();
        }
        return ok;
    } catch (CoreException e) {
        AdtPlugin.log(e, null);
    }
    return false;
}

From source file:com.android.ide.eclipse.auidt.internal.editors.layout.gle2.CustomViewFinder.java

License:Open Source License

private Pair<List<String>, List<String>> findViews(final boolean layoutsOnly) {
    final Set<String> customViews = new HashSet<String>();
    final Set<String> thirdPartyViews = new HashSet<String>();

    ProjectState state = Sdk.getProjectState(mProject);
    final List<IProject> libraries = state != null ? state.getFullLibraryProjects()
            : Collections.<IProject>emptyList();

    SearchRequestor requestor = new SearchRequestor() {
        @Override/*from w  ww . j a va  2 s.  co m*/
        public void acceptSearchMatch(SearchMatch match) throws CoreException {
            // Ignore matches in comments
            if (match.isInsideDocComment()) {
                return;
            }

            Object element = match.getElement();
            if (element instanceof ResolvedBinaryType) {
                // Third party view
                ResolvedBinaryType type = (ResolvedBinaryType) element;
                IPackageFragment fragment = type.getPackageFragment();
                IPath path = fragment.getPath();
                String last = path.lastSegment();
                // Filter out android.jar stuff
                /*  if (last.equals(FN_FRAMEWORK_LIBRARY)) {
                return;
                  }*/
                if (last.equals(FN_FRAMEWORK_LIBRARY)) {
                    return;
                }

                if (!isValidView(type, layoutsOnly)) {
                    return;
                }

                IProject matchProject = match.getResource().getProject();
                if (mProject == matchProject || libraries.contains(matchProject)) {
                    String fqn = type.getFullyQualifiedName();
                    thirdPartyViews.add(fqn);
                }
            } else if (element instanceof ResolvedSourceType) {
                // User custom view
                IProject matchProject = match.getResource().getProject();
                if (mProject == matchProject || libraries.contains(matchProject)) {
                    ResolvedSourceType type = (ResolvedSourceType) element;
                    if (!isValidView(type, layoutsOnly)) {
                        return;
                    }
                    String fqn = type.getFullyQualifiedName();
                    fqn = fqn.replace('$', '.');
                    customViews.add(fqn);
                }
            }
        }
    };
    try {
        IJavaProject javaProject = BaseProjectHelper.getJavaProject(mProject);
        if (javaProject != null) {
            String className = layoutsOnly ? CLASS_VIEWGROUP : CLASS_VIEW;
            IType viewType = javaProject.findType(className);
            if (viewType != null) {
                IJavaSearchScope scope = SearchEngine.createHierarchyScope(viewType);
                SearchParticipant[] participants = new SearchParticipant[] {
                        SearchEngine.getDefaultSearchParticipant() };
                int matchRule = SearchPattern.R_PATTERN_MATCH | SearchPattern.R_CASE_SENSITIVE;

                SearchPattern pattern = SearchPattern.createPattern("*", IJavaSearchConstants.CLASS,
                        IJavaSearchConstants.IMPLEMENTORS, matchRule);
                SearchEngine engine = new SearchEngine();
                engine.search(pattern, participants, scope, requestor, new NullProgressMonitor());
            }
        }
    } catch (CoreException e) {
        AdtPlugin.log(e, null);
    }

    List<String> custom = new ArrayList<String>(customViews);
    List<String> thirdParty = new ArrayList<String>(thirdPartyViews);

    if (!layoutsOnly) {
        // Update our cached answers (unless we were filtered on only layouts)
        mCustomViews = custom;
        mThirdPartyViews = thirdParty;
    }

    return Pair.of(custom, thirdParty);
}

From source file:com.google.gwt.eclipse.core.clientbundle.ui.AddResourcesToClientBundleDialog.java

License:Open Source License

private IType chooseClientBundleType() {
    try {//from w  w w.j av a 2s .c o m
        // Create a search scope for finding ClientBundle subtypes
        IJavaSearchScope scope = SearchEngine
                .createHierarchyScope(ClientBundleUtilities.findClientBundleType(getJavaProject()));

        // Configure the type selection dialog
        FilteredTypesSelectionDialog dialog = new FilteredTypesSelectionDialog(getShell(), false,
                PlatformUI.getWorkbench().getProgressService(), scope, IJavaSearchConstants.INTERFACE);
        dialog.setTitle("ClientBundle Type Selection");
        dialog.setMessage("Choose a type:");

        if (dialog.open() == Window.OK) {
            return (IType) dialog.getFirstResult();
        }
    } catch (JavaModelException e) {
        GWTPluginLog.logError(e);
    }

    return null;
}

From source file:com.google.gwt.eclipse.core.clientbundle.ui.ClientBundleResourceDialog.java

License:Open Source License

private IType chooseResourceType() {
    IJavaSearchScope scope;/* w w w.j ava 2  s  . c om*/
    try {
        scope = SearchEngine.createHierarchyScope(ClientBundleUtilities.findResourcePrototypeType(javaProject));
        FilteredTypesSelectionDialog dialog = new FilteredTypesSelectionDialog(getShell(), false,
                PlatformUI.getWorkbench().getProgressService(), scope, IJavaSearchConstants.INTERFACE);
        dialog.setTitle("Resource Type Selection");
        dialog.setMessage("Choose a resource type:");

        if (dialog.open() == Window.OK) {
            return (IType) dialog.getFirstResult();
        }
    } catch (JavaModelException e) {
        GWTPluginLog.logError(e);
    }

    return null;
}

From source file:com.iw.plugins.spindle.editors.spec.assist.ChooseTypeProposal.java

License:Mozilla Public License

protected IJavaSearchScope createSearchScope(IJavaProject jproject, String hierarchyRoot)
        throws JavaModelException {
    IJavaSearchScope result = null;// w ww .  ja va 2  s .  com
    IType hrootElement = null;
    try {
        if (hierarchyRoot == null)
            return createSearchScope(jproject);

        hrootElement = resolveTypeName(jproject, hierarchyRoot);

        if (hrootElement != null)
            result = SearchEngine.createHierarchyScope(hrootElement);
    } catch (JavaModelException jmex) {
        // ignore
        jmex.printStackTrace();
    }
    if (result == null) {
        IJavaElement[] elements = new IJavaElement[] { jproject };
        result = SearchEngine.createJavaSearchScope(elements);
    }
    return result;
}

From source file:com.iw.plugins.spindle.ui.wizards.fields.RawTypeDialogField.java

License:Mozilla Public License

private IJavaSearchScope createSearchScope() {
    IJavaSearchScope result = null;//from   ww  w. java2  s  .c o m
    IType hrootElement = null;
    try {
        if (hierarchyRoot != null) {
            hrootElement = resolveTypeName(hierarchyRoot);
        }
        if (hrootElement != null) {
            result = SearchEngine.createHierarchyScope(hrootElement);
        }
    } catch (JavaModelException jmex) {
        //ignore
        jmex.printStackTrace();
    }
    if (result == null) {
        IJavaElement[] elements = new IJavaElement[] { jproject };
        result = SearchEngine.createJavaSearchScope(elements);
    }
    return result;
}