Example usage for org.eclipse.jdt.core IJavaElement FIELD

List of usage examples for org.eclipse.jdt.core IJavaElement FIELD

Introduction

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

Prototype

int FIELD

To view the source code for org.eclipse.jdt.core IJavaElement FIELD.

Click Source Link

Document

Constant representing a field.

Usage

From source file:org.codehaus.groovy.eclipse.codeassist.completions.ParameterGuesserDelegate.java

License:Apache License

public ICompletionProposal[] parameterProposals(String parameterType, String paramName, Position position,
        IJavaElement[] assignable, boolean fillBestGuess) {
    parameterType = convertToPrimitive(parameterType);

    Method method = findParameterProposalsMethod();
    try {/* ww  w.j  a va  2 s. c  o m*/
        ICompletionProposal[] allCompletions;
        if (method.getParameterTypes().length == 5) {
            // 3.6
            allCompletions = (ICompletionProposal[]) method.invoke(guesser, parameterType, paramName, position,
                    assignable, fillBestGuess);
        } else {
            // 3.7 and later
            allCompletions = (ICompletionProposal[]) method.invoke(guesser, parameterType, paramName, position,
                    assignable, fillBestGuess, false);
        }

        // ensure enum proposals insert the declaring type as part of the
        // name.
        if (allCompletions != null && allCompletions.length > 0 && assignable != null
                && assignable.length > 0) {
            IType declaring = (IType) assignable[0].getAncestor(IJavaElement.TYPE);
            if (declaring != null && declaring.isEnum()) {
                // each enum is proposed twice. The first time, use the
                // qualified name and the second keep with the simple name
                boolean useFull = true;
                for (int i = 0; i < assignable.length && i < allCompletions.length; i++) {
                    if (assignable[i].getElementType() == IJavaElement.FIELD) {
                        if (useFull) {
                            String newReplacement = declaring.getElementName() + '.'
                                    + assignable[i].getElementName();
                            ReflectionUtils.setPrivateField(PositionBasedCompletionProposal.class,
                                    "fReplacementString", allCompletions[i], newReplacement);
                            ReflectionUtils.setPrivateField(PositionBasedCompletionProposal.class,
                                    "fDisplayString", allCompletions[i], newReplacement);
                            useFull = false;
                        } else {
                            useFull = true;
                        }
                    }
                }
            }
        }
        return addExtras(allCompletions, parameterType, position);
    } catch (Exception e) {
        GroovyCore.logException("Exception trying to reflectively invoke 'parameterProposals' method.", e);
        return ProposalUtils.NO_COMPLETIONS;
    }

}

From source file:org.codehaus.groovy.eclipse.codebrowsing.requestor.CodeSelectRequestor.java

License:Apache License

/**
 * Converts the maybeRequested element into a resolved element by creating a unique key for it.
 *///from  w  ww  . ja v  a 2  s. c  o m
private IJavaElement resolveRequestedElement(TypeLookupResult result, IJavaElement maybeRequested) {
    AnnotatedNode declaration = (AnnotatedNode) result.declaration;
    if (declaration instanceof PropertyNode && maybeRequested instanceof IMethod) {
        // the field associated with this property does not exist, use the method instead
        String getterName = maybeRequested.getElementName();
        MethodNode maybeDeclaration = (MethodNode) declaration.getDeclaringClass().getMethods(getterName)
                .get(0);
        declaration = maybeDeclaration == null ? declaration : maybeDeclaration;
    }

    String uniqueKey = createUniqueKey(declaration, result.type, result.declaringType, maybeRequested);
    IJavaElement candidate;

    // Create the Groovy Resolved Element, which is like a resolved element, but contains extraDoc, as
    // well as the inferred declaration (which may not be the same as the actual declaration)
    switch (maybeRequested.getElementType()) {
    case IJavaElement.FIELD:
        if (maybeRequested.isReadOnly()) {
            candidate = new GroovyResolvedBinaryField((JavaElement) maybeRequested.getParent(),
                    maybeRequested.getElementName(), uniqueKey, result.extraDoc, result.declaration);
        } else {
            candidate = new GroovyResolvedSourceField((JavaElement) maybeRequested.getParent(),
                    maybeRequested.getElementName(), uniqueKey, result.extraDoc, result.declaration);
        }
        break;
    case IJavaElement.METHOD:
        if (maybeRequested.isReadOnly()) {
            candidate = new GroovyResolvedBinaryMethod((JavaElement) maybeRequested.getParent(),
                    maybeRequested.getElementName(), ((IMethod) maybeRequested).getParameterTypes(), uniqueKey,
                    result.extraDoc, result.declaration);
        } else {
            candidate = new GroovyResolvedSourceMethod((JavaElement) maybeRequested.getParent(),
                    maybeRequested.getElementName(), ((IMethod) maybeRequested).getParameterTypes(), uniqueKey,
                    result.extraDoc, result.declaration);
        }
        break;
    case IJavaElement.TYPE:
        if (maybeRequested.isReadOnly()) {
            candidate = new GroovyResolvedBinaryType((JavaElement) maybeRequested.getParent(),
                    maybeRequested.getElementName(), uniqueKey, result.extraDoc, result.declaration);
        } else {
            candidate = new GroovyResolvedSourceType((JavaElement) maybeRequested.getParent(),
                    maybeRequested.getElementName(), uniqueKey, result.extraDoc, result.declaration);
        }
        break;
    default:
        candidate = maybeRequested;
    }
    requestedElement = candidate;
    return requestedElement;
}

From source file:org.codehaus.groovy.eclipse.codebrowsing.requestor.CodeSelectRequestor.java

License:Apache License

/**
 * Creates the unique key for classes, fields and methods
 * @param node/*from   w w  w  . j a v  a  2 s .  c o m*/
 * @param maybeRequested 
 * @return
 */
private String createUniqueKey(AnnotatedNode node, ClassNode resolvedType, ClassNode resolvedDeclaringType,
        IJavaElement maybeRequested) {
    if (resolvedDeclaringType == null) {
        resolvedDeclaringType = node.getDeclaringClass();
        if (resolvedDeclaringType == null) {
            resolvedDeclaringType = VariableScope.OBJECT_CLASS_NODE;
        }
    }
    StringBuilder sb = new StringBuilder();
    if (node instanceof PropertyNode) {
        node = ((PropertyNode) node).getField();
    }
    if (node instanceof FieldNode) {
        return createUniqueKeyForField((FieldNode) node, resolvedType, resolvedDeclaringType).toString();
    } else if (node instanceof MethodNode) {
        if (maybeRequested.getElementType() == IJavaElement.FIELD) {
            // this is likely a generated getter or setter
            return createUniqueKeyForGeneratedAccessor((MethodNode) node, resolvedType, resolvedDeclaringType,
                    (IField) maybeRequested).toString();
        } else {
            return createUniqueKeyForMethod((MethodNode) node, resolvedType, resolvedDeclaringType).toString();
        }
    } else if (node instanceof ClassNode) {
        return createUniqueKeyForClass(resolvedType, resolvedDeclaringType).toString();
    }
    return sb.toString();
}

From source file:org.codehaus.groovy.eclipse.core.search.SyntheticAccessorSearchRequestor.java

License:Apache License

private IMethod findSyntheticMember(IJavaElement element, String prefix) throws JavaModelException {
    if (element.getElementType() != IJavaElement.FIELD) {
        return null;
    }/*from ww  w. j a  va 2  s  .c  o  m*/
    IType parent = (IType) element.getParent();
    String[] sigs;
    String[] names;
    if (prefix.equals("set")) {
        sigs = new String[] { ((IField) element).getTypeSignature() };
        names = new String[] { element.getElementName() };
    } else {
        sigs = new String[0];
        names = new String[0];
    }
    MethodWrapper method = new MethodWrapper(
            parent.getMethod(convertName(prefix, element.getElementName()), sigs), names);
    // only return if method doesn't exist since otherwise, this method would not be synthetic
    return method.reallyExists() ? null : method;
}

From source file:org.codehaus.groovy.eclipse.test.ui.OutlineExtenderTests.java

License:Apache License

public void testGroovyScriptOutline1() throws Exception {
    String contents = "import java.util.Map\n" + "int[] xxx \n" + "def ttt = 8\n" + "Object hhh = 8\n"
            + "class Y { }\n" + "String blah() {  }";
    GroovyOutlinePage outline = openFile("Script", contents);

    OCompilationUnit unit = outline.getOutlineCompilationUnit();
    IJavaElement[] children = unit.getChildren();

    assertEquals("Wrong number of children", 6, children.length);
    assertEquals("", children[0].getElementName()); // import container has no name
    assertEquals("xxx", children[1].getElementName());
    assertEquals("ttt", children[2].getElementName());
    assertEquals("hhh", children[3].getElementName());
    assertEquals("Y", children[4].getElementName());
    assertEquals("blah", children[5].getElementName());

    assertEquals(IJavaElement.IMPORT_CONTAINER, children[0].getElementType());
    assertEquals(IJavaElement.FIELD, children[1].getElementType());
    assertEquals(IJavaElement.FIELD, children[2].getElementType());
    assertEquals(IJavaElement.FIELD, children[3].getElementType());
    assertEquals(IJavaElement.TYPE, children[4].getElementType());
    assertEquals(IJavaElement.METHOD, children[5].getElementType());

    assertEquals("[I", ((IField) children[1]).getTypeSignature());
    assertEquals("Qdef;", ((IField) children[2]).getTypeSignature());
    assertEquals("QObject;", ((IField) children[3]).getTypeSignature());

    assertEquals(contents.indexOf("xxx"), ((IField) children[1]).getNameRange().getOffset());
    assertEquals(contents.indexOf("ttt"), ((IField) children[2]).getNameRange().getOffset());
    assertEquals(contents.indexOf("hhh"), ((IField) children[3]).getNameRange().getOffset());

    assertEquals(3, ((IField) children[1]).getNameRange().getLength());
    assertEquals(3, ((IField) children[2]).getNameRange().getLength());
    assertEquals(3, ((IField) children[3]).getNameRange().getLength());
}

From source file:org.drools.eclipse.editors.completion.RuleCompletionProcessor.java

License:Apache License

private static void processesJavaCompletionProposal(boolean settersOnly, final Collection set, Object o) {
    if (settersOnly) {
        JavaCompletionProposal jcp = (JavaCompletionProposal) o;
        //TODO: FIXME: this is very fragile as it uses reflection to access the private completion field.
        //Yet this is needed to do mvel filtering based on the method signtures, IF we use the richer JDT completion
        //                    Object field = ReflectionUtils.getField( o,
        //                                                             "fProposal" );
        IJavaElement javaElement = jcp.getJavaElement();
        if (javaElement.getElementType() == IJavaElement.FIELD) {
            set.add(o);//from  w  w  w .j av  a 2 s.  c  om

        }
    } else {
        set.add(o);
    }
}

From source file:org.eclim.plugin.jdt.command.complete.CompletionProposalCollector.java

License:Open Source License

public void completionFailure(IProblem problem) {
    ICompilationUnit src = getCompilationUnit();
    IJavaProject javaProject = src.getJavaProject();
    IProject project = javaProject.getProject();

    // undefined type or attempting to complete static members of an unimported
    // type/*ww  w.  ja  v a2s .  co  m*/
    if (problem.getID() == IProblem.UndefinedType || problem.getID() == IProblem.UnresolvedVariable) {
        try {
            SearchPattern pattern = SearchPattern.createPattern(problem.getArguments()[0],
                    IJavaSearchConstants.TYPE, IJavaSearchConstants.DECLARATIONS,
                    SearchPattern.R_EXACT_MATCH | SearchPattern.R_CASE_SENSITIVE);
            IJavaSearchScope scope = SearchEngine.createJavaSearchScope(new IJavaElement[] { javaProject });
            SearchRequestor requestor = new SearchRequestor();
            SearchEngine engine = new SearchEngine();
            SearchParticipant[] participants = new SearchParticipant[] {
                    SearchEngine.getDefaultSearchParticipant() };
            engine.search(pattern, participants, scope, requestor, null);
            if (requestor.getMatches().size() > 0) {
                imports = new ArrayList<String>();
                for (SearchMatch match : requestor.getMatches()) {
                    if (match.getAccuracy() != SearchMatch.A_ACCURATE) {
                        continue;
                    }
                    IJavaElement element = (IJavaElement) match.getElement();
                    String name = null;
                    switch (element.getElementType()) {
                    case IJavaElement.TYPE:
                        IType type = (IType) element;
                        if (Flags.isPublic(type.getFlags())) {
                            name = type.getFullyQualifiedName();
                        }
                        break;
                    case IJavaElement.METHOD:
                    case IJavaElement.FIELD:
                        name = ((IType) element.getParent()).getFullyQualifiedName() + '.'
                                + element.getElementName();
                        break;
                    }
                    if (name != null) {
                        name = name.replace('$', '.');
                        if (!ImportUtils.isImportExcluded(project, name)) {
                            imports.add(name);
                        }
                    }
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    IResource resource = src.getResource();
    String relativeName = resource.getProjectRelativePath().toString();
    if (new String(problem.getOriginatingFileName()).endsWith(relativeName)) {
        String filename = resource.getLocation().toString();

        // ignore the problem if a temp file is being used and the problem is that
        // the type needs to be defined in its own file.
        if (problem.getID() == IProblem.PublicClassMustMatchFileName
                && filename.indexOf("__eclim_temp_") != -1) {
            return;
        }

        FileOffsets offsets = FileOffsets.compile(filename);
        int[] lineColumn = offsets.offsetToLineColumn(problem.getSourceStart());

        error = new Error(problem.getMessage(), filename.replace("__eclim_temp_", ""), lineColumn[0],
                lineColumn[1], problem.isWarning());
    }
}

From source file:org.eclim.plugin.jdt.command.delegate.DelegateCommand.java

License:Open Source License

/**
 * {@inheritDoc}/*  w  w  w.j  a  va 2 s  .  co m*/
 */
public String execute(CommandLine commandLine) throws Exception {
    String project = commandLine.getValue(Options.PROJECT_OPTION);
    String file = commandLine.getValue(Options.FILE_OPTION);
    ICompilationUnit src = JavaUtils.getCompilationUnit(project, file);

    IJavaElement element = src.getElementAt(getOffset(commandLine));
    if (element.getElementType() != IJavaElement.FIELD) {
        return Services.getMessage("not.a.field");
    }

    field = (IField) element;

    String signature = field.getTypeSignature();
    IType delegateType = TypeUtils.findUnqualifiedType(src, Signature.getSignatureSimpleName(signature));

    if (delegateType == null) {
        return Services.getMessage("type.not.found", src.getJavaProject().getElementName(),
                Signature.getSignatureSimpleName(signature)) + "  " + Services.getMessage("check.import");
    }

    ITypeParameter[] params = delegateType.getTypeParameters();
    String[] typeParams = new String[params.length];
    for (int ii = 0; ii < params.length; ii++) {
        typeParams[ii] = params[ii].getElementName();
    }

    String[] args = Signature.getTypeArguments(signature);
    String[] typeArgs = new String[args.length];
    for (int ii = 0; ii < args.length; ii++) {
        typeArgs[ii] = Signature.getSignatureSimpleName(args[ii]);
    }

    delegateTypeInfo = new TypeInfo(delegateType, typeParams, typeArgs);

    return super.execute(commandLine);
}

From source file:org.eclim.plugin.jdt.command.doc.DocSearchCommand.java

License:Open Source License

@Override
public Object execute(CommandLine commandLine) throws Exception {
    IProject project = ProjectUtils.getProject(commandLine.getValue(Options.NAME_OPTION));
    String pattern = commandLine.getValue(Options.PATTERN_OPTION);

    IWorkbenchHelpSystem helpSystem = PlatformUI.getWorkbench().getHelpSystem();

    ArrayList<String> results = new ArrayList<String>();
    for (SearchMatch match : executeSearch(commandLine)) {
        IJavaElement element = (IJavaElement) match.getElement();

        if (element == null) {
            continue;
        }/*w ww.j a  v a2  s  .  c  o m*/

        // for pattern searches, honor import excludes
        if (pattern != null) {
            String name = null;
            switch (element.getElementType()) {
            case IJavaElement.TYPE:
                name = ((IType) element).getFullyQualifiedName();
                break;
            case IJavaElement.METHOD:
            case IJavaElement.FIELD:
                name = ((IType) element.getParent()).getFullyQualifiedName();
                break;
            }
            if (name != null) {
                name = name.replace('$', '.');
                if (ImportUtils.isImportExcluded(project, name)) {
                    continue;
                }
            }
        }

        URL url = JavaUI.getJavadocLocation(element, true);
        if (url == null) {
            continue;
        }

        // android injects its own docs, so filter those out if the project doesn't
        // have the android nature.
        if (ANDROID_JDK_URL.matcher(url.toString()).matches() && !project.hasNature(ANDROID_NATURE)) {
            continue;
        }

        // convert any jar urls to a usable eclipse url
        Matcher jarMatcher = JAR_URL.matcher(url.toExternalForm());
        if (jarMatcher.matches()) {
            url = helpSystem.resolve(url.toExternalForm(), true);
        }

        results.add(url.toString());
    }
    return results;
}

From source file:org.eclim.plugin.jdt.command.impl.DelegateCommand.java

License:Open Source License

@Override
public Object execute(CommandLine commandLine) throws Exception {
    String project = commandLine.getValue(Options.PROJECT_OPTION);
    String file = commandLine.getValue(Options.FILE_OPTION);
    ICompilationUnit src = JavaUtils.getCompilationUnit(project, file);

    IJavaElement element = null;/*from  www  .jav  a  2s  .  co  m*/
    if (commandLine.hasOption(Options.VARIABLE_OPTION)) {
        String var = commandLine.getValue(Options.VARIABLE_OPTION);
        String[] parts = StringUtils.split(var, ".");
        String varName = parts[parts.length - 1];
        IType type = getType(src, commandLine);
        element = type.getField(varName);
    } else {
        element = src.getElementAt(getOffset(commandLine));
    }

    if (element == null || element.getElementType() != IJavaElement.FIELD) {
        return Services.getMessage("not.a.field");
    }

    IField field = (IField) element;
    String signature = field.getTypeSignature();
    IType delegateType = TypeUtils.findUnqualifiedType(src, Signature.getSignatureSimpleName(signature));

    if (delegateType == null) {
        return Services.getMessage("type.not.found", src.getJavaProject().getElementName(),
                Signature.getSignatureSimpleName(signature)) + "  " + Services.getMessage("check.import");
    }

    this.field.set(field);
    return super.execute(commandLine);
}