Example usage for org.eclipse.jdt.core.search SearchPattern R_CAMELCASE_MATCH

List of usage examples for org.eclipse.jdt.core.search SearchPattern R_CAMELCASE_MATCH

Introduction

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

Prototype

int R_CAMELCASE_MATCH

To view the source code for org.eclipse.jdt.core.search SearchPattern R_CAMELCASE_MATCH.

Click Source Link

Document

Match rule: The search pattern contains a Camel Case expression.

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  av a  2 s .  c  om*/
        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;// ww  w.  j  a  va2 s.com
        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.internal.pkgselection.SearchUtils.java

License:Open Source License

/**
 * Returns whether the given pattern is a camel case pattern or not. <em>Note: this method does not consider the
 * {@link SearchPattern#R_CAMELCASE_SAME_PART_COUNT_MATCH} variant.<em>
 * //from w ww .  j a va2s  . c  o m
 * @param pattern the pattern to inspect
 * @return whether it is a camel case pattern or not
 */
public static boolean isCamelCasePattern(String pattern) {
    return SearchPattern.validateMatchRule(pattern,
            SearchPattern.R_CAMELCASE_MATCH) == SearchPattern.R_CAMELCASE_MATCH;
}

From source file:ca.ecliptical.pde.ds.search.DescriptorQueryParticipant.java

License:Open Source License

private int getMatchMode(String pattern) {
    if (pattern.indexOf('*') != -1 || pattern.indexOf('?') != -1)
        return SearchPattern.R_PATTERN_MATCH;

    if (SearchPattern.validateMatchRule(pattern,
            SearchPattern.R_CAMELCASE_MATCH) == SearchPattern.R_CAMELCASE_MATCH)
        return SearchPattern.R_CAMELCASE_MATCH;

    return SearchPattern.R_EXACT_MATCH;
}

From source file:net.harawata.mybatipse.mybatis.ProposalComputorHelper.java

License:Open Source License

public static void searchJavaType(String matchString, IJavaSearchScope scope, TypeNameRequestor requestor)
        throws JavaModelException {
    char[] searchPkg = null;
    char[] searchType = null;
    if (matchString != null && matchString.length() > 0) {
        char[] match = matchString.toCharArray();
        int lastDotPos = matchString.lastIndexOf('.');
        if (lastDotPos == -1) {
            searchType = match;//from  w  ww .j a v a  2  s .  c  om
        } else {
            if (lastDotPos + 1 < match.length) {
                searchType = CharOperation.lastSegment(match, '.');
            }
            searchPkg = Arrays.copyOfRange(match, 0, lastDotPos);
        }
    }
    SearchEngine searchEngine = new SearchEngine();
    searchEngine.searchAllTypeNames(searchPkg, SearchPattern.R_PREFIX_MATCH, searchType,
            SearchPattern.R_CAMELCASE_MATCH, IJavaSearchConstants.CLASS, scope, requestor,
            IJavaSearchConstants.WAIT_UNTIL_READY_TO_SEARCH, null);
}

From source file:net.harawata.mybatipse.mybatis.TypeAliasCache.java

License:Open Source License

private void collectTypesInPackages(final IJavaProject project, Set<String> packages,
        final TypeAliasMap aliasMap, Set<String> superTypes, IReporter reporter) {
    final Set<IType> superTypeSet = new HashSet<IType>();
    try {//ww  w. j  ava 2 s .c o  m
        for (String supType : superTypes) {
            superTypeSet.add(project.findType(supType));
        }
    } catch (JavaModelException e) {
        Activator.log(Status.ERROR, e.getMessage(), e);
    }

    int includeMask = IJavaSearchScope.SOURCES | IJavaSearchScope.REFERENCED_PROJECTS
            | IJavaSearchScope.APPLICATION_LIBRARIES | IJavaSearchScope.SYSTEM_LIBRARIES;
    IJavaSearchScope scope = SearchEngine.createJavaSearchScope(new IJavaProject[] { project }, includeMask);
    TypeNameRequestor requestor = new TypeNameRequestor() {
        @Override
        public void acceptType(int modifiers, char[] packageName, char[] simpleTypeName,
                char[][] enclosingTypeNames, String path) {
            // Ignore abstract classes.
            if (Flags.isAbstract(modifiers))
                return;

            String qualifiedName = NameUtil.buildQualifiedName(packageName, simpleTypeName, enclosingTypeNames,
                    false);
            try {
                IType foundType = project.findType(qualifiedName);
                if (superTypeSet.isEmpty() || isSuperTypeMatched(foundType, superTypeSet)) {
                    String alias = getAliasAnnotationValue(foundType);
                    if (alias == null) {
                        alias = new String(simpleTypeName);
                    }
                    aliasMap.put(alias, qualifiedName);
                }
            } catch (JavaModelException e) {
                Activator.log(Status.WARNING, "Error occurred while searching type alias.", e);
            }
        }

        private boolean isSuperTypeMatched(IType foundType, Set<IType> superTypeSet) throws JavaModelException {
            for (IType superType : superTypeSet) {
                if (isAssignable(foundType, superType)) {
                    return true;
                }
            }
            return false;
        }
    };

    SearchEngine searchEngine = new SearchEngine();
    for (String pkg : packages) {
        if (reporter != null && reporter.isCancelled()) {
            throw new OperationCanceledException();
        }
        try {
            searchEngine.searchAllTypeNames(pkg.toCharArray(), SearchPattern.R_EXACT_MATCH, null,
                    SearchPattern.R_CAMELCASE_MATCH, IJavaSearchConstants.CLASS, scope, requestor,
                    IJavaSearchConstants.WAIT_UNTIL_READY_TO_SEARCH, null);
        } catch (JavaModelException e) {
            Activator.log(Status.ERROR, e.getMessage(), e);
        }
    }
}

From source file:net.harawata.mybatipse.mybatis.XmlCompletionProposalComputer.java

License:Open Source License

private void searchJavaType(String matchString, IJavaSearchScope scope, TypeNameRequestor requestor)
        throws JavaModelException {
    char[] searchPkg = null;
    char[] searchType = null;
    if (matchString != null && matchString.length() > 0) {
        char[] match = matchString.toCharArray();
        int lastDotPos = matchString.lastIndexOf('.');
        if (lastDotPos == -1) {
            searchType = match;/*from  w  w w .j  av a 2s .  c  o m*/
        } else {
            if (lastDotPos + 1 < match.length) {
                searchType = CharOperation.lastSegment(match, '.');
            }
            searchPkg = Arrays.copyOfRange(match, 0, lastDotPos);
        }
    }
    SearchEngine searchEngine = new SearchEngine();
    searchEngine.searchAllTypeNames(searchPkg, SearchPattern.R_PREFIX_MATCH, searchType,
            SearchPattern.R_CAMELCASE_MATCH, IJavaSearchConstants.CLASS, scope, requestor,
            IJavaSearchConstants.WAIT_UNTIL_READY_TO_SEARCH, null);
}

From source file:org.eclim.plugin.jdt.command.search.SearchCommand.java

License:Open Source License

/**
 * Executes the search./* w  ww.j  ava 2s .  c om*/
 *
 * @param commandLine The command line for the search.
 * @return The search results.
 */
public List<SearchMatch> executeSearch(CommandLine commandLine) throws Exception {
    int context = -1;
    if (commandLine.hasOption(Options.CONTEXT_OPTION)) {
        context = getContext(commandLine.getValue(Options.CONTEXT_OPTION));
    }
    String project = commandLine.getValue(Options.NAME_OPTION);
    String scope = commandLine.getValue(Options.SCOPE_OPTION);
    String file = commandLine.getValue(Options.FILE_OPTION);
    String offset = commandLine.getValue(Options.OFFSET_OPTION);
    String length = commandLine.getValue(Options.LENGTH_OPTION);
    String pat = commandLine.getValue(Options.PATTERN_OPTION);

    SearchPattern pattern = null;
    IJavaProject javaProject = project != null ? JavaUtils.getJavaProject(project) : null;

    SearchRequestor requestor = new SearchRequestor();

    // element search
    if (file != null && offset != null && length != null) {
        int charOffset = getOffset(commandLine);
        IJavaElement element = getElement(javaProject, file, charOffset, Integer.parseInt(length));
        if (element != null) {
            // user requested a contextual search.
            if (context == -1) {
                context = getElementContextualContext(element);

                // jdt search doesn't support implementors for method searches, so
                // switch to declarations.
            } else if (context == IJavaSearchConstants.IMPLEMENTORS
                    && element.getElementType() == IJavaElement.METHOD) {
                context = IJavaSearchConstants.DECLARATIONS;
                requestor = new ImplementorsSearchRequestor();
            }
            pattern = SearchPattern.createPattern(element, context);
        }

        // pattern search
    } else if (pat != null) {
        if (context == -1) {
            context = IJavaSearchConstants.DECLARATIONS;
        }

        int matchType = SearchPattern.R_EXACT_MATCH;

        // wild card character supplied, use pattern matching.
        if (pat.indexOf('*') != -1 || pat.indexOf('?') != -1) {
            matchType = SearchPattern.R_PATTERN_MATCH;

            // all upper case, add camel case support.
        } else if (pat.equals(pat.toUpperCase())) {
            matchType |= SearchPattern.R_CAMELCASE_MATCH;
        }

        boolean caseSensitive = !commandLine.hasOption(Options.CASE_INSENSITIVE_OPTION);
        if (caseSensitive) {
            matchType |= SearchPattern.R_CASE_SENSITIVE;
        }

        int type = getType(commandLine.getValue(Options.TYPE_OPTION));

        // jdt search doesn't support implementors for method searches, so switch
        // to declarations.
        if (type == IJavaSearchConstants.METHOD && context == IJavaSearchConstants.IMPLEMENTORS) {
            context = IJavaSearchConstants.DECLARATIONS;
            requestor = new ImplementorsSearchRequestor();
        }

        // hack for inner classes
        Matcher matcher = INNER_CLASS.matcher(pat);
        if (matcher.matches()) {
            // pattern search doesn't support org.test.Type$Inner or
            // org.test.Type.Inner, so convert it to org.test.*Inner, then filter
            // the results.
            pattern = SearchPattern.createPattern(matcher.replaceFirst("$1*$3"), type, context, matchType);
            Pattern toMatch = Pattern.compile(pat.replace(".", "\\.").replace("$", "\\$").replace("(", "\\(")
                    .replace(")", "\\)").replace("*", ".*").replace("?", "."));
            List<SearchMatch> matches = search(pattern, getScope(scope, javaProject));
            Iterator<SearchMatch> iterator = matches.iterator();
            while (iterator.hasNext()) {
                SearchMatch match = iterator.next();
                String name = JavaUtils.getFullyQualifiedName((IJavaElement) match.getElement()).replace("#",
                        ".");
                if (!toMatch.matcher(name).matches()) {
                    iterator.remove();
                }
            }
            return matches;
        }

        pattern = SearchPattern.createPattern(pat, type, context, matchType);

        // bad search request
    } else {
        throw new IllegalArgumentException(Services.getMessage("java_search.indeterminate"));
    }

    List<SearchMatch> matches = search(pattern, getScope(scope, javaProject), requestor);
    return matches;
}

From source file:org.eclipse.e4.tools.emf.editor3x.PDEClassContributionProvider.java

License:Open Source License

@SuppressWarnings("restriction")
public void findContribution(final Filter filter, final ContributionResultHandler handler) {
    boolean followReferences = true;
    if (filter instanceof FilterEx) {
        FilterEx filterEx = (FilterEx) filter;
        if (filterEx.getSearchScope().contains(ResourceSearchScope.PROJECT)
                && !filterEx.getSearchScope().contains(ResourceSearchScope.REFERENCES)) {
            followReferences = false;/*  w  w w  . j  av a 2  s. co  m*/
        }

    }
    IJavaSearchScope scope = null;
    if (followReferences == false) {
        IJavaProject javaProject = JavaCore.create(filter.project);
        IPackageFragmentRoot[] roots;
        try {
            roots = javaProject.getPackageFragmentRoots();
            scope = SearchEngine.createJavaSearchScope(roots, false);
        } catch (JavaModelException e) {
            e.printStackTrace();
        }
    } else {
        // filter.project may be null in the live editor
        scope = filter.project != null ? PDEJavaHelper.getSearchScope(filter.project)
                : SearchEngine.createWorkspaceScope();
    }
    char[] packageName = null;
    char[] typeName = null;
    String currentContent = filter.namePattern;
    int index = currentContent.lastIndexOf('.');

    if (index == -1) {
        // There is no package qualification
        // Perform the search only on the type name
        typeName = currentContent.toCharArray();
        if (currentContent.startsWith("*")) {
            if (!currentContent.endsWith("*")) {
                currentContent += "*";
            }
            typeName = currentContent.toCharArray();
            packageName = "*".toCharArray();
        }

    } else if ((index + 1) == currentContent.length()) {
        // There is a package qualification and the last character is a
        // dot
        // Perform the search for all types under the given package
        // Pattern for all types
        typeName = "".toCharArray(); //$NON-NLS-1$
        // Package name without the trailing dot
        packageName = currentContent.substring(0, index).toCharArray();
    } else {
        // There is a package qualification, followed by a dot, and 
        // a type fragment
        // Type name without the package qualification
        typeName = currentContent.substring(index + 1).toCharArray();
        // Package name without the trailing dot
        packageName = currentContent.substring(0, index).toCharArray();
    }

    //      char[] packageName = "at.bestsolution.e4.handlers".toCharArray();
    //      char[] typeName = "*".toCharArray();

    TypeNameRequestor req = new TypeNameRequestor() {
        @Override
        public void acceptType(int modifiers, char[] packageName, char[] simpleTypeName,
                char[][] enclosingTypeNames, String path) {
            // Accept search results from the JDT SearchEngine
            String cName = new String(simpleTypeName);
            String pName = new String(packageName);
            //            String label = cName + " - " + pName; //$NON-NLS-1$
            String content = pName.length() == 0 ? cName : pName + "." + cName; //$NON-NLS-1$

            //            System.err.println("Found: " + label + " => " + pName + " => " + path);

            IResource resource = ResourcesPlugin.getWorkspace().getRoot().findMember(path);

            if (resource != null) {
                IProject project = resource.getProject();
                IFile f = project.getFile("/META-INF/MANIFEST.MF");

                if (f != null && f.exists()) {
                    BufferedReader r = null;
                    try {
                        InputStream s = f.getContents();
                        r = new BufferedReader(new InputStreamReader(s));
                        String line;
                        while ((line = r.readLine()) != null) {
                            if (line.startsWith("Bundle-SymbolicName:")) {
                                int start = line.indexOf(':');
                                int end = line.indexOf(';');
                                if (end == -1) {
                                    end = line.length();
                                }
                                ContributionData data = new ContributionData(
                                        line.substring(start + 1, end).trim(), content, "Java", null);
                                handler.result(data);
                                break;
                            }
                        }

                    } catch (CoreException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } finally {
                        if (r != null) {
                            try {
                                r.close();
                            } catch (IOException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }
                        }
                    }
                }
            }

            //Image image = (Flags.isInterface(modifiers)) ? PDEPluginImages.get(PDEPluginImages.OBJ_DESC_GENERATE_INTERFACE) : PDEPluginImages.get(PDEPluginImages.OBJ_DESC_GENERATE_CLASS);
            //addProposalToCollection(c, startOffset, length, label, content, image);
        }
    };

    try {
        searchEngine.searchAllTypeNames(packageName, SearchPattern.R_PATTERN_MATCH, typeName,
                SearchPattern.R_PATTERN_MATCH | SearchPattern.R_CAMELCASE_MATCH, IJavaSearchConstants.CLASS,
                scope, req, IJavaSearchConstants.WAIT_UNTIL_READY_TO_SEARCH, null);
    } catch (JavaModelException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:org.eclipse.fx.ide.fxml.editors.FXMLCompletionProposalComputer.java

License:Open Source License

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

    try {/*from   w w w  . j  a va 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")) { //$NON-NLS-1$
                            priority -= 10;
                        }
                        StyledString s = new StyledString(new String(simpleTypeName));
                        s.append(" - " + sPackageName, StyledString.QUALIFIER_STYLER); //$NON-NLS-1$
                        FXMLCompletionProposal prop = createElementProposal(contentAssistRequest, context,
                                sPackageName + "." + new String(simpleTypeName) + " ", s, false, priority, //$NON-NLS-1$//$NON-NLS-2$
                                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 " //$NON-NLS-1$
                                                : "import ") + proposalReplacementString.trim(); //$NON-NLS-1$
                                        importStatement += "?>"; //$NON-NLS-1$

                                        if (endWithLineBreak)
                                            importStatement += "\n\n"; //$NON-NLS-1$
                                        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();
    }

}