Example usage for org.eclipse.jdt.core CompletionRequestor CompletionRequestor

List of usage examples for org.eclipse.jdt.core CompletionRequestor CompletionRequestor

Introduction

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

Prototype

public CompletionRequestor() 

Source Link

Document

Creates a new completion requestor.

Usage

From source file:at.bestsolution.fxide.jdt.editor.JDTProposalComputer.java

License:Open Source License

@Override
public CompletableFuture<List<CompletionProposal>> compute() {
    List<CompletionProposal> rv = new ArrayList<>();
    try {/* ww w.  j ava 2s.  c om*/
        input.getCompilationUnit().codeComplete(editingContext.getCaretOffset(), new CompletionRequestor() {
            @Override
            public void acceptContext(CompletionContext context) {
                super.acceptContext(context);
            }

            @Override
            public void accept(org.eclipse.jdt.core.CompletionProposal proposal) {
                if ((proposal.getAccessibility() & IAccessRule.K_ACCESSIBLE) == IAccessRule.K_ACCESSIBLE) {
                    rv.add(new JDTCompletionProposal(input.getCompilationUnit().getJavaProject(), proposal));
                }
            }
        }, (IProgressMonitor) null);
    } catch (JavaModelException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return CompletableFuture.completedFuture(rv);
}

From source file:at.bestsolution.javafx.ide.jdt.internal.JavaEditor.java

License:Open Source License

@Inject
public JavaEditor(BorderPane pane, IEditorInput input) {
    editor = new SourceEditor();
    pane.setCenter(editor);//from  w w  w .  j  a  va  2 s.com

    IResourceFileInput fsInput = (IResourceFileInput) input;
    try {
        unit = ((ICompilationUnit) JavaCore.create(fsInput.getFile()))
                .getWorkingCopy(new FXWorkingCopyOwner(new IProblemRequestor() {
                    private List<ProblemMarker> l = new ArrayList<>();

                    @Override
                    public boolean isActive() {
                        // TODO Auto-generated method stub
                        return true;
                    }

                    @Override
                    public void endReporting() {
                        setMarkers(l);
                    }

                    @Override
                    public void beginReporting() {
                        l.clear();
                    }

                    @Override
                    public void acceptProblem(IProblem problem) {
                        int linenumber = problem.getSourceLineNumber();
                        int startCol = problem.getSourceStart();
                        int endCol = problem.getSourceEnd();

                        if (endCol == startCol) {
                            endCol++;
                        }

                        String description = problem.getMessage();
                        ProblemMarker marker = new ProblemMarker(
                                problem.isError() ? at.bestsolution.javafx.ide.editor.ProblemMarker.Type.ERROR
                                        : at.bestsolution.javafx.ide.editor.ProblemMarker.Type.WARNING,
                                linenumber, startCol, endCol, description);
                        l.add(marker);
                    }
                }), new NullProgressMonitor());
    } catch (JavaModelException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    final Document doc = createDocument(unit);
    editor.setDocument(doc);
    editor.setContentProposalComputer(new ContentProposalComputer() {

        @Override
        public List<Proposal> computeProposals(String line, String prefix, int offset) {
            final List<Proposal> l = new ArrayList<ContentProposalComputer.Proposal>();

            try {
                unit.codeComplete(offset, new CompletionRequestor() {

                    @Override
                    public void accept(CompletionProposal proposal) {
                        String completion = new String(proposal.getCompletion());

                        if (!Flags.isPublic(proposal.getFlags())) {
                            return;
                        }

                        if (proposal.getKind() == CompletionProposal.METHOD_REF) {
                            String sig = Signature.toString(new String(proposal.getSignature()),
                                    new String(proposal.getName()), null, false, false);
                            StyledString s = new StyledString(sig + " : " + Signature.getSimpleName(Signature
                                    .toString(Signature.getReturnType(new String(proposal.getSignature())))));
                            s.appendString(
                                    " - " + Signature.getSignatureSimpleName(
                                            new String(proposal.getDeclarationSignature())),
                                    Style.colored("#AAAAAA"));

                            l.add(new Proposal(Type.METHOD, completion, s));
                        } else if (proposal.getKind() == CompletionProposal.FIELD_REF) {
                            StyledString s = new StyledString(
                                    completion + " : "
                                            + (proposal.getSignature() != null
                                                    ? Signature.getSignatureSimpleName(
                                                            new String(proposal.getSignature()))
                                                    : "<unknown>"));
                            s.appendString(
                                    " - " + (proposal.getDeclarationSignature() != null
                                            ? Signature.getSignatureSimpleName(
                                                    new String(proposal.getDeclarationSignature()))
                                            : "<unknown>"),
                                    Style.colored("#AAAAAA"));
                            l.add(new Proposal(Type.FIELD, completion, s));
                        } else if (proposal.getKind() == CompletionProposal.TYPE_REF) {
                            if (proposal.getAccessibility() == IAccessRule.K_NON_ACCESSIBLE) {
                                return;
                            }

                            StyledString s = new StyledString(
                                    Signature.getSignatureSimpleName(new String(proposal.getSignature())));
                            s.appendString(" - " + new String(proposal.getDeclarationSignature()),
                                    Style.colored("#AAAAAA"));
                            l.add(new Proposal(Type.TYPE, new String(proposal.getCompletion()), s));
                        } else {
                            System.err.println(proposal);
                        }
                    }
                });
            } catch (JavaModelException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return l;
        }

    });
    editor.setSaveCallback(new Runnable() {

        @Override
        public void run() {
            try {
                unit.commitWorkingCopy(true, null);
            } catch (JavaModelException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    });

    try {
        unit.reconcile(ICompilationUnit.NO_AST, true, null, null);
    } catch (JavaModelException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:com.microsoft.javapkgsrv.JavaParser.java

License:MIT License

private List<AutocompleteResponse.Completion> Autocomplete(ITypeRoot cu, int cursorPosition)
        throws JavaModelException {
    final List<AutocompleteResponse.Completion> proposals = new ArrayList<AutocompleteResponse.Completion>();
    cu.codeComplete(cursorPosition, new CompletionRequestor() {
        @Override/*from  w w w .  j a v a2s  . c  om*/
        public void accept(CompletionProposal proposal) {
            try {
                System.out.println(proposal.toString());
                proposals.add(translateToCompletion(proposal));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
    return proposals;
}

From source file:com.microsoft.javapkgsrv.JavaParser.java

License:MIT License

private List<ParamHelpResponse.Signature> ParamHelp(ITypeRoot cu, int cursorPosition)
        throws JavaModelException {
    final List<ParamHelpResponse.Signature> proposals = new ArrayList<ParamHelpResponse.Signature>();
    cu.codeComplete(cursorPosition, new CompletionRequestor() {
        @Override//from   w  w w  .  j  a  v  a  2 s  .c  o m
        public void accept(CompletionProposal proposal) {
            try {
                System.out.println(proposal.toString());
                if (proposal.getKind() == CompletionProposal.METHOD_REF) {
                    char[] javaSig = proposal.getSignature();

                    ParamHelpResponse.Signature.Builder sig = ParamHelpResponse.Signature.newBuilder()
                            .setName(new String(proposal.getName())).setReturnValue(
                                    new String(Signature.toCharArray(Signature.getReturnType(javaSig))));

                    char[][] javaParamTypes = Signature.getParameterTypes(javaSig);
                    for (char[] javaParamType : javaParamTypes) {
                        sig.addParameters(ParamHelpResponse.Parameter.newBuilder()
                                .setName(new String(Signature.toCharArray(javaParamType))).build());
                    }
                    proposals.add(sig.build());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });
    return proposals;
}

From source file:org.codehaus.groovy.eclipse.codeassist.processors.GroovyProposalTypeSearchRequestor.java

License:Apache License

private ICompletionProposal proposeConstructor(char[] simpleTypeName, int parameterCount, char[] signature,
        char[][] parameterTypes, char[][] parameterNames, int modifiers, char[] packageName, int typeModifiers,
        int accessibility, char[] typeName, char[] fullyQualifiedName, boolean isQualified, int extraFlags) {

    // only show context information and only for methods
    // that exactly match the name. This happens when we are at the
    // start of an argument or an open paren
    String simpleTypeNameStr = String.valueOf(simpleTypeName);
    String fullyQualifiedNameStr = String.valueOf(fullyQualifiedName);
    if (contextOnly && !completionExpression.equals(simpleTypeNameStr)
            && !completionExpression.equals(fullyQualifiedNameStr)) {
        return null;
    }//from  w ww. ja va  2 s  .c om

    char[] typeCompletion;
    if (isQualified) {
        typeCompletion = fullyQualifiedName;
        if (packageName == null || packageName.length == 0) {
            typeCompletion = simpleTypeName;
        }
    } else {
        typeCompletion = simpleTypeName;
    }

    float relevanceMultiplier = 1;
    relevanceMultiplier += accessibility == IAccessRule.K_ACCESSIBLE ? 2 : -1;
    relevanceMultiplier += computeRelevanceForCaseMatching(this.completionExpression.toCharArray(),
            simpleTypeName);

    int augmentedModifiers = modifiers;
    if (Flags.isDeprecated(typeModifiers)) {
        augmentedModifiers |= Flags.AccDeprecated;
    }

    if (parameterCount == -1) {
        // default constructor
        parameterNames = CharOperation.NO_CHAR_CHAR;
        parameterTypes = CharOperation.NO_CHAR_CHAR;
    } else {
        int parameterNamesLength = parameterNames == null ? 0 : parameterNames.length;
        if (parameterCount != parameterNamesLength) {
            parameterNames = null;
        }
    }

    GroovyCompletionProposal proposal = createProposal(
            contextOnly ? CompletionProposal.METHOD_REF : CompletionProposal.CONSTRUCTOR_INVOCATION,
            offset - 1);
    char[] declarationSignature = CompletionEngine.createNonGenericTypeSignature(packageName, typeName);
    proposal.setDeclarationSignature(declarationSignature);

    if (contextOnly) {
        proposal.setReplaceRange(actualCompletionPosition, actualCompletionPosition);
        proposal.setTokenRange(actualCompletionPosition, actualCompletionPosition);
        proposal.setCompletion(CharOperation.NO_CHAR);
    } else {
        // otherwise this is a normal constructor proposal
        proposal.setCompletion(this.completionExpression.toCharArray());
        // looks strange, but this is just copying similar code in
        // CompletionEngine.java
        proposal.setReplaceRange(this.offset + this.replaceLength, this.offset + this.replaceLength);
        proposal.setTokenRange(this.offset, this.actualCompletionPosition);
        proposal.setCompletion(new char[] { '(', ')' });

        // provides the import statement
        GroovyCompletionProposal typeProposal = createTypeProposal(packageName, typeModifiers, accessibility,
                typeName, fullyQualifiedName, isQualified, typeCompletion, augmentedModifiers,
                declarationSignature);
        proposal.setRequiredProposals(new CompletionProposal[] { typeProposal });
    }

    if (signature == null) {
        proposal.setSignature(createConstructorSignature(parameterTypes, isQualified));
    } else {
        char[] copy = new char[signature.length];
        System.arraycopy(signature, 0, copy, 0, copy.length);
        CharOperation.replace(copy, '/', '.');
        proposal.setSignature(copy);
    }

    if (parameterNames != null) {
        proposal.setParameterNames(parameterNames);
    } else {
        proposal.setHasNoParameterNamesFromIndex(true);
        if (mockEngine == null) {
            // used for caching types only
            mockEngine = new CompletionEngine(null, new CompletionRequestor() {

                @Override
                public void accept(CompletionProposal proposal) {

                }
            }, null, null, null, null);
        }
        proposal.setCompletionEngine(mockEngine);
    }

    proposal.setDeclarationPackageName(packageName);
    proposal.setDeclarationTypeName(simpleTypeName);
    proposal.setParameterTypeNames(parameterTypes);
    // proposal.setParameterPackageNames(); not right
    proposal.setName(simpleTypeName);

    proposal.setIsContructor(true);

    proposal.setRelevance(Relevance.MEDIUM_HIGH.getRelevance(relevanceMultiplier));

    proposal.setFlags(augmentedModifiers);

    proposal.setTypeName(simpleTypeName);
    proposal.setAccessibility(typeModifiers);
    proposal.setPackageName(packageName);

    LazyJavaCompletionProposal lazyProposal = new GroovyJavaMethodCompletionProposal(proposal, javaContext,
            getProposalOptions());
    lazyProposal.setRelevance(proposal.getRelevance());
    if (proposal.hasParameters()) {
        lazyProposal.setTriggerCharacters(ProposalUtils.METHOD_WITH_ARGUMENTS_TRIGGERS);
    } else {
        lazyProposal.setTriggerCharacters(ProposalUtils.METHOD_TRIGGERS);
    }
    ImportRewrite r = groovyRewriter.getImportRewrite(monitor);
    if (r != null) {
        ReflectionUtils.setPrivateField(LazyJavaTypeCompletionProposal.class, "fImportRewrite", lazyProposal,
                r);
    }
    if (contextOnly) {
        ((GroovyJavaMethodCompletionProposal) lazyProposal).contextOnly();
    }

    return lazyProposal;
}

From source file:org.drools.eclipse.editors.DRLRuleEditor.java

License:Apache License

public static List<String> getAllClassesInPackage(String packageName, IJavaProject javaProject) {
    final List<String> list = new ArrayList<String>();
    CompletionRequestor requestor = new CompletionRequestor() {
        public void accept(org.eclipse.jdt.core.CompletionProposal proposal) {
            String className = new String(proposal.getCompletion());
            if (proposal.getKind() == org.eclipse.jdt.core.CompletionProposal.TYPE_REF) {
                list.add(className);//from  w w w .j a  v a  2s  .co m
            }
            // ignore all other proposals
        }
    };

    try {
        javaProject.newEvaluationContext().codeComplete(packageName + ".", packageName.length() + 1, requestor);
    } catch (Throwable t) {
        DroolsEclipsePlugin.log(t);
    }
    return list;
}

From source file:org.drools.eclipse.editors.DRLRuleEditor.java

License:Apache License

protected List<String> getAllStaticMethodsInClass(String className) {
    final List<String> list = new ArrayList<String>();
    if (className != null) {
        IEditorInput input = getEditorInput();
        if (input instanceof IFileEditorInput) {
            IProject project = ((IFileEditorInput) input).getFile().getProject();
            IJavaProject javaProject = JavaCore.create(project);

            CompletionRequestor requestor = new CompletionRequestor() {
                public void accept(org.eclipse.jdt.core.CompletionProposal proposal) {
                    String functionName = new String(proposal.getCompletion());
                    if (proposal.getKind() == org.eclipse.jdt.core.CompletionProposal.METHOD_REF) {
                        list.add(functionName.substring(0, functionName.length() - 2)); // remove the ()
                    }/*from ww  w.ja  va2 s .  com*/
                    // ignore all other proposals
                }
            };

            try {
                javaProject.newEvaluationContext().codeComplete(className + ".", className.length() + 1,
                        requestor);
            } catch (Throwable t) {
                DroolsEclipsePlugin.log(t);
            }
        }
    }
    return list;
}

From source file:org.eclipse.dltk.mod.javascript.jdt.integration.JavaProposalReference.java

License:Open Source License

public Set getChilds(boolean resolveLocals) {
    if (resolveLocals) {
        String chType = getChildType();
        if (chType.charAt(0) == 'T')
            chType = "Ljava.lang.Object;";
        chType = chType.substring(1);/*  www .  ja  v a  2 s  .c o m*/
        int k = chType.indexOf('<');
        if (k != -1)
            chType = chType.substring(0, k);
        k = chType.indexOf(';');
        if (k != -1)
            chType = chType.substring(0, k);

        final IJavaProject create = project;

        String string = chType + " z=new " + chType + ";z.";
        final String id = chType;
        try {
            final HashSet result = new HashSet();
            context.codeComplete(string, string.length(), new CompletionRequestor() {
                public void accept(CompletionProposal proposal) {
                    IReference r = new JavaProposalReference(context, proposal, owner, create, id);
                    result.add(r);

                }
            });
            return result;
        } catch (JavaModelException e) {
            return null;
        }
    }
    return new HashSet();
}

From source file:org.eclipse.dltk.mod.javascript.jdt.integration.JdtReferenceResolver.java

License:Open Source License

public Set getChilds(final IResolvableReference ref) {
    if (ref instanceof AbstractCallResultReference) {
        final AbstractCallResultReference cm = (AbstractCallResultReference) ref;
        if (cm instanceof NewReference) {
            String preId = cm.getId();
            final HashSet result = new HashSet();
            if (preId.startsWith(PACKAGES))
                preId = preId.substring(PACKAGES.length());
            IJavaSearchScope createJavaSearchScope = SearchEngine
                    .createJavaSearchScope(new IJavaElement[] { create });
            SearchPattern createPattern = SearchPattern.createPattern("jsFunction*",
                    IJavaSearchConstants.METHOD, 100, SearchPattern.R_PATTERN_MATCH);
            try {

                engine.search(createPattern,
                        new org.eclipse.jdt.core.search.SearchParticipant[] {
                                engine.getDefaultSearchParticipant() },
                        createJavaSearchScope, new SearchRequestor() {

                            public void acceptSearchMatch(SearchMatch match) throws CoreException {
                                Object element = match.getElement();

                                if (element instanceof IMethod) {
                                    IMethod m = (IMethod) element;
                                    IType declaringType = m.getDeclaringType();
                                    if (!declaringType.getElementName().equals(cm.getId()))
                                        return;
                                    IMethod[] ts = declaringType.getMethods();
                                    for (int a = 0; a < ts.length; a++) {
                                        String string = "jsFunction_";
                                        String stringget = "jsGet_";
                                        String stringset = "jsSet_";
                                        IMethod method = ts[a];
                                        if (method.getElementName().startsWith(string)) {
                                            UnknownReference r = new UnknownReference(
                                                    method.getElementName().substring(string.length()), true);

                                            result.add(r);
                                            r.setFunctionRef();
                                        } else if (method.getElementName().startsWith(stringget)) {
                                            IReference r = new UnknownReference(
                                                    method.getElementName().substring(stringget.length()),
                                                    true);
                                            result.add(r);
                                        } else if (method.getElementName().startsWith(stringset)) {
                                            IReference r = new UnknownReference(
                                                    method.getElementName().substring(stringset.length()),
                                                    true);
                                            result.add(r);
                                        }
                                    }/* ww  w .j  a  va2  s.  co  m*/
                                }
                            }

                        }, null);
            } catch (CoreException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            final String cmid = preId;
            if (!result.isEmpty())
                return result;
            String string = cmid + " z=new " + cmid + ";z.";
            try {

                context.codeComplete(string, string.length(), new CompletionRequestor() {
                    public void accept(CompletionProposal proposal) {
                        IReference r = new JavaProposalReference(context, proposal, owner, create, cmid);
                        result.add(r);

                    }
                });
                return result;
            } catch (JavaModelException e) {
                return null;
            }
        }
        if (cm instanceof CallResultReference) {
            CallResultReference call = (CallResultReference) cm;
            IReference rm = call.getRoot();
            if (rm != null) {
                int lastIndexOf = call.getId().lastIndexOf('.');
                String substring = call.getId().substring(lastIndexOf + 1);
                IReference child = rm.getChild(substring, true);
                if (child == null)
                    return null;
                return child.getChilds(true);
            }
        }
    }
    return null;
}

From source file:org.eclipse.dltk.mod.javascript.jdt.integration.JdtReferenceResolver.java

License:Open Source License

public Set resolveGlobals(String id) {

    final HashSet result = new HashSet();
    if (id.startsWith(PACKAGES))
        id = id.substring(PACKAGES.length());
    final String id2 = id;

    String sm = id;// w w  w . j a  v  a2 s  . co m

    int indexOf = id.indexOf('.');

    if (indexOf == -1) {
        sm = "import " + sm;
        IJavaSearchScope createJavaSearchScope = SearchEngine
                .createJavaSearchScope(new IJavaElement[] { create });
        SearchPattern createPattern = SearchPattern.createPattern("jsFunction*", IJavaSearchConstants.METHOD,
                100, SearchPattern.R_PATTERN_MATCH);
        try {
            engine.search(createPattern,
                    new org.eclipse.jdt.core.search.SearchParticipant[] {
                            engine.getDefaultSearchParticipant() },
                    createJavaSearchScope, new SearchRequestor() {

                        public void acceptSearchMatch(SearchMatch match) throws CoreException {
                            Object element = match.getElement();

                            if (element instanceof IMethod) {
                                IMethod m = (IMethod) element;
                                String elementName = m.getDeclaringType().getElementName();
                                IReference r = new ClassRef(elementName, true);
                                result.add(r);
                            }
                        }

                    }, null);
        } catch (CoreException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        if (result.size() > 0)
            return result;
        try {
            context.codeComplete(sm, sm.length(), new CompletionRequestor() {

                public void accept(CompletionProposal proposal) {
                    if (proposal.getName() != null) {
                        IReference r = new JavaProposalReference(context, proposal, owner, create, "");
                        result.add(r);
                    } else {
                        char[] completion = proposal.getCompletion();
                        String sm = new String(completion);
                        IReference r = new JavaProposalReference(context, sm, proposal, owner, create, "");
                        result.add(r);
                    }
                }

            });
        } catch (JavaModelException e) {

        }
    } else {
        try {
            context.codeComplete(sm, sm.length(), new CompletionRequestor() {

                public void accept(CompletionProposal proposal) {
                    if (proposal.getName() != null) {
                        IReference r = new JavaProposalReference(context, proposal, owner, create, "");
                        result.add(r);
                    } else {

                        char[] completion = proposal.getCompletion();
                        String sm = new String(completion);
                        String pName = sm;
                        if (proposal.getKind() == CompletionProposal.PACKAGE_REF) {
                            sm = sm.substring(id2.length());
                        } else {
                            if (sm.startsWith(id2) && sm.length() != id2.length())
                                sm = sm.substring(id2.length()).trim();

                        }
                        IReference r = new JavaProposalReference(context, sm, proposal, owner, create, pName);
                        result.add(r);
                    }
                }

            });
        } catch (JavaModelException e) {

        }
    }
    return result;
}