Example usage for org.eclipse.jdt.core IType getField

List of usage examples for org.eclipse.jdt.core IType getField

Introduction

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

Prototype

IField getField(String name);

Source Link

Document

Returns the field with the specified name in this type (for example, "bar").

Usage

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

License:Open Source License

public static HtmlString toHtml(CompletionProposal proposal, IJavaProject jProject) throws JavaModelException {
    String content = null;/*from   w w  w  . j a v a2 s.c o  m*/
    if (proposal.getKind() == org.eclipse.jdt.core.CompletionProposal.FIELD_REF) {
        IType jType = getOwnerType(proposal, jProject);
        if (jType != null) {
            IField field = jType.getField(String.valueOf(proposal.getName()));
            if (field != null && field.exists()) {
                try {
                    content = JavadocContentAccess2.getHTMLContent(field, true);
                } catch (CoreException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    } else if (proposal.getKind() == org.eclipse.jdt.core.CompletionProposal.METHOD_REF) {
        IType jType = getOwnerType(proposal, jProject);
        if (jType != null) {
            MethodUtil m = new MethodUtil(proposal, jType);
            IMethod method = m.resolve();
            if (method != null && method.exists()) {
                try {
                    content = JavadocContentAccess2.getHTMLContent(method, true);
                    if (content != null) {
                        content = content.replace("<pre><code>",
                                "<pre class=\"prettyprint\"><code class=\"language-java\">");
                    }
                } catch (CoreException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }

    if (content != null) {
        return new HtmlString("<html><header><style>"
                + ("theme.dark".equals(themeMgr.getCurrentTheme().getId()) ? darkCSS : defaultCSS)
                + "</style><script>" + prettifyJS + "\n</script></header><body onload='PR.prettyPrint();'>"
                + content + "</body></html>");
    }

    return null;
}

From source file:at.bestsolution.fxide.jdt.text.javadoc.JavadocContentAccess2.java

License:Open Source License

private static String getJavaFxPropertyDoc(IMember member) throws JavaModelException {
    // XXX: should not do this by default (but we don't have settings for Javadoc, see https://bugs.eclipse.org/424283 )
    if (member instanceof IMethod) {
        String name = member.getElementName();
        boolean isGetter = name.startsWith("get") && name.length() > 3; //$NON-NLS-1$
        boolean isBooleanGetter = name.startsWith("is") && name.length() > 2; //$NON-NLS-1$
        boolean isSetter = name.startsWith("set") && name.length() > 3; //$NON-NLS-1$

        if (isGetter || isBooleanGetter || isSetter) {
            String propertyName = firstToLower(name.substring(isBooleanGetter ? 2 : 3));
            IType type = member.getDeclaringType();
            IMethod method = type.getMethod(propertyName + "Property", new String[0]); //$NON-NLS-1$

            if (method.exists()) {
                String content = getHTMLContentFromSource(method);
                if (content != null) {
                    if (isSetter) {
                        content = Messages.format(JavaDocMessages.JavadocContentAccess2_setproperty_message,
                                new Object[] { propertyName, content });
                    } else {
                        content = Messages.format(JavaDocMessages.JavadocContentAccess2_getproperty_message,
                                new Object[] { propertyName, content });
                    }/*from   ww  w.  j a  v a2s . c o m*/
                }
                return content;
            }
        } else if (name.endsWith("Property")) { //$NON-NLS-1$
            String propertyName = name.substring(0, name.length() - 8);

            IType type = member.getDeclaringType();
            IField field = type.getField(propertyName);
            if (field.exists()) {
                return getHTMLContentFromSource(field);
            }
        }
    }
    return null;
}

From source file:at.bestsolution.fxide.jdt.text.javadoc.JavadocContentAccess2.java

License:Open Source License

private boolean handleValueTag(TagElement node) {

    List<? extends ASTNode> fragments = node.fragments();
    try {/* w ww  . j a  va  2 s.c o  m*/
        if (!(fElement instanceof IMember)) {
            return false;
        }
        if (fragments.isEmpty()) {
            if (fElement instanceof IField && JdtFlags.isStatic((IField) fElement)
                    && JdtFlags.isFinal((IField) fElement)) {
                IField field = (IField) fElement;
                return handleConstantValue(field, false);
            }
        } else if (fragments.size() == 1) {
            Object first = fragments.get(0);
            if (first instanceof MemberRef) {
                MemberRef memberRef = (MemberRef) first;
                if (memberRef.getQualifier() == null) {
                    SimpleName name = memberRef.getName();
                    IType type = fElement instanceof IType ? (IType) fElement
                            : ((IMember) fElement).getDeclaringType();
                    while (type != null) {
                        IField field = type.getField(name.getIdentifier());
                        if (field != null && field.exists()) {
                            if (JdtFlags.isStatic(field) && JdtFlags.isFinal(field))
                                return handleConstantValue(field, true);
                            break;
                        }
                        type = type.getDeclaringType();
                    }
                }
            }
        }
    } catch (JavaModelException e) {
        //TODO
        e.printStackTrace();
    }

    return false;
}

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

License:Open Source License

/**
 * Returns the activities associated with the given layout file. Makes an educated guess
 * by peeking at the usages of the R.layout.name field corresponding to the layout and
 * if it finds a usage.//from w w w. ja  v a 2s. com
 *
 * @param project the project containing the layout
 * @param layoutName the layout whose activity we want to look up
 * @param pkg the package containing activities
 * @return the activity name
 */
@NonNull
public static List<String> guessActivities(IProject project, String layoutName, String pkg) {
    final LinkedList<String> activities = new LinkedList<String>();
    SearchRequestor requestor = new SearchRequestor() {
        @Override
        public void acceptSearchMatch(SearchMatch match) throws CoreException {
            Object element = match.getElement();
            if (element instanceof IMethod) {
                IMethod method = (IMethod) element;
                IType declaringType = method.getDeclaringType();
                String fqcn = declaringType.getFullyQualifiedName();

                if ((declaringType.getSuperclassName() != null
                        && declaringType.getSuperclassName().endsWith("Activity")) //$NON-NLS-1$
                        || method.getElementName().equals("onCreate")) { //$NON-NLS-1$
                    activities.addFirst(fqcn);
                } else {
                    activities.addLast(fqcn);
                }
            }
        }
    };
    try {
        IJavaProject javaProject = BaseProjectHelper.getJavaProject(project);
        if (javaProject == null) {
            return Collections.emptyList();
        }
        // TODO - look around a bit more and see if we can figure out whether the
        // call if from within a setContentView call!

        // Search for which java classes call setContentView(R.layout.layoutname);
        String typeFqcn = "R.layout"; //$NON-NLS-1$
        if (pkg != null) {
            typeFqcn = pkg + '.' + typeFqcn;
        }

        IType type = javaProject.findType(typeFqcn);
        if (type != null) {
            IField field = type.getField(layoutName);
            if (field.exists()) {
                SearchPattern pattern = SearchPattern.createPattern(field, REFERENCES);
                try {
                    search(requestor, javaProject, pattern);
                } catch (OperationCanceledException canceled) {
                    // pass
                }
            }
        }
    } catch (CoreException e) {
        AdtPlugin.log(e, null);
    }

    return activities;
}

From source file:com.android.ide.eclipse.adt.internal.refactorings.core.RenameResourceParticipant.java

License:Open Source License

/**
 * Initiates a renaming of a resource item
 *
 * @param project the project containing the resource references
 * @param type the type of resource//from   w  w  w. j  ava 2  s  . c  o  m
 * @param name the name of the resource
 * @return false if initiating the rename failed
 */
@Nullable
private static IField getResourceField(@NonNull IProject project, @NonNull ResourceType type,
        @NonNull String name) {
    try {
        IJavaProject javaProject = BaseProjectHelper.getJavaProject(project);
        if (javaProject == null) {
            return null;
        }

        String pkg = ManifestInfo.get(project).getPackage();
        // TODO: Rename in all libraries too?
        IType t = javaProject.findType(pkg + '.' + R_CLASS + '.' + type.getName());
        if (t == null) {
            return null;
        }

        return t.getField(name);
    } catch (CoreException e) {
        AdtPlugin.log(e, null);
    }

    return null;
}

From source file:com.android.ide.eclipse.adt.internal.refactorings.core.RenameResourceParticipantTest.java

License:Open Source License

public void testRefactor8() throws Exception {
    // Test refactoring initiated on a Java field rename
    IProject project = createProject(TEST_PROJECT);
    IJavaProject javaProject = BaseProjectHelper.getJavaProject(project);
    assertNotNull(javaProject);//from  ww w.  jav a 2s  . c  o  m
    IType type = javaProject.findType("com.example.refactoringtest.R.layout");
    if (type == null || !type.exists()) {
        type = javaProject.findType("com.example.refactoringtest.R$layout");
        System.out.println("Had to switch to $ notation");
    }
    assertNotNull(type);
    assertTrue(type.exists());
    IField field = type.getField("activity_main");
    assertNotNull(field);
    assertTrue(field.exists());

    renameResource(project, field, true /*updateReferences*/, "newlauncher",

            "CHANGES:\n" + "-------\n"
                    + "[x] Rename 'testRefactor8/res/layout/activity_main.xml' to 'newlauncher.xml'\n" + "\n"
                    + "[x] Rename 'testRefactor8/res/layout-land/activity_main.xml' to 'newlauncher.xml'\n"
                    + "\n"
                    + "[x] MainActivity.java - /testRefactor8/src/com/example/refactoringtest/MainActivity.java\n"
                    + "  @@ -13 +13\n" + "  -         setContentView(R.layout.activity_main);\n"
                    + "  +         setContentView(R.layout.newlauncher);\n" + "\n" + "\n"
                    + "[ ] R.java - /testRefactor8/gen/com/example/refactoringtest/R.java\n" + "  @@ -23 +23\n"
                    + "  -         public static final int activity_main=0x7f030000;\n"
                    + "  +         public static final int newlauncher=0x7f030000;",
            null);
}

From source file:com.codenvy.ide.ext.java.JavadocTest.java

License:Open Source License

@Test
public void binaryFieldDoc() throws JavaModelException {
    IType type = project.findType("java.util.ArrayList");
    assertThat(type).isNotNull();/*from w ww. j a  v  a  2s. c  o  m*/
    IField field = type.getField("size");
    assertThat(field).isNotNull();
    String htmlContent = JavadocContentAccess2.getHTMLContent(field, true, urlPart);
    assertThat(htmlContent).isNotNull().isNotEmpty()
            .contains("The size of the ArrayList (the number of elements it contains).");
}

From source file:com.codenvy.ide.ext.java.JavadocUrlTest.java

License:Open Source License

@Test
public void binaryFieldUri() throws JavaModelException, URISyntaxException, UnsupportedEncodingException {
    IType type = project.findType("java.util.ArrayList");
    IField field = type.getField("size");
    String uri = JavaElementLinks.createURI(urlPart, field);
    String handle = uri.substring(urlPart.length());
    handle = URLDecoder.decode(handle, "UTF-8");
    IJavaElement element = JavaElementLinks.parseURI(handle, project);
    assertThat(element).isNotNull().isEqualTo(field);
}

From source file:com.codenvy.ide.ext.java.server.internal.core.search.matching.FieldLocator.java

License:Open Source License

protected void reportDeclaration(FieldBinding fieldBinding, MatchLocator locator, SimpleSet knownFields)
        throws CoreException {
    // ignore length field
    if (fieldBinding == ArrayBinding.ArrayLength)
        return;// w w  w . ja  va  2 s  .c o  m

    ReferenceBinding declaringClass = fieldBinding.declaringClass;
    IType type = locator.lookupType(declaringClass);
    if (type == null)
        return; // case of a secondary type

    char[] bindingName = fieldBinding.name;
    IField field = type.getField(new String(bindingName));
    if (knownFields.addIfNotIncluded(field) == null)
        return;

    IResource resource = type.getResource();
    boolean isBinary = type.isBinary();
    IBinaryType info = null;
    if (isBinary) {
        if (resource == null)
            resource = type.getJavaProject().getProject();
        info = locator.getBinaryInfo((org.eclipse.jdt.internal.core.ClassFile) type.getClassFile(), resource);
        locator.reportBinaryMemberDeclaration(resource, field, fieldBinding, info, SearchMatch.A_ACCURATE);
    } else {
        if (declaringClass instanceof ParameterizedTypeBinding)
            declaringClass = ((ParameterizedTypeBinding) declaringClass).genericType();
        ClassScope scope = ((SourceTypeBinding) declaringClass).scope;
        if (scope != null) {
            TypeDeclaration typeDecl = scope.referenceContext;
            FieldDeclaration fieldDecl = null;
            FieldDeclaration[] fieldDecls = typeDecl.fields;
            int length = fieldDecls == null ? 0 : fieldDecls.length;
            for (int i = 0; i < length; i++) {
                if (CharOperation.equals(bindingName, fieldDecls[i].name)) {
                    fieldDecl = fieldDecls[i];
                    break;
                }
            }
            if (fieldDecl != null) {
                int offset = fieldDecl.sourceStart;
                this.match = new FieldDeclarationMatch(((JavaElement) field).resolved(fieldBinding),
                        SearchMatch.A_ACCURATE, offset, fieldDecl.sourceEnd - offset + 1,
                        locator.getParticipant(), resource);
                locator.report(this.match);
            }
        }
    }
}

From source file:com.codenvy.ide.ext.java.server.internal.core.SourceMapper.java

License:Open Source License

/**
 * @see org.eclipse.jdt.internal.compiler.ISourceElementRequestor
 *///  w  ww  . j a v a  2s  .  c  o  m
public void enterField(FieldInfo fieldInfo) {
    if (this.typeDepth >= 0) {
        this.memberDeclarationStart[this.typeDepth] = fieldInfo.declarationStart;
        this.memberNameRange[this.typeDepth] = new SourceRange(fieldInfo.nameSourceStart,
                fieldInfo.nameSourceEnd - fieldInfo.nameSourceStart + 1);
        String fieldName = new String(fieldInfo.name);
        this.memberName[this.typeDepth] = fieldName;

        // categories
        IType currentType = this.types[this.typeDepth];
        IField field = currentType.getField(fieldName);
        addCategories(field, fieldInfo.categories);
    }
}