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

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

Introduction

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

Prototype

public SearchEngine() 

Source Link

Document

Creates a new search engine.

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 ava 2  s  .  c  o m
        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:at.bestsolution.efxclipse.tooling.fxml.editors.FXMLCompletionProposalComputer.java

License:Open Source License

@Override
protected void addAttributeValueProposals(final ContentAssistRequest contentAssistRequest,
        final CompletionProposalInvocationContext context) {
    IDOMNode n = (IDOMNode) contentAssistRequest.getNode();

    if (Character.isUpperCase(n.getNodeName().charAt(0))) {
        NamedNodeMap m = n.getAttributes();
        IDOMNode attribute = null;/*from www  . ja  v a2s  . co m*/
        for (int i = 0; i < m.getLength(); i++) {
            IDOMNode a = (IDOMNode) m.item(i);
            if (a.contains(contentAssistRequest.getStartOffset())) {
                attribute = a;
            }
        }

        if (attribute != null) {
            if ("http://javafx.com/fxml".equals(attribute.getNamespaceURI())) {
                if ("constant".equals(attribute.getLocalName())) {
                    IType type = findType(n.getNodeName(), contentAssistRequest, context);
                    if (type != null) {
                        try {
                            List<IField> fields = new ArrayList<IField>();
                            collectStaticFields(fields, type);

                            for (IField f : fields) {
                                StyledString s = new StyledString(f.getElementName() + " : "
                                        + Signature.getSimpleName(Signature.toString(f.getTypeSignature())));
                                String owner = ((IType) f.getAncestor(IJavaElement.TYPE)).getElementName();
                                s.append(" - " + Signature.getSimpleName(owner), StyledString.QUALIFIER_STYLER);

                                FXMLCompletionProposal cp = createProposal(contentAssistRequest, context,
                                        "\"" + f.getElementName(), s, IconKeys.getIcon(IconKeys.CLASS_KEY),
                                        CLASS_ATTRIBUTE_MATCHER);

                                if (cp != null) {
                                    contentAssistRequest.addProposal(cp);
                                }
                            }

                        } catch (JavaModelException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                } else if ("controller".equals(attribute.getLocalName())) {
                    IJavaProject jproject = findProject(contentAssistRequest);

                    char[] typeName = null;
                    char[] packageName = null;
                    if (!contentAssistRequest.getMatchString().isEmpty()) {
                        if (contentAssistRequest.getMatchString().startsWith("\"")) {
                            typeName = contentAssistRequest.getMatchString().substring(1).toCharArray();
                        } else {
                            typeName = contentAssistRequest.getMatchString().toCharArray();
                        }
                    }

                    IJavaSearchScope searchScope = SearchEngine
                            .createJavaSearchScope(new IJavaElement[] { jproject });
                    SearchEngine searchEngine = new SearchEngine();
                    try {
                        searchEngine.searchAllTypeNames(packageName, SearchPattern.R_PATTERN_MATCH, typeName,
                                SearchPattern.R_PREFIX_MATCH | SearchPattern.R_CAMELCASE_MATCH,
                                IJavaSearchConstants.TYPE, searchScope, new TypeNameRequestor() {
                                    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")) {
                                            priority -= 10;
                                        }
                                        StyledString s = new StyledString(new String(simpleTypeName));
                                        s.append(" - " + sPackageName, StyledString.QUALIFIER_STYLER);

                                        FXMLCompletionProposal cp = createProposal(contentAssistRequest,
                                                context, "\"" + sPackageName + "." + new String(simpleTypeName),
                                                s, IconKeys.getIcon(IconKeys.CLASS_KEY),
                                                CLASS_ATTRIBUTE_MATCHER);

                                        if (cp != null) {
                                            contentAssistRequest.addProposal(cp);
                                        }
                                    }
                                }, IJavaSearchConstants.WAIT_UNTIL_READY_TO_SEARCH, new NullProgressMonitor());
                    } catch (JavaModelException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                }
            } else if (attribute.getNodeName().contains(".")) {
                String[] parts = attribute.getNodeName().split("\\.");

                IType type = findType(parts[0], contentAssistRequest, context);
                if (type != null) {
                    IFXClass fxClass = FXPlugin.getClassmodel().findClass(type.getJavaProject(), type);
                    if (fxClass != null) {
                        IFXProperty p = fxClass.getStaticProperty(parts[1]);
                        if (p instanceof IFXPrimitiveProperty) {
                            createAttributeValuePrimitiveProposals(contentAssistRequest, context,
                                    (IFXPrimitiveProperty) p);
                        } else if (p instanceof IFXEnumProperty) {
                            createAttributeValueEnumProposals(contentAssistRequest, context,
                                    (IFXEnumProperty) p);
                        } else if (p instanceof IFXObjectProperty) {
                            createAttributeValueObjectProposals(contentAssistRequest, context,
                                    (IFXObjectProperty) p);
                        }
                    }
                }
            } else {
                IType type = findType(n.getNodeName(), contentAssistRequest, context);
                if (type != null) {
                    IFXClass fxClass = FXPlugin.getClassmodel().findClass(type.getJavaProject(), type);
                    if (fxClass != null) {
                        IFXProperty p = fxClass.getProperty(attribute.getNodeName());
                        if (p instanceof IFXPrimitiveProperty) {
                            createAttributeValuePrimitiveProposals(contentAssistRequest, context,
                                    (IFXPrimitiveProperty) p);
                        } else if (p instanceof IFXEnumProperty) {
                            createAttributeValueEnumProposals(contentAssistRequest, context,
                                    (IFXEnumProperty) p);
                        } else if (p instanceof IFXObjectProperty) {
                            createAttributeValueObjectProposals(contentAssistRequest, context,
                                    (IFXObjectProperty) p);
                        } else if (p instanceof IFXEventHandlerProperty) {
                            createAttributeValueEventHandlerProposals(contentAssistRequest, context,
                                    (IFXEventHandlerProperty) p);
                        }
                    }
                }
            }
        }
    }
}

From source file:bndtools.editor.components.ComponentNameProposalProvider.java

License:Open Source License

@Override
protected List<IContentProposal> doGenerateProposals(String contents, int position) {
    final String prefix = contents.substring(0, position);
    IJavaProject javaProject = searchContext.getJavaProject();
    final List<IContentProposal> result = new ArrayList<IContentProposal>(100);

    // Resource matches
    IProject project = javaProject.getProject();
    try {/*from  www . j a  va2s  .  c o  m*/
        project.accept(new IResourceProxyVisitor() {
            public boolean visit(IResourceProxy proxy) throws CoreException {
                if (proxy.getType() == IResource.FILE) {
                    if (proxy.getName().toLowerCase().startsWith(prefix)
                            && proxy.getName().toLowerCase().endsWith(XML_SUFFIX)) {
                        result.add(new ResourceProposal(proxy.requestResource()));
                    }
                    return false;
                }
                // Recurse into everything else
                return true;
            }
        }, 0);
    } catch (CoreException e) {
        Plugin.log(new Status(IStatus.ERROR, Plugin.PLUGIN_ID, 0, "Error searching for resources.", e));
    }

    // Class matches
    final IJavaSearchScope scope = SearchEngine.createJavaSearchScope(new IJavaElement[] { javaProject });
    final TypeNameRequestor requestor = new TypeNameRequestor() {
        @Override
        public void acceptType(int modifiers, char[] packageName, char[] simpleTypeName,
                char[][] enclosingTypeNames, String path) {
            if (!Flags.isAbstract(modifiers) && (Flags.isPublic(modifiers) || Flags.isProtected(modifiers))) {
                result.add(new JavaContentProposal(new String(packageName), new String(simpleTypeName), false));
            }
        };
    };
    final IRunnableWithProgress runnable = new IRunnableWithProgress() {
        public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
            try {
                new SearchEngine().searchAllTypeNames(null, 0, prefix.toCharArray(),
                        SearchPattern.R_PREFIX_MATCH, IJavaSearchConstants.CLASS, scope, requestor,
                        IJavaSearchConstants.CANCEL_IF_NOT_READY_TO_SEARCH, monitor);
            } catch (JavaModelException e) {
                throw new InvocationTargetException(e);
            }
        }
    };
    IRunnableContext runContext = searchContext.getRunContext();
    try {
        if (runContext != null) {
            runContext.run(false, false, runnable);
        } else {
            runnable.run(new NullProgressMonitor());
        }
    } catch (InvocationTargetException e) {
        Plugin.log(new Status(IStatus.ERROR, Plugin.PLUGIN_ID, 0, "Error searching for classes.",
                e.getTargetException()));
    } catch (InterruptedException e) {
        // Reset the interruption status and continue
        Thread.currentThread().interrupt();
    }
    return result;
}

From source file:bndtools.editor.components.SvcInterfaceProposalProvider.java

License:Open Source License

@Override
protected List<IContentProposal> doGenerateProposals(String contents, int position) {
    final String prefix = contents.substring(0, position);
    final IJavaSearchScope scope = SearchEngine
            .createJavaSearchScope(new IJavaElement[] { searchContext.getJavaProject() });
    final ArrayList<IContentProposal> result = new ArrayList<IContentProposal>(100);
    final TypeNameRequestor typeNameRequestor = new TypeNameRequestor() {
        @Override//from   w  w  w. j a  v  a 2 s. c  o  m
        public void acceptType(int modifiers, char[] packageName, char[] simpleTypeName,
                char[][] enclosingTypeNames, String path) {
            boolean isInterface = Flags.isInterface(modifiers);
            result.add(
                    new JavaContentProposal(new String(packageName), new String(simpleTypeName), isInterface));
        }
    };
    IRunnableWithProgress runnable = new IRunnableWithProgress() {
        public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
            try {
                new SearchEngine().searchAllTypeNames(null, 0, prefix.toCharArray(),
                        SearchPattern.R_PREFIX_MATCH, IJavaSearchConstants.CLASS_AND_INTERFACE, scope,
                        typeNameRequestor, IJavaSearchConstants.CANCEL_IF_NOT_READY_TO_SEARCH, monitor);
            } catch (JavaModelException e) {
                throw new InvocationTargetException(e);
            }
        }
    };

    try {
        if (searchContext.getRunContext() == null) {
            runnable.run(new NullProgressMonitor());
        } else {
            searchContext.getRunContext().run(false, false, runnable);
        }
    } catch (InvocationTargetException e) {
        Plugin.log(new Status(IStatus.ERROR, Plugin.PLUGIN_ID, 0, "Error searching for Java types.",
                e.getTargetException()));
        return Collections.emptyList();
    } catch (InterruptedException e) {
        // Reset interrupted status and return empty
        Thread.currentThread().interrupt();
        return Collections.emptyList();
    }
    return result;
}

From source file:bndtools.editor.pkgpatterns.PkgPatternsProposalProvider.java

License:Open Source License

@Override
protected Collection<? extends IContentProposal> doGenerateProposals(String contents, int position) {
    String prefix = contents.substring(0, position);

    final int replaceFromPos;
    if (prefix.startsWith("!")) { //$NON-NLS-1$
        prefix = prefix.substring(1);/*  w  w  w  .ja v  a2s  .c om*/
        replaceFromPos = 1;
    } else {
        replaceFromPos = 0;
    }

    Comparator<PkgPatternProposal> comparator = new Comparator<PkgPatternProposal>() {
        @Override
        public int compare(PkgPatternProposal o1, PkgPatternProposal o2) {
            int result = o1.getPackageFragment().getElementName()
                    .compareTo(o2.getPackageFragment().getElementName());
            if (result == 0) {
                result = Boolean.valueOf(o1.isWildcard()).compareTo(Boolean.valueOf(o2.isWildcard()));
            }
            return result;
        }
    };
    final TreeSet<PkgPatternProposal> result = new TreeSet<PkgPatternProposal>(comparator);

    final IJavaSearchScope scope = SearchEngine
            .createJavaSearchScope(new IJavaElement[] { searchContext.getJavaProject() });
    final SearchPattern pattern = SearchPattern.createPattern("*" + prefix + "*", IJavaSearchConstants.PACKAGE,
            IJavaSearchConstants.DECLARATIONS, SearchPattern.R_PATTERN_MATCH);
    final SearchRequestor requestor = new SearchRequestor() {
        @Override
        public void acceptSearchMatch(SearchMatch match) throws CoreException {
            IPackageFragment pkg = (IPackageFragment) match.getElement();
            // Reject the default package and any package starting with
            // "java." since these cannot be imported
            if (pkg.isDefaultPackage() || pkg.getElementName().startsWith("java."))
                return;

            result.add(new PkgPatternProposal(pkg, false, replaceFromPos));
            result.add(new PkgPatternProposal(pkg, true, replaceFromPos));
        }
    };
    IRunnableWithProgress runnable = new IRunnableWithProgress() {
        @Override
        public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
            try {
                new SearchEngine().search(pattern,
                        new SearchParticipant[] { SearchEngine.getDefaultSearchParticipant() }, scope,
                        requestor, monitor);
            } catch (CoreException e) {
                throw new InvocationTargetException(e);
            }
        }
    };

    try {
        IRunnableContext runContext = searchContext.getRunContext();
        if (runContext != null) {
            runContext.run(false, false, runnable);
        } else {
            runnable.run(new NullProgressMonitor());
        }
        return result;
    } catch (InvocationTargetException e) {
        logger.logError("Error searching for packages.", e);
        return Collections.emptyList();
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
        return Collections.emptyList();
    }
}

From source file:bndtools.internal.pkgselection.JavaSearchScopePackageLister.java

License:Open Source License

@Override
public String[] getPackages(boolean includeNonSource, IPackageFilter filter) throws PackageListException {
    final List<IJavaElement> packageList = new LinkedList<IJavaElement>();
    final SearchRequestor requestor = new SearchRequestor() {
        @Override//from www . java  2 s .c om
        public void acceptSearchMatch(SearchMatch match) throws CoreException {
            IJavaElement enclosingElement = (IJavaElement) match.getElement();
            String name = enclosingElement.getElementName();
            if (name.length() > 0) { // Do not include default pkg
                packageList.add(enclosingElement);
            }
        }
    };
    final SearchPattern pattern = SearchPattern.createPattern("*", IJavaSearchConstants.PACKAGE,
            IJavaSearchConstants.DECLARATIONS, SearchPattern.R_PATTERN_MATCH | SearchPattern.R_CASE_SENSITIVE);

    IRunnableWithProgress operation = new IRunnableWithProgress() {
        @Override
        public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
            try {
                new SearchEngine().search(pattern, SearchUtils.getDefaultSearchParticipants(), scope, requestor,
                        monitor);
            } catch (CoreException e) {
                throw new InvocationTargetException(e);
            }
        }
    };

    try {
        runContext.run(true, true, operation);
    } catch (InvocationTargetException e) {
        throw new PackageListException(e.getCause());
    } catch (InterruptedException e) {
        throw new PackageListException("Operation interrupted");
    }

    // Remove non-source and excludes
    Set<String> packageNames = new LinkedHashSet<String>();
    for (Iterator<IJavaElement> iter = packageList.iterator(); iter.hasNext();) {
        boolean omit = false;
        IJavaElement element = iter.next();
        if (!includeNonSource) {
            IPackageFragment pkgFragment = (IPackageFragment) element;
            try {
                if (pkgFragment.getCompilationUnits().length == 0) {
                    omit = true;
                }
            } catch (JavaModelException e) {
                throw new PackageListException(e);
            }
        }

        if (filter != null && !filter.select(element.getElementName())) {
            omit = true;
        }
        if (!omit) {
            packageNames.add(element.getElementName());
        }
    }

    return packageNames.toArray(new String[0]);
}

From source file:ca.ubc.cs.ferret.tests.support.TestProject.java

License:Open Source License

public void waitForIndexer() throws JavaModelException {
    new SearchEngine().searchAllTypeNames(null, null, SearchPattern.R_EXACT_MATCH, IJavaSearchConstants.CLASS,
            SearchEngine.createJavaSearchScope(new IJavaElement[0]), new TypeNameRequestor() {
                // nothing needs to be done here...we accept everything
            }, IJavaSearchConstants.WAIT_UNTIL_READY_TO_SEARCH, null);
}

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 {// w w  w .j  a va  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:ccw.editors.clojure.ClojureProposalProcessor.java

License:Open Source License

private List<ICompletionProposal> computeAndAddJavaInstanceMethodCompletionProposal(
        final PrefixInfo prefixInfo) {
    final List<ICompletionProposal> proposals = new ArrayList<ICompletionProposal>();

    if (!checkJavaPrefixLength(prefixInfo)) {
        return Collections.emptyList();
    }/*from w w w  .  j av  a  2s .c  o m*/

    final String methodPrefix = prefixInfo.prefix.substring(1);
    System.out.println("method prefix:" + methodPrefix);
    boolean isPattern = (methodPrefix.contains("*") || methodPrefix.contains("?"));
    boolean autoAddEndWildcard = isPattern && !methodPrefix.endsWith("*");
    SearchPattern pattern = SearchPattern.createPattern(autoAddEndWildcard ? methodPrefix + "*" : methodPrefix,
            IJavaSearchConstants.METHOD, // | IJavaSearchConstants.FIELD,
            //         IJavaSearchConstants.TYPE,
            IJavaSearchConstants.DECLARATIONS,
            isPattern ? SearchPattern.R_PATTERN_MATCH : SearchPattern.R_PREFIX_MATCH);
    if (pattern != null) {
        IJavaProject editedFileProject = editor.getAssociatedProject();
        if (editedFileProject != null) {
            IJavaSearchScope scope = SearchEngine
                    .createJavaSearchScope(new IJavaElement[] { editedFileProject });
            SearchRequestor requestor = new SearchRequestor() {
                private int counter;

                @Override
                public void beginReporting() {
                    super.beginReporting();
                    System.out.println("begin reporting");
                    counter = 0;
                }

                @Override
                public void acceptSearchMatch(SearchMatch match) throws CoreException {
                    counter++;
                    if (counter >= MAX_JAVA_SEARCH_RESULT_NUMBER) {
                        System.out.println("too much results (>" + MAX_JAVA_SEARCH_RESULT_NUMBER
                                + "), throwing exception");
                        throw new CoreException(Status.OK_STATUS);
                    }
                    proposals.add(new MethodLazyCompletionProposal((IMethod) match.getElement(), methodPrefix,
                            prefixInfo.prefixOffset + 1, null, editor));
                }

                @Override
                public void endReporting() {
                    super.endReporting();
                    System.out.println("end reporting : count=" + counter);
                }

            };
            SearchEngine searchEngine = new SearchEngine();
            try {
                searchEngine.search(pattern,
                        new SearchParticipant[] { SearchEngine.getDefaultSearchParticipant() }, scope,
                        requestor, null /* no progress monitor */);
                assistant.setStatusMessage(MESSAGE_JAVA_COMPLETION);
            } catch (CoreException e) {
                if (e.getStatus() != Status.OK_STATUS) {
                    CCWPlugin.logWarning("java code proposal search error in clojure dev", e);
                } else {
                    errorMessage = ERROR_MESSAGE_TOO_MANY_COMPLETIONS;
                    assistant.setStatusMessage(ERROR_MESSAGE_TOO_MANY_COMPLETIONS);
                }
            }
        }
    }
    return proposals;
}

From source file:ccw.editors.clojure.ClojureProposalProcessor.java

License:Open Source License

private List<ICompletionProposal> computeAndAddJavaStaticMethodCompletionProposal(final PrefixInfo prefixInfo,
        final JavaSearchType searchType) {
    final List<ICompletionProposal> proposals = new ArrayList<ICompletionProposal>();

    if (!checkJavaPrefixLength(prefixInfo)) {
        return Collections.emptyList();
    }/*w ww  .  j a  v  a  2s . co m*/

    int nbPatterns = searchType.matchRule().length;
    List<SearchPattern> combinedPattern = new ArrayList<SearchPattern>();

    for (int i = 0; i < nbPatterns; i++) {
        if (prefixInfo.prefix.length() < searchType.prefixMinLength()[i]) {
            continue;
        }
        SearchPattern pattern = SearchPattern.createPattern(searchType.patternStr(prefixInfo)[i],
                searchType.searchFor()[i], IJavaSearchConstants.DECLARATIONS, searchType.matchRule()[i]);
        combinedPattern.add(pattern);
    }

    IJavaProject editedFileProject = editor.getAssociatedProject();
    if (editedFileProject != null) {
        IJavaSearchScope scope = SearchEngine.createJavaSearchScope(new IJavaElement[] { editedFileProject });
        SearchRequestor requestor = new SearchRequestor() {
            @Override
            public void acceptSearchMatch(SearchMatch match) throws CoreException {
                proposals.add(searchType.lazyCompletionProposal(prefixInfo, editor, match));
            }
        };
        SearchEngine searchEngine = new SearchEngine();
        try {
            for (SearchPattern pattern : combinedPattern) {
                if (pattern != null) {
                    searchEngine.search(pattern,
                            new SearchParticipant[] { SearchEngine.getDefaultSearchParticipant() }, scope,
                            requestor, null /* no progress monitor */);
                    assistant.setStatusMessage(MESSAGE_JAVA_COMPLETION);
                }
            }
        } catch (CoreException e) {
            if (e.getStatus() != Status.OK_STATUS) {
                CCWPlugin.logWarning("java code proposal search error in clojure dev", e);
            } else {
                errorMessage = ERROR_MESSAGE_TOO_MANY_COMPLETIONS;
                assistant.setStatusMessage(ERROR_MESSAGE_TOO_MANY_COMPLETIONS);
            }
        }
    }
    return proposals;
}